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": "keke.com')).toBeFalsy()\n\n it 'should succeed on \"keke@keke.com\"', () ->\n helper.link()\n expect(helper.vali", "end": 563, "score": 0.9997132420539856, "start": 550, "tag": "EMAIL", "value": "keke@keke.com" }, { "context": " ->\n helper.link()\n expect(helper.validate('keke@keke.com')).toBeTruthy()\n\n\n", "end": 632, "score": 0.9991912245750427, "start": 619, "tag": "EMAIL", "value": "keke@keke.com" } ]
src/tests/validators/email.spec.coffee
SteefTheBeef/angular-validate
0
describe 'Email Test', () -> helper = new ValidatorTestHelper() helper.beforeEach('email') it 'should fail on "keke"', () -> helper.link() expect(helper.validate('keke')).toBeFalsy() it 'should fail on "keke@"', () -> helper.link() expect(helper.validate('keke@')).toBeFalsy() it 'should fail on "keke.@."', () -> helper.link() expect(helper.validate('keke.@.')).toBeFalsy() it 'should fail on "keke.com"', () -> helper.link() expect(helper.validate('keke.com')).toBeFalsy() it 'should succeed on "keke@keke.com"', () -> helper.link() expect(helper.validate('keke@keke.com')).toBeTruthy()
217792
describe 'Email Test', () -> helper = new ValidatorTestHelper() helper.beforeEach('email') it 'should fail on "keke"', () -> helper.link() expect(helper.validate('keke')).toBeFalsy() it 'should fail on "keke@"', () -> helper.link() expect(helper.validate('keke@')).toBeFalsy() it 'should fail on "keke.@."', () -> helper.link() expect(helper.validate('keke.@.')).toBeFalsy() it 'should fail on "keke.com"', () -> helper.link() expect(helper.validate('keke.com')).toBeFalsy() it 'should succeed on "<EMAIL>"', () -> helper.link() expect(helper.validate('<EMAIL>')).toBeTruthy()
true
describe 'Email Test', () -> helper = new ValidatorTestHelper() helper.beforeEach('email') it 'should fail on "keke"', () -> helper.link() expect(helper.validate('keke')).toBeFalsy() it 'should fail on "keke@"', () -> helper.link() expect(helper.validate('keke@')).toBeFalsy() it 'should fail on "keke.@."', () -> helper.link() expect(helper.validate('keke.@.')).toBeFalsy() it 'should fail on "keke.com"', () -> helper.link() expect(helper.validate('keke.com')).toBeFalsy() it 'should succeed on "PI:EMAIL:<EMAIL>END_PI"', () -> helper.link() expect(helper.validate('PI:EMAIL:<EMAIL>END_PI')).toBeTruthy()
[ { "context": "(element) ->\n super\n @name = ko.observable('World')\n", "end": 273, "score": 0.7235448956489563, "start": 268, "tag": "NAME", "value": "World" } ]
client/components/home-page/index.coffee
ryansolid/component-ko-example
0
ko = require 'knockout' Component = require 'component-register-ko' module.exports = class HomePage extends Component @tag: 'home-page', @template: require './template' @styles: require './styles' constructor: (element) -> super @name = ko.observable('World')
160375
ko = require 'knockout' Component = require 'component-register-ko' module.exports = class HomePage extends Component @tag: 'home-page', @template: require './template' @styles: require './styles' constructor: (element) -> super @name = ko.observable('<NAME>')
true
ko = require 'knockout' Component = require 'component-register-ko' module.exports = class HomePage extends Component @tag: 'home-page', @template: require './template' @styles: require './styles' constructor: (element) -> super @name = ko.observable('PI:NAME:<NAME>END_PI')
[ { "context": "R = if LOCAL then \"http://localhost\" else \"http://50.116.7.184\"\n\nwindow.socket = socket = io.connect SERVER\n\nper", "end": 67, "score": 0.9825966954231262, "start": 55, "tag": "IP_ADDRESS", "value": "50.116.7.184" }, { "context": ".latitude, lng: position.coords.longitude, name: 'test'}\n \n # TODO: Handle denials, in the cas", "end": 798, "score": 0.7970427870750427, "start": 794, "tag": "USERNAME", "value": "test" } ]
src/client.coffee
feross/Fling
13
SERVER = if LOCAL then "http://localhost" else "http://50.116.7.184" window.socket = socket = io.connect SERVER percentOfHeight = (percent) -> $(window).height() * (percent / 100) percentOfWidth = (percent) -> $(window).width() * (percent / 100) playWhoosh = -> $('body').append '<audio preload="auto" autoplay><source src="/static/sound/whoosh.mp3" /><source src="/static/sound/whoosh.ogg" /></audio>' $(document).ready -> $('#frisbee-button').click -> socket.emit 'frisbee', {lat: 5, lng: 5} navigator.geolocation.getCurrentPosition (position) -> console.log(position.coords.latitude, position.coords.longitude) # TODO: ask the user for their name socket.emit 'id', {lat: position.coords.latitude, lng: position.coords.longitude, name: 'test'} # TODO: Handle denials, in the case of denial, just fail handleData = (data) -> {type, content} = data switch type when "url" a = $("<iframe src='#{content}'></iframe>") a.css width: percentOfWidth(100) - 100, height: percentOfHeight(100) - 100 when "youtube" time = if data.time then data.time else "" a = $("<iframe src='http://www.youtube.com/embed/#{content}?autoplay=1\#t=#{time}' style='background-color: #fff' frameborder='0' autoplay=true allowfullscreen></iframe>") a.css width: percentOfWidth(100) - 100, height: percentOfHeight(100) - 100 when "image" $("body").append $("<img src='#{content}'></img>") when "spotify" document.location = "spotify:track:#{content}" else alert("Unknown") return a.hide() a.appendTo('.content') a.fadeIn('slow') socket.on 'frisbee', (data) -> console.log data throwFrisbee -> handleData data throwFrisbee = window.throwFrisbee = (cb) -> if !$('.content').length $("body").append $('<div>', class: 'content') else $('.content').empty() $('.swoosh').fadeOut().remove() oldFrisbee = $ '.frisbee' animateFrisbee = -> oldFrisbee.remove() playWhoosh() frisbee = $ '<div>', class: 'frisbee frisbeeContent' frisbee.css left: 145, bottom: 137, width: 50, height: 29 frisbee.appendTo '#fixed' frisbee.animate width: percentOfWidth(150), height: percentOfHeight(150), duration: 1500 easing: 'linear' queue: false frisbee.animate {left: percentOfWidth(75), bottom: percentOfHeight(45)}, 750, 'easeOutQuad' frisbee.animate {left: percentOfWidth(-25), bottom: percentOfHeight(-25)}, 750, 'easeInOutQuad', -> cb() if oldFrisbee.length is 0 animateFrisbee() else if oldFrisbee.hasClass('frisbeeContent') oldFrisbee.fadeOut animateFrisbee else oldFrisbee.animate left: -300, 1000, 'easeInOutQuad', animateFrisbee showSwoosh = -> swoosh = $ '<img>', class: 'swoosh', src: '/static/img/swoosh.png' swoosh.css left: 100, bottom: 150, width: percentOfWidth(75), height: percentOfHeight(60) - 50, opacity: 0 swoosh.appendTo '#fixed' swoosh.animate opacity: 1, 500, 'linear' # icons = ['music', 'video', 'article'] # for type in icons # icon = $ '<div>', class: type # icon throwLogoFrisbee = (frisbee) -> kid2 = $ '<div>', class: 'kid2' kid2.css right: -50, bottom: 50 kid2.appendTo '#fixed' kid2.animate right: 75, 250 frisbee.animate width: 249, height: 145, duration: 2500 easing: 'linear' queue: false frisbee.animate {left: percentOfWidth(75), bottom: percentOfHeight(45)}, 1250, 'easeOutQuad' frisbee.animate {left: percentOfWidth(25), bottom: percentOfHeight(60)}, 1250, 'easeInOutQuad', -> showSwoosh() createCloud = -> cloudNum = Math.floor(Math.random()*3) + 1 cloudTop = Math.floor(Math.random()*200) + 1 cloud = $ '<div>', class: 'cloud'+cloudNum cloud.css left: $(window).width(), top: cloudTop cloud.appendTo '#fixed' cloud.animate {left: -250}, 60000, 'linear', -> cloud.remove() performYTSearch = (s, cb) -> $.ajax dataType: 'jsonp' type: 'GET' url: "http://gdata.youtube.com/feeds/api/videos?q=#{ encodeURIComponent(s) }" + "&format=5&v=2&alt=jsonc" + # Force embeddable vids (format=5) "&max-results=1" success: (responseData, textStatus, XMLHttpRequest) => if videoId = responseData?.data?.items?[0].id cb (videoId) startAnimation = -> createCloud() window.setInterval -> createCloud() , 15000 kid1 = $ '<div>', class: 'kid1' kid1.css left: -50, bottom: 50 kid1.appendTo '#fixed' frisbee = $ '<img>', class: 'frisbeeLogo frisbee', src: '/static/img/frisbee-logo.png' frisbee.css left: 20, bottom: 137, width: 50, height: 29 frisbee.appendTo '#fixed' time = 500 kid1.animate left: 75, time frisbee.animate left: 145, bottom: 137, time, -> window.setTimeout -> throwLogoFrisbee(frisbee) , 200 $ -> search = window.location.search if search YT_SEARCH = ///youtube=([^&]*)/// result = YT_SEARCH.exec search s = result[1] s = s.replace(',', ' ') YT_TIME = ///time=([^&]*)/// result = YT_TIME.exec search time = result[1] console.log 'hey' performYTSearch s, (videoId) -> throwFrisbee -> handleData type: 'youtube', content: videoId, time: time else startAnimation()
128505
SERVER = if LOCAL then "http://localhost" else "http://192.168.127.12" window.socket = socket = io.connect SERVER percentOfHeight = (percent) -> $(window).height() * (percent / 100) percentOfWidth = (percent) -> $(window).width() * (percent / 100) playWhoosh = -> $('body').append '<audio preload="auto" autoplay><source src="/static/sound/whoosh.mp3" /><source src="/static/sound/whoosh.ogg" /></audio>' $(document).ready -> $('#frisbee-button').click -> socket.emit 'frisbee', {lat: 5, lng: 5} navigator.geolocation.getCurrentPosition (position) -> console.log(position.coords.latitude, position.coords.longitude) # TODO: ask the user for their name socket.emit 'id', {lat: position.coords.latitude, lng: position.coords.longitude, name: 'test'} # TODO: Handle denials, in the case of denial, just fail handleData = (data) -> {type, content} = data switch type when "url" a = $("<iframe src='#{content}'></iframe>") a.css width: percentOfWidth(100) - 100, height: percentOfHeight(100) - 100 when "youtube" time = if data.time then data.time else "" a = $("<iframe src='http://www.youtube.com/embed/#{content}?autoplay=1\#t=#{time}' style='background-color: #fff' frameborder='0' autoplay=true allowfullscreen></iframe>") a.css width: percentOfWidth(100) - 100, height: percentOfHeight(100) - 100 when "image" $("body").append $("<img src='#{content}'></img>") when "spotify" document.location = "spotify:track:#{content}" else alert("Unknown") return a.hide() a.appendTo('.content') a.fadeIn('slow') socket.on 'frisbee', (data) -> console.log data throwFrisbee -> handleData data throwFrisbee = window.throwFrisbee = (cb) -> if !$('.content').length $("body").append $('<div>', class: 'content') else $('.content').empty() $('.swoosh').fadeOut().remove() oldFrisbee = $ '.frisbee' animateFrisbee = -> oldFrisbee.remove() playWhoosh() frisbee = $ '<div>', class: 'frisbee frisbeeContent' frisbee.css left: 145, bottom: 137, width: 50, height: 29 frisbee.appendTo '#fixed' frisbee.animate width: percentOfWidth(150), height: percentOfHeight(150), duration: 1500 easing: 'linear' queue: false frisbee.animate {left: percentOfWidth(75), bottom: percentOfHeight(45)}, 750, 'easeOutQuad' frisbee.animate {left: percentOfWidth(-25), bottom: percentOfHeight(-25)}, 750, 'easeInOutQuad', -> cb() if oldFrisbee.length is 0 animateFrisbee() else if oldFrisbee.hasClass('frisbeeContent') oldFrisbee.fadeOut animateFrisbee else oldFrisbee.animate left: -300, 1000, 'easeInOutQuad', animateFrisbee showSwoosh = -> swoosh = $ '<img>', class: 'swoosh', src: '/static/img/swoosh.png' swoosh.css left: 100, bottom: 150, width: percentOfWidth(75), height: percentOfHeight(60) - 50, opacity: 0 swoosh.appendTo '#fixed' swoosh.animate opacity: 1, 500, 'linear' # icons = ['music', 'video', 'article'] # for type in icons # icon = $ '<div>', class: type # icon throwLogoFrisbee = (frisbee) -> kid2 = $ '<div>', class: 'kid2' kid2.css right: -50, bottom: 50 kid2.appendTo '#fixed' kid2.animate right: 75, 250 frisbee.animate width: 249, height: 145, duration: 2500 easing: 'linear' queue: false frisbee.animate {left: percentOfWidth(75), bottom: percentOfHeight(45)}, 1250, 'easeOutQuad' frisbee.animate {left: percentOfWidth(25), bottom: percentOfHeight(60)}, 1250, 'easeInOutQuad', -> showSwoosh() createCloud = -> cloudNum = Math.floor(Math.random()*3) + 1 cloudTop = Math.floor(Math.random()*200) + 1 cloud = $ '<div>', class: 'cloud'+cloudNum cloud.css left: $(window).width(), top: cloudTop cloud.appendTo '#fixed' cloud.animate {left: -250}, 60000, 'linear', -> cloud.remove() performYTSearch = (s, cb) -> $.ajax dataType: 'jsonp' type: 'GET' url: "http://gdata.youtube.com/feeds/api/videos?q=#{ encodeURIComponent(s) }" + "&format=5&v=2&alt=jsonc" + # Force embeddable vids (format=5) "&max-results=1" success: (responseData, textStatus, XMLHttpRequest) => if videoId = responseData?.data?.items?[0].id cb (videoId) startAnimation = -> createCloud() window.setInterval -> createCloud() , 15000 kid1 = $ '<div>', class: 'kid1' kid1.css left: -50, bottom: 50 kid1.appendTo '#fixed' frisbee = $ '<img>', class: 'frisbeeLogo frisbee', src: '/static/img/frisbee-logo.png' frisbee.css left: 20, bottom: 137, width: 50, height: 29 frisbee.appendTo '#fixed' time = 500 kid1.animate left: 75, time frisbee.animate left: 145, bottom: 137, time, -> window.setTimeout -> throwLogoFrisbee(frisbee) , 200 $ -> search = window.location.search if search YT_SEARCH = ///youtube=([^&]*)/// result = YT_SEARCH.exec search s = result[1] s = s.replace(',', ' ') YT_TIME = ///time=([^&]*)/// result = YT_TIME.exec search time = result[1] console.log 'hey' performYTSearch s, (videoId) -> throwFrisbee -> handleData type: 'youtube', content: videoId, time: time else startAnimation()
true
SERVER = if LOCAL then "http://localhost" else "http://PI:IP_ADDRESS:192.168.127.12END_PI" window.socket = socket = io.connect SERVER percentOfHeight = (percent) -> $(window).height() * (percent / 100) percentOfWidth = (percent) -> $(window).width() * (percent / 100) playWhoosh = -> $('body').append '<audio preload="auto" autoplay><source src="/static/sound/whoosh.mp3" /><source src="/static/sound/whoosh.ogg" /></audio>' $(document).ready -> $('#frisbee-button').click -> socket.emit 'frisbee', {lat: 5, lng: 5} navigator.geolocation.getCurrentPosition (position) -> console.log(position.coords.latitude, position.coords.longitude) # TODO: ask the user for their name socket.emit 'id', {lat: position.coords.latitude, lng: position.coords.longitude, name: 'test'} # TODO: Handle denials, in the case of denial, just fail handleData = (data) -> {type, content} = data switch type when "url" a = $("<iframe src='#{content}'></iframe>") a.css width: percentOfWidth(100) - 100, height: percentOfHeight(100) - 100 when "youtube" time = if data.time then data.time else "" a = $("<iframe src='http://www.youtube.com/embed/#{content}?autoplay=1\#t=#{time}' style='background-color: #fff' frameborder='0' autoplay=true allowfullscreen></iframe>") a.css width: percentOfWidth(100) - 100, height: percentOfHeight(100) - 100 when "image" $("body").append $("<img src='#{content}'></img>") when "spotify" document.location = "spotify:track:#{content}" else alert("Unknown") return a.hide() a.appendTo('.content') a.fadeIn('slow') socket.on 'frisbee', (data) -> console.log data throwFrisbee -> handleData data throwFrisbee = window.throwFrisbee = (cb) -> if !$('.content').length $("body").append $('<div>', class: 'content') else $('.content').empty() $('.swoosh').fadeOut().remove() oldFrisbee = $ '.frisbee' animateFrisbee = -> oldFrisbee.remove() playWhoosh() frisbee = $ '<div>', class: 'frisbee frisbeeContent' frisbee.css left: 145, bottom: 137, width: 50, height: 29 frisbee.appendTo '#fixed' frisbee.animate width: percentOfWidth(150), height: percentOfHeight(150), duration: 1500 easing: 'linear' queue: false frisbee.animate {left: percentOfWidth(75), bottom: percentOfHeight(45)}, 750, 'easeOutQuad' frisbee.animate {left: percentOfWidth(-25), bottom: percentOfHeight(-25)}, 750, 'easeInOutQuad', -> cb() if oldFrisbee.length is 0 animateFrisbee() else if oldFrisbee.hasClass('frisbeeContent') oldFrisbee.fadeOut animateFrisbee else oldFrisbee.animate left: -300, 1000, 'easeInOutQuad', animateFrisbee showSwoosh = -> swoosh = $ '<img>', class: 'swoosh', src: '/static/img/swoosh.png' swoosh.css left: 100, bottom: 150, width: percentOfWidth(75), height: percentOfHeight(60) - 50, opacity: 0 swoosh.appendTo '#fixed' swoosh.animate opacity: 1, 500, 'linear' # icons = ['music', 'video', 'article'] # for type in icons # icon = $ '<div>', class: type # icon throwLogoFrisbee = (frisbee) -> kid2 = $ '<div>', class: 'kid2' kid2.css right: -50, bottom: 50 kid2.appendTo '#fixed' kid2.animate right: 75, 250 frisbee.animate width: 249, height: 145, duration: 2500 easing: 'linear' queue: false frisbee.animate {left: percentOfWidth(75), bottom: percentOfHeight(45)}, 1250, 'easeOutQuad' frisbee.animate {left: percentOfWidth(25), bottom: percentOfHeight(60)}, 1250, 'easeInOutQuad', -> showSwoosh() createCloud = -> cloudNum = Math.floor(Math.random()*3) + 1 cloudTop = Math.floor(Math.random()*200) + 1 cloud = $ '<div>', class: 'cloud'+cloudNum cloud.css left: $(window).width(), top: cloudTop cloud.appendTo '#fixed' cloud.animate {left: -250}, 60000, 'linear', -> cloud.remove() performYTSearch = (s, cb) -> $.ajax dataType: 'jsonp' type: 'GET' url: "http://gdata.youtube.com/feeds/api/videos?q=#{ encodeURIComponent(s) }" + "&format=5&v=2&alt=jsonc" + # Force embeddable vids (format=5) "&max-results=1" success: (responseData, textStatus, XMLHttpRequest) => if videoId = responseData?.data?.items?[0].id cb (videoId) startAnimation = -> createCloud() window.setInterval -> createCloud() , 15000 kid1 = $ '<div>', class: 'kid1' kid1.css left: -50, bottom: 50 kid1.appendTo '#fixed' frisbee = $ '<img>', class: 'frisbeeLogo frisbee', src: '/static/img/frisbee-logo.png' frisbee.css left: 20, bottom: 137, width: 50, height: 29 frisbee.appendTo '#fixed' time = 500 kid1.animate left: 75, time frisbee.animate left: 145, bottom: 137, time, -> window.setTimeout -> throwLogoFrisbee(frisbee) , 200 $ -> search = window.location.search if search YT_SEARCH = ///youtube=([^&]*)/// result = YT_SEARCH.exec search s = result[1] s = s.replace(',', ' ') YT_TIME = ///time=([^&]*)/// result = YT_TIME.exec search time = result[1] console.log 'hey' performYTSearch s, (videoId) -> throwFrisbee -> handleData type: 'youtube', content: videoId, time: time else startAnimation()
[ { "context": " autoassign : false\n key : \"is_proxy_rule\"\n id_touch_list\n ast\n ", "end": 18601, "score": 0.874885082244873, "start": 18588, "tag": "KEY", "value": "is_proxy_rule" }, { "context": " for i in [0 ... last_id]\n key = \"__arg_#{i}\"\n # p \"key=#{key}\"\n ", "end": 19741, "score": 0.9973506331443787, "start": 19729, "tag": "KEY", "value": "\"__arg_#{i}\"" }, { "context": " else\n if v.key == \"__arg_0\" and rule.sequence.length == 3\n ", "end": 20576, "score": 0.7557905912399292, "start": 20575, "tag": "KEY", "value": "0" }, { "context": " }\n else if v.key == \"__arg_1\" and rule.sequence.length == 3\n ", "end": 20926, "score": 0.697698175907135, "start": 20926, "tag": "KEY", "value": "" }, { "context": " break\n \n pass_hash_key = \"proxy_#{head_rule.sequence.join(',')}_#{uid++}\"\n ", "end": 22784, "score": 0.9710308909416199, "start": 22776, "tag": "KEY", "value": "proxy_#{" }, { "context": "s_hash_key = \"proxy_#{head_rule.sequence.join(',')}_#{uid++}\"\n head_rule.ret_hash_key = pass_", "end": 22816, "score": 0.9781731963157654, "start": 22814, "tag": "KEY", "value": "#{" }, { "context": "key = \"proxy_#{head_rule.sequence.join(',')}_#{uid++}\"\n head_rule.ret_hash_key = pass_hash_", "end": 22819, "score": 0.7278755307197571, "start": 22819, "tag": "KEY", "value": "" } ]
src/rule.coffee
hu2prod/gram2
0
# BUG hash_to_pos для head/tail правил отсутствует module = @ require 'fy/lib/codegen' {Node} = require './node' {explicit_list_generator} = require './explicit_list_generator' # ################################################################################################### # tokenizer # ################################################################################################### {Tokenizer, Token_parser} = require 'gram' tokenizer = new Tokenizer tokenizer.parser_list.push (new Token_parser 'dollar_id', /^\$[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'hash_id', /^\#[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'pass_id', /^\@[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'id', /^[_a-z][_a-z0-9]*/i) tokenizer.parser_list.push (new Token_parser '_bin_op', /// ^ ( (&&?|\|\|?|[-+*/])| <>|[<>!=]=|<|> ) ///) tokenizer.parser_list.push (new Token_parser '_pre_op', /^!/) # tokenizer.parser_list.push (new Token_parser 'assign_bin_op', /^(&&?|\|\|?|[-+])?=/) tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/) tokenizer.parser_list.push (new Token_parser 'delimiter', /^[:.]/) string_regex_craft = /// \\[^xu] | # x and u are case sensitive while hex letters are not \\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence \\u(?: [0-9a-fA-F]{4} | # Unicode escape sequence \{(?: [0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF 10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF )\} ) ///.toString().replace(/\//g,'') single_quoted_regex_craft = /// (?: [^\\] | #{string_regex_craft} )*? ///.toString().replace(/\//g,'') tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///) double_quoted_regexp_craft = /// (?: [^\\#] | \#(?!\{) | #{string_regex_craft} )*? ///.toString().replace(/\//g,'') tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///) tokenizer.parser_list.push (new Token_parser 'number', /^[0-9]+/) # ################################################################################################### # gram # ################################################################################################### base_priority = -9000 {Gram} = require 'gram' gram = new Gram q = (a, b)->gram.rule a,b q('pre_op', '!') .mx('priority=1') q('pre_op', '-') .mx('priority=1') q('pre_op', '+') .mx('priority=1') q('bin_op', '*|/') .mx('priority=5 right_assoc=1') q('bin_op', '+|-') .mx('priority=6 right_assoc=1') q('bin_op', '<|<=|>|>=|!=|<>|==') .mx('priority=9') q('bin_op', '&|&&|and|or|[PIPE]|[PIPE][PIPE]') .mx('priority=10 right_assoc=1') q('access_rvalue', '#dollar_id') .mx("priority=#{base_priority} ult=dollar_id") q('access_rvalue', '#hash_id') .mx("priority=#{base_priority} ult=hash_id") q('rvalue', '#access_rvalue') .mx("priority=#{base_priority} ult=access_rvalue") q('rvalue', '#pass_id') .mx("priority=#{base_priority} ult=dollar_id") q('rvalue', '#number') .mx("priority=#{base_priority} ult=value") q('rvalue', '#id') .mx("priority=#{base_priority} ult=wrap_string") q('rvalue', '#string_literal_singleq') .mx("priority=#{base_priority} ult=value") q('rvalue', '#string_literal_doubleq') .mx("priority=#{base_priority} ult=value") q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority<#bin_op.priority #rvalue[2].priority<#bin_op.priority') # q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority<#bin_op.priority #rvalue[2].priority=#bin_op.priority #bin_op.left_assoc') q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority=#bin_op.priority #rvalue[2].priority<#bin_op.priority #bin_op.right_assoc') q('rvalue', '#pre_op #rvalue') .mx('priority=#pre_op.priority ult=pre_op') .strict('#rvalue[1].priority<=#pre_op.priority') q('rvalue', '( #rvalue )') .mx("priority=#{base_priority} ult=deep") q('access_rvalue', '#hash_id [ #rvalue ]') .mx("priority=#{base_priority} ult=hash_array_access") q('rvalue', '#access_rvalue [ #number : #number ]') .mx("priority=#{base_priority} ult=slice_access") # . access q('rvalue', '#access_rvalue . #id') .mx("priority=#{base_priority} ult=field_access") q('strict_rule', '#rvalue') .mx("ult=deep") # ################################################################################################### # trans # ################################################################################################### { Translator bin_op_translator_framework bin_op_translator_holder un_op_translator_framework un_op_translator_holder } = require 'gram' trans = new Translator trans.trans_skip = {} trans.trans_token = {} deep = (ctx, node)-> list = [] # if node.mx_hash.deep? # node.mx_hash.deep = '0' if node.mx_hash.deep == false # special case for deep=0 # value_array = (node.value_array[pos] for pos in node.mx_hash.deep.split ',') # else # value_array = node.value_array value_array = node.value_array for v,k in value_array list.push ctx.translate v list # ################################################################################################### do ()-> holder = new bin_op_translator_holder for v in bin_op_list = "+ - * / && ||".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" # SPECIAL holder.op_list["&"] = new bin_op_translator_framework "($1&&$2)" holder.op_list["|"] = new bin_op_translator_framework "($1||$2)" holder.op_list["<>"] = new bin_op_translator_framework "($1!=$2)" for v in bin_op_list = "== != < <= > >=".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" trans.translator_hash['bin_op'] = holder do ()-> holder = new un_op_translator_holder holder.mode_pre() for v in un_op_list = "+ - !".split ' ' holder.op_list[v] = new un_op_translator_framework "$op$1" trans.translator_hash['pre_op'] = holder # ################################################################################################### trans.translator_hash['deep'] = translate:(ctx, node)-> list = deep ctx, node list.join('') trans.translator_hash['value'] = translate:(ctx, node)->node.value trans.translator_hash['wrap_string'] = translate:(ctx, node)->JSON.stringify node.value trans.translator_hash['dollar_id'] = translate:(ctx, node)-> idx = (node.value.substr 1)-1 if idx < 0 or idx >= ctx.rule.sequence.length throw new Error "strict_rule access out of bounds [0, #{ctx.rule.sequence.length}] idx=#{idx} (note real value are +1)" node.mx_hash.idx = idx ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['hash_id'] = translate:(ctx, node)-> name = node.value.substr 1 if !idx_list = ctx.rule.hash_to_pos[name] throw new Error "unknown hash_key '#{name}' allowed key list #{JSON.stringify Object.keys(ctx.rule.hash_to_pos)}" node.mx_hash.idx = idx = idx_list[0] ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['access_rvalue'] = translate:(ctx, node)-> code = ctx.translate node.value_array[0] "#{code}.value" trans.translator_hash['hash_array_access'] = translate:(ctx, node)-> [id_node, _s, idx_node] = node.value_array name = id_node.value.substr 1 if !idx_list = ctx.rule.hash_to_pos[name] throw new Error "unknown hash_key '#{name}' allowed key list #{JSON.stringify Object.keys(ctx.rule.hash_to_pos)}" idx = idx_node.value-1 if idx < 0 or idx >= idx_list.length throw new Error "hash_array_access out of bounds [0, #{idx_list.length}] idx=#{idx} (note real value are +1)" node.mx_hash.idx = idx = idx_list[idx] ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['slice_access'] = translate:(ctx, node)-> [rvalue_node, _s, start_node, _s, end_node] = node.value_array rvalue = ctx.translate rvalue_node start = +start_node.value end = +end_node.value if end < start throw new Error "end < start at #{node.value}" "#{rvalue}.value.substr(#{start},#{end-start+1})" trans.translator_hash['field_access'] = translate:(ctx, node)-> [root_node, _s, field_node] = node.value_array root = ctx.translate root_node field = field_node.value "#{root}.mx_hash.#{field}" # ################################################################################################### # Gram_rule # ################################################################################################### class @Gram_rule hash_to_pos : {} ret_hash_key: '' ret_hash_key_idx: 0 sequence : [] mx_sequence : [] strict_sequence : [] mx_rule_fn : (arg_list)->{} # default pass strict_rule_fn: (arg_list)->true # default pass # TODO loop wrap constructor : ()-> @hash_to_pos = {} @sequence = [] @mx_sequence = [] @strict_sequence= [] cmp_seq : (t)-> return @sequence.join() == t.sequence.join() # ################################################################################################### # mx # ################################################################################################### mx : (str)-> pos_list = str.split /\s+/g @mx_sequence = [] code_jl = [] for pos in pos_list continue if !pos [key, value] = pos.split `/=/` if !value # autoassign case if @sequence.length != 1 throw new Error "can't autoassign if sequence.length(#{@sequence.length}) != 1" @mx_sequence.push { autoassign : true key id_touch_list : null ast : null } continue {id_touch_list, ast} = @_strict_pos_parse value @mx_sequence.push { autoassign : false key id_touch_list ast } return _mx : ()-> code_jl = [] for v in @mx_sequence {key} = v if v.autoassign code_jl.push """ mx_hash_stub[#{JSON.stringify key}] = arg_list[0].mx_hash[#{JSON.stringify key}]; """ else trans.rule = @ trans.id_touch_list = [] code = trans.go v.ast code_jl.push """ mx_hash_stub[#{JSON.stringify key}] = #{code}; """ @mx_rule_fn = eval """ __ret = (function(arg_list, mx_hash_stub){ #{join_list code_jl, ' '} }) """ return cmp_mx : (t)-> return false if @mx_sequence.length != t.mx_sequence.length for v1,idx in @mx_sequence v2 = t.mx_sequence[idx] return false if v1.autoassign != v2.autoassign return false if v1.key != v2.key return false if v1.id_touch_list.join() != v2.id_touch_list.join() return false if v1.ast.value != v2.ast.value # !!! DANGER !!! true # ################################################################################################### # strict # ################################################################################################### strict : (str)-> pos_list = str.split /\s+/g @strict_sequence = [] for pos in pos_list continue if !pos {id_touch_list, ast} = @_strict_pos_parse pos @strict_sequence.push { id_touch_list ast } return _strict : ()-> code_jl = [] for pos,idx in @sequence continue if pos[0] == "#" code_jl.push """ if (arg_list[#{idx}].value != #{JSON.stringify pos}) return false; """ for v in @strict_sequence trans.rule = @ trans.id_touch_list = [] code = trans.go v.ast code_jl.push """ if (!(#{code})) return false; """ @strict_rule_fn = eval """ __ret = (function(arg_list){ #{join_list code_jl, ' '} return true; }) """ cmp_strict : (t)-> return false if @strict_sequence.length != t.strict_sequence.length for v1,idx in @strict_sequence v2 = t.strict_sequence[idx] return false if v1.id_touch_list.join() != v2.id_touch_list.join() return false if v1.ast.value != v2.ast.value # !!! DANGER !!! true _strict_pos_parse : (str)-> tok_list = tokenizer.go str gram.mode_full = true ast = gram.parse_text_list tok_list, expected_token : 'strict_rule' if ast.length == 0 throw new Error "Parsing error. No proper combination found" if ast.length != 1 # [a,b] = ast # show_diff a,b ### !pragma coverage-skip-block ### throw new Error "Parsing error. More than one proper combination found #{ast.length}" trans.rule = @ trans.id_touch_list = [] code = trans.go ast[0] { code id_touch_list : trans.id_touch_list ast : ast[0] } # unused # cmp : (t)-> # return false if @ret_hash_key != t.ret_hash_key # return false if !@cmp_seq(t) # return false if !@cmp_mx(t) # return false if !@cmp_strict(t) # return _head_cmp : (t)-> return false if @ret_hash_key != t.ret_hash_key return false if !@cmp_seq(t) return false if !@cmp_mx(t) return false if !@cmp_strict(t) true class @Gram_rule_proxy rule_list : [] constructor:()-> @rule_list = [] mx : (str)-> for rule in @rule_list rule.mx str @ strict : (str)-> for rule in @rule_list rule.strict str @ # ################################################################################################### # Gram # ################################################################################################### str_replace = (search, replace, str)-> str.split(search).join(replace) @gram_escape= (v) -> v = str_replace '|', '[PIPE]', v v = str_replace '?', '[QUESTION]', v v = str_replace '$', '[DOLLAR]', v v = str_replace '#', '[HASH]', v @gram_unescape= (v) -> v = str_replace '[PIPE]', '|', v v = str_replace '[QUESTION]','?', v v = str_replace '[DOLLAR]', '$', v # нужно в случае конструкций ${}, когда нельзя отделить $ от токена v = str_replace '[HASH]', '#', v class @Gram @magic_attempt_limit_mult : 20 initial_rule_list : [] hash_key_list : [] extra_hash_key_list : [] _optimized : false # Array<Array<Node> > # hki = hash_key_idx # a_pos = left token bound position # b_pos = right token bound position t_hki_a_pos_old_list : [] t_hki_a_pos_new_list : [] t_hki_b_pos_old_list : [] t_hki_b_pos_new_list : [] new_new_list : [] constructor:()-> @initial_rule_list = [] @hash_key_list = [] @extra_hash_key_list = [] @t_hki_a_pos_old_list = [] @t_hki_a_pos_new_list = [] @t_hki_b_pos_old_list = [] @t_hki_b_pos_new_list = [] @new_new_list = [] rule : (_ret, str_list)-> @_optimized = false ret = new module.Gram_rule_proxy hash_to_pos = {} pos_list_list = [] for chunk,idx in chunk_list = str_list.split /\s+/g list = chunk.split '|' if list.length > 1 # NOTE positions not allowed, only const for v,k in list if v[0] == '#' throw new Error "#positions + | not allowed" list[k] = module.gram_unescape v pos_list_list.push list continue if chunk[0] == "#" id = chunk.substr 1 id = module.gram_unescape id hash_to_pos[id] ?= [] hash_to_pos[id].push idx if /\?$/.test chunk chunk = chunk.substr 0, chunk.length-1 chunk = module.gram_unescape chunk pos_list_list.push [chunk, null] continue chunk = module.gram_unescape chunk pos_list_list.push [chunk] pos_list_list2 = explicit_list_generator pos_list_list for sequence in pos_list_list2 id_mapping = {} sequence_filtered = [] dst = 0 for v,idx in sequence continue if !v? id_mapping[idx] = dst++ sequence_filtered.push v continue if sequence_filtered.length == 0 rule = new module.Gram_rule rule.ret_hash_key = _ret for k,v of hash_to_pos rule.hash_to_pos[k] = v.map (t)->id_mapping[t] rule.sequence = sequence_filtered rule.strict('') # reinit strict_rule_fn by sequence in case strict will not be called at all @initial_rule_list.push rule ret.rule_list.push rule ret rule_1_by_arg : [] rule_2_by_arg : [] optimize : ()-> @_optimized = true synth_rule_list = [] uid = 0 proxy = new module.Gram_rule proxy.sequence = ['STUB', 'STUB'] replace_id_access = (tree, skip_id)-> search_idx = tree.mx_hash.idx if search_idx? if search_idx != skip_id {ast} = proxy._strict_pos_parse "$1.__arg_#{search_idx}" return ast else # $2 # #a # #a[2] {ast} = proxy._strict_pos_parse "@2" return ast list = tree.value_array for v,k in list list[k] = replace_id_access v, skip_id tree for rule in @initial_rule_list switch rule.sequence.length when 1,2 found = false for _rule in synth_rule_list if rule._head_cmp _rule found = _rule break if !found synth_rule_list.push rule else found = null while rule.sequence.length > 2 head_rule = new module.Gram_rule tail_rule = new module.Gram_rule {ast, id_touch_list} = proxy._strict_pos_parse "1" tail_rule.mx_sequence.push { autoassign : false key : "is_proxy_rule" id_touch_list ast } tail_rule.ret_hash_key = rule.ret_hash_key head_rule.hash_to_pos = rule.hash_to_pos # дабы не сломалось ничего. _max_idx = rule.sequence.length-1 for k,list of rule.hash_to_pos v = list.last() if v == _max_idx tail_rule.hash_to_pos[k] ?= [] tail_rule.hash_to_pos[k].push 1 # а остальных быть не может т.к. strict rule будет переписано и все остальные позиции будут через @ head_rule.sequence = rule.sequence.clone() last = head_rule.sequence.pop() tail_rule.sequence = ['REPLACE_ME', last] last_id = head_rule.sequence.length # mx отдувается за всех. Ему нужно пробросить всё head_filled_with_mx_pass = false fill_head = ()-> if !head_filled_with_mx_pass head_filled_with_mx_pass = true for i in [0 ... last_id] key = "__arg_#{i}" # p "key=#{key}" {ast, id_touch_list} = head_rule._strict_pos_parse "@#{i+1}" head_rule.mx_sequence.push { autoassign : false key id_touch_list ast } return for v in rule.mx_sequence if v.autoassign # DEBUG ONLY throw new Error "WTF" if v.id_touch_list.has last_id if v.id_touch_list.length == 1 tail_rule.mx_sequence.push v else # PROBLEM fill_head() v.ast = replace_id_access v.ast, last_id tail_rule.mx_sequence.push v else if v.key == "__arg_0" and rule.sequence.length == 3 {ast, id_touch_list} = proxy._strict_pos_parse "@1" head_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } else if v.key == "__arg_1" and rule.sequence.length == 3 {ast, id_touch_list} = proxy._strict_pos_parse "@2" head_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } else head_rule.mx_sequence.push v {ast, id_touch_list} = proxy._strict_pos_parse "$1.#{v.key}" tail_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } for v in rule.strict_sequence if v.id_touch_list.has last_id if v.id_touch_list.length == 1 # tail_rule.strict_sequence.push v # p "last_id=#{last_id}" # p v.ast.value_array[0]?.value_array[0]?.value_array[0] v.ast = replace_id_access v.ast, last_id # p v.ast.value_array[0]?.value_array[0]?.value_array[0] tail_rule.strict_sequence.push v else v.ast = replace_id_access v.ast, last_id # вызывать тяжелую артиллерию только тогда, когда действительно надо tail_rule.strict_sequence.push v # PROBLEM fill_head() else head_rule.strict_sequence.push v for _rule in synth_rule_list if head_rule._head_cmp _rule found = _rule break synth_rule_list.push tail_rule if found tail_rule.sequence[0] = "#"+found.ret_hash_key break pass_hash_key = "proxy_#{head_rule.sequence.join(',')}_#{uid++}" head_rule.ret_hash_key = pass_hash_key tail_rule.sequence[0] = "#"+pass_hash_key rule = head_rule if !found synth_rule_list.push rule for rule in synth_rule_list rule._mx() rule._strict() # ################################################################################################### @hash_key_list.clear() @hash_key_list.push '*' # special position for string constants @hash_key_list.uappend @extra_hash_key_list for rule in synth_rule_list @hash_key_list.upush rule.ret_hash_key for v in rule.sequence if v[0] == "#" @hash_key_list.upush v.substr 1 for rule in synth_rule_list rule.ret_hash_key_idx = @hash_key_list.idx rule.ret_hash_key # ################################################################################################### @rule_1_by_arg = [] for i in [0 ... @hash_key_list.length] @rule_1_by_arg.push [] @rule_2_by_arg = [] for i in [0 ... (@hash_key_list.length ** 2)] @rule_2_by_arg.push [] pos_to_idx = (pos)=> idx = 0 # if string const if pos[0] == "#" idx = @hash_key_list.idx pos.substr 1 if idx == -1 # DEBUG throw new Error "WTF idx == -1 pos=#{pos} #{JSON.stringify @hash_key_list}" idx mult = @hash_key_list.length for rule in synth_rule_list switch rule.sequence.length when 1 [pos] = rule.sequence idx = pos_to_idx pos @rule_1_by_arg[idx].push rule when 2 [pos_a, pos_b] = rule.sequence idx_a = pos_to_idx pos_a idx_b = pos_to_idx pos_b @rule_2_by_arg[idx_a*mult + idx_b].push rule return hypothesis_find : (node_hypothesis_list, opt={})-> @optimize() if !@_optimized mode_full = false mode_full = opt.mode_full if opt.mode_full? expected_token_idx = -1 if opt.expected_token? if -1 == expected_token_idx = @hash_key_list.idx opt.expected_token throw new Error "unknown expected_token hash_key '#{opt.expected_token}' list=#{JSON.stringify @hash_key_list}" max_hki = @hash_key_list.length max_idx = node_hypothesis_list.length @t_hki_a_pos_old_list.length = max_hki @t_hki_a_pos_new_list.length = max_hki @t_hki_b_pos_old_list.length = max_hki @t_hki_b_pos_new_list.length = max_hki t_hki_a_new_count_list = [] t_hki_b_new_count_list = [] for i in [0 ... max_hki] t_hki_a_new_count_list.push 0 t_hki_b_new_count_list.push 0 init_max_idx = ()-> ret = [] for j in [0 .. max_idx] ret.push [] ret @new_new_list = [] # INCLUSIVE [a,b] for i in [0 ... max_hki] @t_hki_a_pos_old_list[i] = init_max_idx() @t_hki_a_pos_new_list[i] = init_max_idx() @t_hki_b_pos_old_list[i] = init_max_idx() @t_hki_b_pos_new_list[i] = init_max_idx() for v_list,idx in node_hypothesis_list for v in v_list v.a = idx v.b = idx+1 v.hash_key_idx = @hash_key_list.idx v.mx_hash.hash_key if v.hash_key_idx == -1 throw new Error "WTF v.hash_key_idx == -1 v.mx_hash.hash_key=#{v.mx_hash.hash_key} list=#{JSON.stringify @hash_key_list}" @t_hki_a_pos_new_list[v.hash_key_idx][idx ].push v @t_hki_b_pos_new_list[v.hash_key_idx][idx+1].push v if v.hash_key_idx != 0 @t_hki_a_pos_new_list[0][idx ].push v @t_hki_b_pos_new_list[0][idx+1].push v @new_new_list.push v # create hash_key_idx arrays for max_idx ret = [] fin_collect = ()=> ret.clear() if mode_full for pos_list_list,hash_key_idx in @t_hki_a_pos_old_list continue if expected_token_idx != -1 and hash_key_idx != expected_token_idx list = pos_list_list[0] for v in list continue if v.b != max_idx continue if v.hash_key_idx != hash_key_idx ret.push v for v in @new_new_list continue if v.a != 0 continue if v.b != max_idx continue if expected_token_idx != -1 and v.hash_key_idx != expected_token_idx ret.push v if mode_full then false else !!ret.length return ret if fin_collect() # BUG? правила вида term term лезут во все токены в поисках value даже в те, где есть только value_view limit = Gram.magic_attempt_limit_mult*max_idx for i in [1 .. limit] @new_new_list.clear() # MORE OPT jump list for hash_key_idx in [0 ... max_hki] count = 0 for v in @t_hki_a_pos_new_list[hash_key_idx] count += v.length t_hki_a_new_count_list[hash_key_idx] = count count = 0 for v in @t_hki_b_pos_new_list[hash_key_idx] count += v.length t_hki_b_new_count_list[hash_key_idx] = count # L2R rule_2_idx = 0 len = @hash_key_list.length for hash_key_idx_1 in [0 ... len] for hash_key_idx_2 in [0 ... len] rule_list = @rule_2_by_arg[rule_2_idx++] continue if rule_list.length == 0 # new_list_b_count = 1 # new_list_a_count = 1 new_list_b_count = t_hki_b_new_count_list[hash_key_idx_1] new_list_a_count = t_hki_a_new_count_list[hash_key_idx_2] continue if new_list_a_count == 0 and new_list_b_count == 0 node_old_list_b = @t_hki_b_pos_old_list[hash_key_idx_1] node_new_list_b = @t_hki_b_pos_new_list[hash_key_idx_1] node_old_list_a = @t_hki_a_pos_old_list[hash_key_idx_2] node_new_list_a = @t_hki_a_pos_new_list[hash_key_idx_2] # OPT this call can be inlined # keeped for readability fn = (lla, llb)=> # TODO opt no new token at hash_key (count before rule) for list_a,joint_pos in llb continue if list_a.length == 0 list_b = lla[joint_pos] continue if list_b.length == 0 for rule in rule_list # can opt in strict_rule_fn for a in list_a for b in list_b value_array = [a, b] # PROD continue if !rule.strict_rule_fn value_array # DEBUG # try # res = rule.strict_rule_fn value_array # catch err # pp value_array[0] # p rule.strict_rule_fn.toString() # throw err # continue if !res # new_node = new Node new_node.value_view = "#{a.value or a.value_view} #{b.value or b.value_view}" new_node.value_array = value_array rule.mx_rule_fn value_array, new_node.mx_hash new_node.mx_hash.hash_key = rule.ret_hash_key new_node.hash_key_idx = rule.ret_hash_key_idx new_node.a = a.a new_node.b = b.b @new_new_list.push new_node return if new_list_b_count fn node_old_list_a, node_new_list_b if new_list_a_count fn node_new_list_a, node_old_list_b if new_list_a_count and new_list_b_count fn node_new_list_a, node_new_list_b # R2L ничего не даст т.к. new_new_list # singles for rule_list, hash_key_idx in @rule_1_by_arg for node_list in @t_hki_a_pos_new_list[hash_key_idx] for rule in rule_list # can opt in strict_rule_fn for node in node_list value_array = [node] continue if !rule.strict_rule_fn value_array new_node = new Node new_node.value_view = node.value or node.value_view new_node.value_array = value_array rule.mx_rule_fn value_array, new_node.mx_hash new_node.mx_hash.hash_key = rule.ret_hash_key new_node.hash_key_idx = rule.ret_hash_key_idx new_node.a = node.a new_node.b = node.b @new_new_list.push new_node return ret if fin_collect() for hki in [0 ... max_hki] for pos in [0 .. max_idx] if @t_hki_a_pos_new_list[hki][pos].length @t_hki_a_pos_old_list[hki][pos].append @t_hki_a_pos_new_list[hki][pos] @t_hki_a_pos_new_list[hki][pos].clear() if @t_hki_b_pos_new_list[hki][pos].length @t_hki_b_pos_old_list[hki][pos].append @t_hki_b_pos_new_list[hki][pos] @t_hki_b_pos_new_list[hki][pos].clear() for node in @new_new_list @t_hki_a_pos_new_list[node.hash_key_idx][node.a].push node @t_hki_b_pos_new_list[node.hash_key_idx][node.b].push node @t_hki_a_pos_new_list[0][node.a].push node @t_hki_b_pos_new_list[0][node.b].push node if @new_new_list.length == 0 # p "# ###################################################################################################" # pp @t_hki_a_pos_old_list @new_new_list.clear() fin_collect() return ret throw new Error "magic_attempt_limit_mult exceed" go : (node_hypothesis_list, opt={})-> opt.reemerge ?= true ret = @hypothesis_find node_hypothesis_list, opt if opt.reemerge walk = (tree)-> for v in tree.value_array walk v if tree.mx_hash.is_proxy_rule delete tree.mx_hash.is_proxy_rule [head, tail] = tree.value_array tree.value_array.clear() tree.value_array.append head.value_array tree.value_array.push tail str_list = [] for v in tree.value_array str_list.push v.value or v.value_view tree.value_view = str_list.join ' ' return for tree,k in ret ret[k] = tree = tree.deep_clone() walk tree ret
26213
# BUG hash_to_pos для head/tail правил отсутствует module = @ require 'fy/lib/codegen' {Node} = require './node' {explicit_list_generator} = require './explicit_list_generator' # ################################################################################################### # tokenizer # ################################################################################################### {Tokenizer, Token_parser} = require 'gram' tokenizer = new Tokenizer tokenizer.parser_list.push (new Token_parser 'dollar_id', /^\$[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'hash_id', /^\#[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'pass_id', /^\@[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'id', /^[_a-z][_a-z0-9]*/i) tokenizer.parser_list.push (new Token_parser '_bin_op', /// ^ ( (&&?|\|\|?|[-+*/])| <>|[<>!=]=|<|> ) ///) tokenizer.parser_list.push (new Token_parser '_pre_op', /^!/) # tokenizer.parser_list.push (new Token_parser 'assign_bin_op', /^(&&?|\|\|?|[-+])?=/) tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/) tokenizer.parser_list.push (new Token_parser 'delimiter', /^[:.]/) string_regex_craft = /// \\[^xu] | # x and u are case sensitive while hex letters are not \\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence \\u(?: [0-9a-fA-F]{4} | # Unicode escape sequence \{(?: [0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF 10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF )\} ) ///.toString().replace(/\//g,'') single_quoted_regex_craft = /// (?: [^\\] | #{string_regex_craft} )*? ///.toString().replace(/\//g,'') tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///) double_quoted_regexp_craft = /// (?: [^\\#] | \#(?!\{) | #{string_regex_craft} )*? ///.toString().replace(/\//g,'') tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///) tokenizer.parser_list.push (new Token_parser 'number', /^[0-9]+/) # ################################################################################################### # gram # ################################################################################################### base_priority = -9000 {Gram} = require 'gram' gram = new Gram q = (a, b)->gram.rule a,b q('pre_op', '!') .mx('priority=1') q('pre_op', '-') .mx('priority=1') q('pre_op', '+') .mx('priority=1') q('bin_op', '*|/') .mx('priority=5 right_assoc=1') q('bin_op', '+|-') .mx('priority=6 right_assoc=1') q('bin_op', '<|<=|>|>=|!=|<>|==') .mx('priority=9') q('bin_op', '&|&&|and|or|[PIPE]|[PIPE][PIPE]') .mx('priority=10 right_assoc=1') q('access_rvalue', '#dollar_id') .mx("priority=#{base_priority} ult=dollar_id") q('access_rvalue', '#hash_id') .mx("priority=#{base_priority} ult=hash_id") q('rvalue', '#access_rvalue') .mx("priority=#{base_priority} ult=access_rvalue") q('rvalue', '#pass_id') .mx("priority=#{base_priority} ult=dollar_id") q('rvalue', '#number') .mx("priority=#{base_priority} ult=value") q('rvalue', '#id') .mx("priority=#{base_priority} ult=wrap_string") q('rvalue', '#string_literal_singleq') .mx("priority=#{base_priority} ult=value") q('rvalue', '#string_literal_doubleq') .mx("priority=#{base_priority} ult=value") q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority<#bin_op.priority #rvalue[2].priority<#bin_op.priority') # q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority<#bin_op.priority #rvalue[2].priority=#bin_op.priority #bin_op.left_assoc') q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority=#bin_op.priority #rvalue[2].priority<#bin_op.priority #bin_op.right_assoc') q('rvalue', '#pre_op #rvalue') .mx('priority=#pre_op.priority ult=pre_op') .strict('#rvalue[1].priority<=#pre_op.priority') q('rvalue', '( #rvalue )') .mx("priority=#{base_priority} ult=deep") q('access_rvalue', '#hash_id [ #rvalue ]') .mx("priority=#{base_priority} ult=hash_array_access") q('rvalue', '#access_rvalue [ #number : #number ]') .mx("priority=#{base_priority} ult=slice_access") # . access q('rvalue', '#access_rvalue . #id') .mx("priority=#{base_priority} ult=field_access") q('strict_rule', '#rvalue') .mx("ult=deep") # ################################################################################################### # trans # ################################################################################################### { Translator bin_op_translator_framework bin_op_translator_holder un_op_translator_framework un_op_translator_holder } = require 'gram' trans = new Translator trans.trans_skip = {} trans.trans_token = {} deep = (ctx, node)-> list = [] # if node.mx_hash.deep? # node.mx_hash.deep = '0' if node.mx_hash.deep == false # special case for deep=0 # value_array = (node.value_array[pos] for pos in node.mx_hash.deep.split ',') # else # value_array = node.value_array value_array = node.value_array for v,k in value_array list.push ctx.translate v list # ################################################################################################### do ()-> holder = new bin_op_translator_holder for v in bin_op_list = "+ - * / && ||".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" # SPECIAL holder.op_list["&"] = new bin_op_translator_framework "($1&&$2)" holder.op_list["|"] = new bin_op_translator_framework "($1||$2)" holder.op_list["<>"] = new bin_op_translator_framework "($1!=$2)" for v in bin_op_list = "== != < <= > >=".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" trans.translator_hash['bin_op'] = holder do ()-> holder = new un_op_translator_holder holder.mode_pre() for v in un_op_list = "+ - !".split ' ' holder.op_list[v] = new un_op_translator_framework "$op$1" trans.translator_hash['pre_op'] = holder # ################################################################################################### trans.translator_hash['deep'] = translate:(ctx, node)-> list = deep ctx, node list.join('') trans.translator_hash['value'] = translate:(ctx, node)->node.value trans.translator_hash['wrap_string'] = translate:(ctx, node)->JSON.stringify node.value trans.translator_hash['dollar_id'] = translate:(ctx, node)-> idx = (node.value.substr 1)-1 if idx < 0 or idx >= ctx.rule.sequence.length throw new Error "strict_rule access out of bounds [0, #{ctx.rule.sequence.length}] idx=#{idx} (note real value are +1)" node.mx_hash.idx = idx ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['hash_id'] = translate:(ctx, node)-> name = node.value.substr 1 if !idx_list = ctx.rule.hash_to_pos[name] throw new Error "unknown hash_key '#{name}' allowed key list #{JSON.stringify Object.keys(ctx.rule.hash_to_pos)}" node.mx_hash.idx = idx = idx_list[0] ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['access_rvalue'] = translate:(ctx, node)-> code = ctx.translate node.value_array[0] "#{code}.value" trans.translator_hash['hash_array_access'] = translate:(ctx, node)-> [id_node, _s, idx_node] = node.value_array name = id_node.value.substr 1 if !idx_list = ctx.rule.hash_to_pos[name] throw new Error "unknown hash_key '#{name}' allowed key list #{JSON.stringify Object.keys(ctx.rule.hash_to_pos)}" idx = idx_node.value-1 if idx < 0 or idx >= idx_list.length throw new Error "hash_array_access out of bounds [0, #{idx_list.length}] idx=#{idx} (note real value are +1)" node.mx_hash.idx = idx = idx_list[idx] ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['slice_access'] = translate:(ctx, node)-> [rvalue_node, _s, start_node, _s, end_node] = node.value_array rvalue = ctx.translate rvalue_node start = +start_node.value end = +end_node.value if end < start throw new Error "end < start at #{node.value}" "#{rvalue}.value.substr(#{start},#{end-start+1})" trans.translator_hash['field_access'] = translate:(ctx, node)-> [root_node, _s, field_node] = node.value_array root = ctx.translate root_node field = field_node.value "#{root}.mx_hash.#{field}" # ################################################################################################### # Gram_rule # ################################################################################################### class @Gram_rule hash_to_pos : {} ret_hash_key: '' ret_hash_key_idx: 0 sequence : [] mx_sequence : [] strict_sequence : [] mx_rule_fn : (arg_list)->{} # default pass strict_rule_fn: (arg_list)->true # default pass # TODO loop wrap constructor : ()-> @hash_to_pos = {} @sequence = [] @mx_sequence = [] @strict_sequence= [] cmp_seq : (t)-> return @sequence.join() == t.sequence.join() # ################################################################################################### # mx # ################################################################################################### mx : (str)-> pos_list = str.split /\s+/g @mx_sequence = [] code_jl = [] for pos in pos_list continue if !pos [key, value] = pos.split `/=/` if !value # autoassign case if @sequence.length != 1 throw new Error "can't autoassign if sequence.length(#{@sequence.length}) != 1" @mx_sequence.push { autoassign : true key id_touch_list : null ast : null } continue {id_touch_list, ast} = @_strict_pos_parse value @mx_sequence.push { autoassign : false key id_touch_list ast } return _mx : ()-> code_jl = [] for v in @mx_sequence {key} = v if v.autoassign code_jl.push """ mx_hash_stub[#{JSON.stringify key}] = arg_list[0].mx_hash[#{JSON.stringify key}]; """ else trans.rule = @ trans.id_touch_list = [] code = trans.go v.ast code_jl.push """ mx_hash_stub[#{JSON.stringify key}] = #{code}; """ @mx_rule_fn = eval """ __ret = (function(arg_list, mx_hash_stub){ #{join_list code_jl, ' '} }) """ return cmp_mx : (t)-> return false if @mx_sequence.length != t.mx_sequence.length for v1,idx in @mx_sequence v2 = t.mx_sequence[idx] return false if v1.autoassign != v2.autoassign return false if v1.key != v2.key return false if v1.id_touch_list.join() != v2.id_touch_list.join() return false if v1.ast.value != v2.ast.value # !!! DANGER !!! true # ################################################################################################### # strict # ################################################################################################### strict : (str)-> pos_list = str.split /\s+/g @strict_sequence = [] for pos in pos_list continue if !pos {id_touch_list, ast} = @_strict_pos_parse pos @strict_sequence.push { id_touch_list ast } return _strict : ()-> code_jl = [] for pos,idx in @sequence continue if pos[0] == "#" code_jl.push """ if (arg_list[#{idx}].value != #{JSON.stringify pos}) return false; """ for v in @strict_sequence trans.rule = @ trans.id_touch_list = [] code = trans.go v.ast code_jl.push """ if (!(#{code})) return false; """ @strict_rule_fn = eval """ __ret = (function(arg_list){ #{join_list code_jl, ' '} return true; }) """ cmp_strict : (t)-> return false if @strict_sequence.length != t.strict_sequence.length for v1,idx in @strict_sequence v2 = t.strict_sequence[idx] return false if v1.id_touch_list.join() != v2.id_touch_list.join() return false if v1.ast.value != v2.ast.value # !!! DANGER !!! true _strict_pos_parse : (str)-> tok_list = tokenizer.go str gram.mode_full = true ast = gram.parse_text_list tok_list, expected_token : 'strict_rule' if ast.length == 0 throw new Error "Parsing error. No proper combination found" if ast.length != 1 # [a,b] = ast # show_diff a,b ### !pragma coverage-skip-block ### throw new Error "Parsing error. More than one proper combination found #{ast.length}" trans.rule = @ trans.id_touch_list = [] code = trans.go ast[0] { code id_touch_list : trans.id_touch_list ast : ast[0] } # unused # cmp : (t)-> # return false if @ret_hash_key != t.ret_hash_key # return false if !@cmp_seq(t) # return false if !@cmp_mx(t) # return false if !@cmp_strict(t) # return _head_cmp : (t)-> return false if @ret_hash_key != t.ret_hash_key return false if !@cmp_seq(t) return false if !@cmp_mx(t) return false if !@cmp_strict(t) true class @Gram_rule_proxy rule_list : [] constructor:()-> @rule_list = [] mx : (str)-> for rule in @rule_list rule.mx str @ strict : (str)-> for rule in @rule_list rule.strict str @ # ################################################################################################### # Gram # ################################################################################################### str_replace = (search, replace, str)-> str.split(search).join(replace) @gram_escape= (v) -> v = str_replace '|', '[PIPE]', v v = str_replace '?', '[QUESTION]', v v = str_replace '$', '[DOLLAR]', v v = str_replace '#', '[HASH]', v @gram_unescape= (v) -> v = str_replace '[PIPE]', '|', v v = str_replace '[QUESTION]','?', v v = str_replace '[DOLLAR]', '$', v # нужно в случае конструкций ${}, когда нельзя отделить $ от токена v = str_replace '[HASH]', '#', v class @Gram @magic_attempt_limit_mult : 20 initial_rule_list : [] hash_key_list : [] extra_hash_key_list : [] _optimized : false # Array<Array<Node> > # hki = hash_key_idx # a_pos = left token bound position # b_pos = right token bound position t_hki_a_pos_old_list : [] t_hki_a_pos_new_list : [] t_hki_b_pos_old_list : [] t_hki_b_pos_new_list : [] new_new_list : [] constructor:()-> @initial_rule_list = [] @hash_key_list = [] @extra_hash_key_list = [] @t_hki_a_pos_old_list = [] @t_hki_a_pos_new_list = [] @t_hki_b_pos_old_list = [] @t_hki_b_pos_new_list = [] @new_new_list = [] rule : (_ret, str_list)-> @_optimized = false ret = new module.Gram_rule_proxy hash_to_pos = {} pos_list_list = [] for chunk,idx in chunk_list = str_list.split /\s+/g list = chunk.split '|' if list.length > 1 # NOTE positions not allowed, only const for v,k in list if v[0] == '#' throw new Error "#positions + | not allowed" list[k] = module.gram_unescape v pos_list_list.push list continue if chunk[0] == "#" id = chunk.substr 1 id = module.gram_unescape id hash_to_pos[id] ?= [] hash_to_pos[id].push idx if /\?$/.test chunk chunk = chunk.substr 0, chunk.length-1 chunk = module.gram_unescape chunk pos_list_list.push [chunk, null] continue chunk = module.gram_unescape chunk pos_list_list.push [chunk] pos_list_list2 = explicit_list_generator pos_list_list for sequence in pos_list_list2 id_mapping = {} sequence_filtered = [] dst = 0 for v,idx in sequence continue if !v? id_mapping[idx] = dst++ sequence_filtered.push v continue if sequence_filtered.length == 0 rule = new module.Gram_rule rule.ret_hash_key = _ret for k,v of hash_to_pos rule.hash_to_pos[k] = v.map (t)->id_mapping[t] rule.sequence = sequence_filtered rule.strict('') # reinit strict_rule_fn by sequence in case strict will not be called at all @initial_rule_list.push rule ret.rule_list.push rule ret rule_1_by_arg : [] rule_2_by_arg : [] optimize : ()-> @_optimized = true synth_rule_list = [] uid = 0 proxy = new module.Gram_rule proxy.sequence = ['STUB', 'STUB'] replace_id_access = (tree, skip_id)-> search_idx = tree.mx_hash.idx if search_idx? if search_idx != skip_id {ast} = proxy._strict_pos_parse "$1.__arg_#{search_idx}" return ast else # $2 # #a # #a[2] {ast} = proxy._strict_pos_parse "@2" return ast list = tree.value_array for v,k in list list[k] = replace_id_access v, skip_id tree for rule in @initial_rule_list switch rule.sequence.length when 1,2 found = false for _rule in synth_rule_list if rule._head_cmp _rule found = _rule break if !found synth_rule_list.push rule else found = null while rule.sequence.length > 2 head_rule = new module.Gram_rule tail_rule = new module.Gram_rule {ast, id_touch_list} = proxy._strict_pos_parse "1" tail_rule.mx_sequence.push { autoassign : false key : "<KEY>" id_touch_list ast } tail_rule.ret_hash_key = rule.ret_hash_key head_rule.hash_to_pos = rule.hash_to_pos # дабы не сломалось ничего. _max_idx = rule.sequence.length-1 for k,list of rule.hash_to_pos v = list.last() if v == _max_idx tail_rule.hash_to_pos[k] ?= [] tail_rule.hash_to_pos[k].push 1 # а остальных быть не может т.к. strict rule будет переписано и все остальные позиции будут через @ head_rule.sequence = rule.sequence.clone() last = head_rule.sequence.pop() tail_rule.sequence = ['REPLACE_ME', last] last_id = head_rule.sequence.length # mx отдувается за всех. Ему нужно пробросить всё head_filled_with_mx_pass = false fill_head = ()-> if !head_filled_with_mx_pass head_filled_with_mx_pass = true for i in [0 ... last_id] key = <KEY> # p "key=#{key}" {ast, id_touch_list} = head_rule._strict_pos_parse "@#{i+1}" head_rule.mx_sequence.push { autoassign : false key id_touch_list ast } return for v in rule.mx_sequence if v.autoassign # DEBUG ONLY throw new Error "WTF" if v.id_touch_list.has last_id if v.id_touch_list.length == 1 tail_rule.mx_sequence.push v else # PROBLEM fill_head() v.ast = replace_id_access v.ast, last_id tail_rule.mx_sequence.push v else if v.key == "__arg_<KEY>" and rule.sequence.length == 3 {ast, id_touch_list} = proxy._strict_pos_parse "@1" head_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } else if v.key == "__arg<KEY>_1" and rule.sequence.length == 3 {ast, id_touch_list} = proxy._strict_pos_parse "@2" head_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } else head_rule.mx_sequence.push v {ast, id_touch_list} = proxy._strict_pos_parse "$1.#{v.key}" tail_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } for v in rule.strict_sequence if v.id_touch_list.has last_id if v.id_touch_list.length == 1 # tail_rule.strict_sequence.push v # p "last_id=#{last_id}" # p v.ast.value_array[0]?.value_array[0]?.value_array[0] v.ast = replace_id_access v.ast, last_id # p v.ast.value_array[0]?.value_array[0]?.value_array[0] tail_rule.strict_sequence.push v else v.ast = replace_id_access v.ast, last_id # вызывать тяжелую артиллерию только тогда, когда действительно надо tail_rule.strict_sequence.push v # PROBLEM fill_head() else head_rule.strict_sequence.push v for _rule in synth_rule_list if head_rule._head_cmp _rule found = _rule break synth_rule_list.push tail_rule if found tail_rule.sequence[0] = "#"+found.ret_hash_key break pass_hash_key = "<KEY>head_rule.sequence.join(',')}_<KEY>uid<KEY>++}" head_rule.ret_hash_key = pass_hash_key tail_rule.sequence[0] = "#"+pass_hash_key rule = head_rule if !found synth_rule_list.push rule for rule in synth_rule_list rule._mx() rule._strict() # ################################################################################################### @hash_key_list.clear() @hash_key_list.push '*' # special position for string constants @hash_key_list.uappend @extra_hash_key_list for rule in synth_rule_list @hash_key_list.upush rule.ret_hash_key for v in rule.sequence if v[0] == "#" @hash_key_list.upush v.substr 1 for rule in synth_rule_list rule.ret_hash_key_idx = @hash_key_list.idx rule.ret_hash_key # ################################################################################################### @rule_1_by_arg = [] for i in [0 ... @hash_key_list.length] @rule_1_by_arg.push [] @rule_2_by_arg = [] for i in [0 ... (@hash_key_list.length ** 2)] @rule_2_by_arg.push [] pos_to_idx = (pos)=> idx = 0 # if string const if pos[0] == "#" idx = @hash_key_list.idx pos.substr 1 if idx == -1 # DEBUG throw new Error "WTF idx == -1 pos=#{pos} #{JSON.stringify @hash_key_list}" idx mult = @hash_key_list.length for rule in synth_rule_list switch rule.sequence.length when 1 [pos] = rule.sequence idx = pos_to_idx pos @rule_1_by_arg[idx].push rule when 2 [pos_a, pos_b] = rule.sequence idx_a = pos_to_idx pos_a idx_b = pos_to_idx pos_b @rule_2_by_arg[idx_a*mult + idx_b].push rule return hypothesis_find : (node_hypothesis_list, opt={})-> @optimize() if !@_optimized mode_full = false mode_full = opt.mode_full if opt.mode_full? expected_token_idx = -1 if opt.expected_token? if -1 == expected_token_idx = @hash_key_list.idx opt.expected_token throw new Error "unknown expected_token hash_key '#{opt.expected_token}' list=#{JSON.stringify @hash_key_list}" max_hki = @hash_key_list.length max_idx = node_hypothesis_list.length @t_hki_a_pos_old_list.length = max_hki @t_hki_a_pos_new_list.length = max_hki @t_hki_b_pos_old_list.length = max_hki @t_hki_b_pos_new_list.length = max_hki t_hki_a_new_count_list = [] t_hki_b_new_count_list = [] for i in [0 ... max_hki] t_hki_a_new_count_list.push 0 t_hki_b_new_count_list.push 0 init_max_idx = ()-> ret = [] for j in [0 .. max_idx] ret.push [] ret @new_new_list = [] # INCLUSIVE [a,b] for i in [0 ... max_hki] @t_hki_a_pos_old_list[i] = init_max_idx() @t_hki_a_pos_new_list[i] = init_max_idx() @t_hki_b_pos_old_list[i] = init_max_idx() @t_hki_b_pos_new_list[i] = init_max_idx() for v_list,idx in node_hypothesis_list for v in v_list v.a = idx v.b = idx+1 v.hash_key_idx = @hash_key_list.idx v.mx_hash.hash_key if v.hash_key_idx == -1 throw new Error "WTF v.hash_key_idx == -1 v.mx_hash.hash_key=#{v.mx_hash.hash_key} list=#{JSON.stringify @hash_key_list}" @t_hki_a_pos_new_list[v.hash_key_idx][idx ].push v @t_hki_b_pos_new_list[v.hash_key_idx][idx+1].push v if v.hash_key_idx != 0 @t_hki_a_pos_new_list[0][idx ].push v @t_hki_b_pos_new_list[0][idx+1].push v @new_new_list.push v # create hash_key_idx arrays for max_idx ret = [] fin_collect = ()=> ret.clear() if mode_full for pos_list_list,hash_key_idx in @t_hki_a_pos_old_list continue if expected_token_idx != -1 and hash_key_idx != expected_token_idx list = pos_list_list[0] for v in list continue if v.b != max_idx continue if v.hash_key_idx != hash_key_idx ret.push v for v in @new_new_list continue if v.a != 0 continue if v.b != max_idx continue if expected_token_idx != -1 and v.hash_key_idx != expected_token_idx ret.push v if mode_full then false else !!ret.length return ret if fin_collect() # BUG? правила вида term term лезут во все токены в поисках value даже в те, где есть только value_view limit = Gram.magic_attempt_limit_mult*max_idx for i in [1 .. limit] @new_new_list.clear() # MORE OPT jump list for hash_key_idx in [0 ... max_hki] count = 0 for v in @t_hki_a_pos_new_list[hash_key_idx] count += v.length t_hki_a_new_count_list[hash_key_idx] = count count = 0 for v in @t_hki_b_pos_new_list[hash_key_idx] count += v.length t_hki_b_new_count_list[hash_key_idx] = count # L2R rule_2_idx = 0 len = @hash_key_list.length for hash_key_idx_1 in [0 ... len] for hash_key_idx_2 in [0 ... len] rule_list = @rule_2_by_arg[rule_2_idx++] continue if rule_list.length == 0 # new_list_b_count = 1 # new_list_a_count = 1 new_list_b_count = t_hki_b_new_count_list[hash_key_idx_1] new_list_a_count = t_hki_a_new_count_list[hash_key_idx_2] continue if new_list_a_count == 0 and new_list_b_count == 0 node_old_list_b = @t_hki_b_pos_old_list[hash_key_idx_1] node_new_list_b = @t_hki_b_pos_new_list[hash_key_idx_1] node_old_list_a = @t_hki_a_pos_old_list[hash_key_idx_2] node_new_list_a = @t_hki_a_pos_new_list[hash_key_idx_2] # OPT this call can be inlined # keeped for readability fn = (lla, llb)=> # TODO opt no new token at hash_key (count before rule) for list_a,joint_pos in llb continue if list_a.length == 0 list_b = lla[joint_pos] continue if list_b.length == 0 for rule in rule_list # can opt in strict_rule_fn for a in list_a for b in list_b value_array = [a, b] # PROD continue if !rule.strict_rule_fn value_array # DEBUG # try # res = rule.strict_rule_fn value_array # catch err # pp value_array[0] # p rule.strict_rule_fn.toString() # throw err # continue if !res # new_node = new Node new_node.value_view = "#{a.value or a.value_view} #{b.value or b.value_view}" new_node.value_array = value_array rule.mx_rule_fn value_array, new_node.mx_hash new_node.mx_hash.hash_key = rule.ret_hash_key new_node.hash_key_idx = rule.ret_hash_key_idx new_node.a = a.a new_node.b = b.b @new_new_list.push new_node return if new_list_b_count fn node_old_list_a, node_new_list_b if new_list_a_count fn node_new_list_a, node_old_list_b if new_list_a_count and new_list_b_count fn node_new_list_a, node_new_list_b # R2L ничего не даст т.к. new_new_list # singles for rule_list, hash_key_idx in @rule_1_by_arg for node_list in @t_hki_a_pos_new_list[hash_key_idx] for rule in rule_list # can opt in strict_rule_fn for node in node_list value_array = [node] continue if !rule.strict_rule_fn value_array new_node = new Node new_node.value_view = node.value or node.value_view new_node.value_array = value_array rule.mx_rule_fn value_array, new_node.mx_hash new_node.mx_hash.hash_key = rule.ret_hash_key new_node.hash_key_idx = rule.ret_hash_key_idx new_node.a = node.a new_node.b = node.b @new_new_list.push new_node return ret if fin_collect() for hki in [0 ... max_hki] for pos in [0 .. max_idx] if @t_hki_a_pos_new_list[hki][pos].length @t_hki_a_pos_old_list[hki][pos].append @t_hki_a_pos_new_list[hki][pos] @t_hki_a_pos_new_list[hki][pos].clear() if @t_hki_b_pos_new_list[hki][pos].length @t_hki_b_pos_old_list[hki][pos].append @t_hki_b_pos_new_list[hki][pos] @t_hki_b_pos_new_list[hki][pos].clear() for node in @new_new_list @t_hki_a_pos_new_list[node.hash_key_idx][node.a].push node @t_hki_b_pos_new_list[node.hash_key_idx][node.b].push node @t_hki_a_pos_new_list[0][node.a].push node @t_hki_b_pos_new_list[0][node.b].push node if @new_new_list.length == 0 # p "# ###################################################################################################" # pp @t_hki_a_pos_old_list @new_new_list.clear() fin_collect() return ret throw new Error "magic_attempt_limit_mult exceed" go : (node_hypothesis_list, opt={})-> opt.reemerge ?= true ret = @hypothesis_find node_hypothesis_list, opt if opt.reemerge walk = (tree)-> for v in tree.value_array walk v if tree.mx_hash.is_proxy_rule delete tree.mx_hash.is_proxy_rule [head, tail] = tree.value_array tree.value_array.clear() tree.value_array.append head.value_array tree.value_array.push tail str_list = [] for v in tree.value_array str_list.push v.value or v.value_view tree.value_view = str_list.join ' ' return for tree,k in ret ret[k] = tree = tree.deep_clone() walk tree ret
true
# BUG hash_to_pos для head/tail правил отсутствует module = @ require 'fy/lib/codegen' {Node} = require './node' {explicit_list_generator} = require './explicit_list_generator' # ################################################################################################### # tokenizer # ################################################################################################### {Tokenizer, Token_parser} = require 'gram' tokenizer = new Tokenizer tokenizer.parser_list.push (new Token_parser 'dollar_id', /^\$[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'hash_id', /^\#[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'pass_id', /^\@[_a-z0-9]+/i) tokenizer.parser_list.push (new Token_parser 'id', /^[_a-z][_a-z0-9]*/i) tokenizer.parser_list.push (new Token_parser '_bin_op', /// ^ ( (&&?|\|\|?|[-+*/])| <>|[<>!=]=|<|> ) ///) tokenizer.parser_list.push (new Token_parser '_pre_op', /^!/) # tokenizer.parser_list.push (new Token_parser 'assign_bin_op', /^(&&?|\|\|?|[-+])?=/) tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/) tokenizer.parser_list.push (new Token_parser 'delimiter', /^[:.]/) string_regex_craft = /// \\[^xu] | # x and u are case sensitive while hex letters are not \\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence \\u(?: [0-9a-fA-F]{4} | # Unicode escape sequence \{(?: [0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF 10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF )\} ) ///.toString().replace(/\//g,'') single_quoted_regex_craft = /// (?: [^\\] | #{string_regex_craft} )*? ///.toString().replace(/\//g,'') tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///) double_quoted_regexp_craft = /// (?: [^\\#] | \#(?!\{) | #{string_regex_craft} )*? ///.toString().replace(/\//g,'') tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///) tokenizer.parser_list.push (new Token_parser 'number', /^[0-9]+/) # ################################################################################################### # gram # ################################################################################################### base_priority = -9000 {Gram} = require 'gram' gram = new Gram q = (a, b)->gram.rule a,b q('pre_op', '!') .mx('priority=1') q('pre_op', '-') .mx('priority=1') q('pre_op', '+') .mx('priority=1') q('bin_op', '*|/') .mx('priority=5 right_assoc=1') q('bin_op', '+|-') .mx('priority=6 right_assoc=1') q('bin_op', '<|<=|>|>=|!=|<>|==') .mx('priority=9') q('bin_op', '&|&&|and|or|[PIPE]|[PIPE][PIPE]') .mx('priority=10 right_assoc=1') q('access_rvalue', '#dollar_id') .mx("priority=#{base_priority} ult=dollar_id") q('access_rvalue', '#hash_id') .mx("priority=#{base_priority} ult=hash_id") q('rvalue', '#access_rvalue') .mx("priority=#{base_priority} ult=access_rvalue") q('rvalue', '#pass_id') .mx("priority=#{base_priority} ult=dollar_id") q('rvalue', '#number') .mx("priority=#{base_priority} ult=value") q('rvalue', '#id') .mx("priority=#{base_priority} ult=wrap_string") q('rvalue', '#string_literal_singleq') .mx("priority=#{base_priority} ult=value") q('rvalue', '#string_literal_doubleq') .mx("priority=#{base_priority} ult=value") q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority<#bin_op.priority #rvalue[2].priority<#bin_op.priority') # q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority<#bin_op.priority #rvalue[2].priority=#bin_op.priority #bin_op.left_assoc') q('rvalue', '#rvalue #bin_op #rvalue') .mx('priority=#bin_op.priority ult=bin_op') .strict('#rvalue[1].priority=#bin_op.priority #rvalue[2].priority<#bin_op.priority #bin_op.right_assoc') q('rvalue', '#pre_op #rvalue') .mx('priority=#pre_op.priority ult=pre_op') .strict('#rvalue[1].priority<=#pre_op.priority') q('rvalue', '( #rvalue )') .mx("priority=#{base_priority} ult=deep") q('access_rvalue', '#hash_id [ #rvalue ]') .mx("priority=#{base_priority} ult=hash_array_access") q('rvalue', '#access_rvalue [ #number : #number ]') .mx("priority=#{base_priority} ult=slice_access") # . access q('rvalue', '#access_rvalue . #id') .mx("priority=#{base_priority} ult=field_access") q('strict_rule', '#rvalue') .mx("ult=deep") # ################################################################################################### # trans # ################################################################################################### { Translator bin_op_translator_framework bin_op_translator_holder un_op_translator_framework un_op_translator_holder } = require 'gram' trans = new Translator trans.trans_skip = {} trans.trans_token = {} deep = (ctx, node)-> list = [] # if node.mx_hash.deep? # node.mx_hash.deep = '0' if node.mx_hash.deep == false # special case for deep=0 # value_array = (node.value_array[pos] for pos in node.mx_hash.deep.split ',') # else # value_array = node.value_array value_array = node.value_array for v,k in value_array list.push ctx.translate v list # ################################################################################################### do ()-> holder = new bin_op_translator_holder for v in bin_op_list = "+ - * / && ||".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" # SPECIAL holder.op_list["&"] = new bin_op_translator_framework "($1&&$2)" holder.op_list["|"] = new bin_op_translator_framework "($1||$2)" holder.op_list["<>"] = new bin_op_translator_framework "($1!=$2)" for v in bin_op_list = "== != < <= > >=".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" trans.translator_hash['bin_op'] = holder do ()-> holder = new un_op_translator_holder holder.mode_pre() for v in un_op_list = "+ - !".split ' ' holder.op_list[v] = new un_op_translator_framework "$op$1" trans.translator_hash['pre_op'] = holder # ################################################################################################### trans.translator_hash['deep'] = translate:(ctx, node)-> list = deep ctx, node list.join('') trans.translator_hash['value'] = translate:(ctx, node)->node.value trans.translator_hash['wrap_string'] = translate:(ctx, node)->JSON.stringify node.value trans.translator_hash['dollar_id'] = translate:(ctx, node)-> idx = (node.value.substr 1)-1 if idx < 0 or idx >= ctx.rule.sequence.length throw new Error "strict_rule access out of bounds [0, #{ctx.rule.sequence.length}] idx=#{idx} (note real value are +1)" node.mx_hash.idx = idx ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['hash_id'] = translate:(ctx, node)-> name = node.value.substr 1 if !idx_list = ctx.rule.hash_to_pos[name] throw new Error "unknown hash_key '#{name}' allowed key list #{JSON.stringify Object.keys(ctx.rule.hash_to_pos)}" node.mx_hash.idx = idx = idx_list[0] ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['access_rvalue'] = translate:(ctx, node)-> code = ctx.translate node.value_array[0] "#{code}.value" trans.translator_hash['hash_array_access'] = translate:(ctx, node)-> [id_node, _s, idx_node] = node.value_array name = id_node.value.substr 1 if !idx_list = ctx.rule.hash_to_pos[name] throw new Error "unknown hash_key '#{name}' allowed key list #{JSON.stringify Object.keys(ctx.rule.hash_to_pos)}" idx = idx_node.value-1 if idx < 0 or idx >= idx_list.length throw new Error "hash_array_access out of bounds [0, #{idx_list.length}] idx=#{idx} (note real value are +1)" node.mx_hash.idx = idx = idx_list[idx] ctx.id_touch_list.upush idx "arg_list[#{idx}]" trans.translator_hash['slice_access'] = translate:(ctx, node)-> [rvalue_node, _s, start_node, _s, end_node] = node.value_array rvalue = ctx.translate rvalue_node start = +start_node.value end = +end_node.value if end < start throw new Error "end < start at #{node.value}" "#{rvalue}.value.substr(#{start},#{end-start+1})" trans.translator_hash['field_access'] = translate:(ctx, node)-> [root_node, _s, field_node] = node.value_array root = ctx.translate root_node field = field_node.value "#{root}.mx_hash.#{field}" # ################################################################################################### # Gram_rule # ################################################################################################### class @Gram_rule hash_to_pos : {} ret_hash_key: '' ret_hash_key_idx: 0 sequence : [] mx_sequence : [] strict_sequence : [] mx_rule_fn : (arg_list)->{} # default pass strict_rule_fn: (arg_list)->true # default pass # TODO loop wrap constructor : ()-> @hash_to_pos = {} @sequence = [] @mx_sequence = [] @strict_sequence= [] cmp_seq : (t)-> return @sequence.join() == t.sequence.join() # ################################################################################################### # mx # ################################################################################################### mx : (str)-> pos_list = str.split /\s+/g @mx_sequence = [] code_jl = [] for pos in pos_list continue if !pos [key, value] = pos.split `/=/` if !value # autoassign case if @sequence.length != 1 throw new Error "can't autoassign if sequence.length(#{@sequence.length}) != 1" @mx_sequence.push { autoassign : true key id_touch_list : null ast : null } continue {id_touch_list, ast} = @_strict_pos_parse value @mx_sequence.push { autoassign : false key id_touch_list ast } return _mx : ()-> code_jl = [] for v in @mx_sequence {key} = v if v.autoassign code_jl.push """ mx_hash_stub[#{JSON.stringify key}] = arg_list[0].mx_hash[#{JSON.stringify key}]; """ else trans.rule = @ trans.id_touch_list = [] code = trans.go v.ast code_jl.push """ mx_hash_stub[#{JSON.stringify key}] = #{code}; """ @mx_rule_fn = eval """ __ret = (function(arg_list, mx_hash_stub){ #{join_list code_jl, ' '} }) """ return cmp_mx : (t)-> return false if @mx_sequence.length != t.mx_sequence.length for v1,idx in @mx_sequence v2 = t.mx_sequence[idx] return false if v1.autoassign != v2.autoassign return false if v1.key != v2.key return false if v1.id_touch_list.join() != v2.id_touch_list.join() return false if v1.ast.value != v2.ast.value # !!! DANGER !!! true # ################################################################################################### # strict # ################################################################################################### strict : (str)-> pos_list = str.split /\s+/g @strict_sequence = [] for pos in pos_list continue if !pos {id_touch_list, ast} = @_strict_pos_parse pos @strict_sequence.push { id_touch_list ast } return _strict : ()-> code_jl = [] for pos,idx in @sequence continue if pos[0] == "#" code_jl.push """ if (arg_list[#{idx}].value != #{JSON.stringify pos}) return false; """ for v in @strict_sequence trans.rule = @ trans.id_touch_list = [] code = trans.go v.ast code_jl.push """ if (!(#{code})) return false; """ @strict_rule_fn = eval """ __ret = (function(arg_list){ #{join_list code_jl, ' '} return true; }) """ cmp_strict : (t)-> return false if @strict_sequence.length != t.strict_sequence.length for v1,idx in @strict_sequence v2 = t.strict_sequence[idx] return false if v1.id_touch_list.join() != v2.id_touch_list.join() return false if v1.ast.value != v2.ast.value # !!! DANGER !!! true _strict_pos_parse : (str)-> tok_list = tokenizer.go str gram.mode_full = true ast = gram.parse_text_list tok_list, expected_token : 'strict_rule' if ast.length == 0 throw new Error "Parsing error. No proper combination found" if ast.length != 1 # [a,b] = ast # show_diff a,b ### !pragma coverage-skip-block ### throw new Error "Parsing error. More than one proper combination found #{ast.length}" trans.rule = @ trans.id_touch_list = [] code = trans.go ast[0] { code id_touch_list : trans.id_touch_list ast : ast[0] } # unused # cmp : (t)-> # return false if @ret_hash_key != t.ret_hash_key # return false if !@cmp_seq(t) # return false if !@cmp_mx(t) # return false if !@cmp_strict(t) # return _head_cmp : (t)-> return false if @ret_hash_key != t.ret_hash_key return false if !@cmp_seq(t) return false if !@cmp_mx(t) return false if !@cmp_strict(t) true class @Gram_rule_proxy rule_list : [] constructor:()-> @rule_list = [] mx : (str)-> for rule in @rule_list rule.mx str @ strict : (str)-> for rule in @rule_list rule.strict str @ # ################################################################################################### # Gram # ################################################################################################### str_replace = (search, replace, str)-> str.split(search).join(replace) @gram_escape= (v) -> v = str_replace '|', '[PIPE]', v v = str_replace '?', '[QUESTION]', v v = str_replace '$', '[DOLLAR]', v v = str_replace '#', '[HASH]', v @gram_unescape= (v) -> v = str_replace '[PIPE]', '|', v v = str_replace '[QUESTION]','?', v v = str_replace '[DOLLAR]', '$', v # нужно в случае конструкций ${}, когда нельзя отделить $ от токена v = str_replace '[HASH]', '#', v class @Gram @magic_attempt_limit_mult : 20 initial_rule_list : [] hash_key_list : [] extra_hash_key_list : [] _optimized : false # Array<Array<Node> > # hki = hash_key_idx # a_pos = left token bound position # b_pos = right token bound position t_hki_a_pos_old_list : [] t_hki_a_pos_new_list : [] t_hki_b_pos_old_list : [] t_hki_b_pos_new_list : [] new_new_list : [] constructor:()-> @initial_rule_list = [] @hash_key_list = [] @extra_hash_key_list = [] @t_hki_a_pos_old_list = [] @t_hki_a_pos_new_list = [] @t_hki_b_pos_old_list = [] @t_hki_b_pos_new_list = [] @new_new_list = [] rule : (_ret, str_list)-> @_optimized = false ret = new module.Gram_rule_proxy hash_to_pos = {} pos_list_list = [] for chunk,idx in chunk_list = str_list.split /\s+/g list = chunk.split '|' if list.length > 1 # NOTE positions not allowed, only const for v,k in list if v[0] == '#' throw new Error "#positions + | not allowed" list[k] = module.gram_unescape v pos_list_list.push list continue if chunk[0] == "#" id = chunk.substr 1 id = module.gram_unescape id hash_to_pos[id] ?= [] hash_to_pos[id].push idx if /\?$/.test chunk chunk = chunk.substr 0, chunk.length-1 chunk = module.gram_unescape chunk pos_list_list.push [chunk, null] continue chunk = module.gram_unescape chunk pos_list_list.push [chunk] pos_list_list2 = explicit_list_generator pos_list_list for sequence in pos_list_list2 id_mapping = {} sequence_filtered = [] dst = 0 for v,idx in sequence continue if !v? id_mapping[idx] = dst++ sequence_filtered.push v continue if sequence_filtered.length == 0 rule = new module.Gram_rule rule.ret_hash_key = _ret for k,v of hash_to_pos rule.hash_to_pos[k] = v.map (t)->id_mapping[t] rule.sequence = sequence_filtered rule.strict('') # reinit strict_rule_fn by sequence in case strict will not be called at all @initial_rule_list.push rule ret.rule_list.push rule ret rule_1_by_arg : [] rule_2_by_arg : [] optimize : ()-> @_optimized = true synth_rule_list = [] uid = 0 proxy = new module.Gram_rule proxy.sequence = ['STUB', 'STUB'] replace_id_access = (tree, skip_id)-> search_idx = tree.mx_hash.idx if search_idx? if search_idx != skip_id {ast} = proxy._strict_pos_parse "$1.__arg_#{search_idx}" return ast else # $2 # #a # #a[2] {ast} = proxy._strict_pos_parse "@2" return ast list = tree.value_array for v,k in list list[k] = replace_id_access v, skip_id tree for rule in @initial_rule_list switch rule.sequence.length when 1,2 found = false for _rule in synth_rule_list if rule._head_cmp _rule found = _rule break if !found synth_rule_list.push rule else found = null while rule.sequence.length > 2 head_rule = new module.Gram_rule tail_rule = new module.Gram_rule {ast, id_touch_list} = proxy._strict_pos_parse "1" tail_rule.mx_sequence.push { autoassign : false key : "PI:KEY:<KEY>END_PI" id_touch_list ast } tail_rule.ret_hash_key = rule.ret_hash_key head_rule.hash_to_pos = rule.hash_to_pos # дабы не сломалось ничего. _max_idx = rule.sequence.length-1 for k,list of rule.hash_to_pos v = list.last() if v == _max_idx tail_rule.hash_to_pos[k] ?= [] tail_rule.hash_to_pos[k].push 1 # а остальных быть не может т.к. strict rule будет переписано и все остальные позиции будут через @ head_rule.sequence = rule.sequence.clone() last = head_rule.sequence.pop() tail_rule.sequence = ['REPLACE_ME', last] last_id = head_rule.sequence.length # mx отдувается за всех. Ему нужно пробросить всё head_filled_with_mx_pass = false fill_head = ()-> if !head_filled_with_mx_pass head_filled_with_mx_pass = true for i in [0 ... last_id] key = PI:KEY:<KEY>END_PI # p "key=#{key}" {ast, id_touch_list} = head_rule._strict_pos_parse "@#{i+1}" head_rule.mx_sequence.push { autoassign : false key id_touch_list ast } return for v in rule.mx_sequence if v.autoassign # DEBUG ONLY throw new Error "WTF" if v.id_touch_list.has last_id if v.id_touch_list.length == 1 tail_rule.mx_sequence.push v else # PROBLEM fill_head() v.ast = replace_id_access v.ast, last_id tail_rule.mx_sequence.push v else if v.key == "__arg_PI:KEY:<KEY>END_PI" and rule.sequence.length == 3 {ast, id_touch_list} = proxy._strict_pos_parse "@1" head_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } else if v.key == "__argPI:KEY:<KEY>END_PI_1" and rule.sequence.length == 3 {ast, id_touch_list} = proxy._strict_pos_parse "@2" head_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } else head_rule.mx_sequence.push v {ast, id_touch_list} = proxy._strict_pos_parse "$1.#{v.key}" tail_rule.mx_sequence.push { autoassign : false key : v.key id_touch_list ast } for v in rule.strict_sequence if v.id_touch_list.has last_id if v.id_touch_list.length == 1 # tail_rule.strict_sequence.push v # p "last_id=#{last_id}" # p v.ast.value_array[0]?.value_array[0]?.value_array[0] v.ast = replace_id_access v.ast, last_id # p v.ast.value_array[0]?.value_array[0]?.value_array[0] tail_rule.strict_sequence.push v else v.ast = replace_id_access v.ast, last_id # вызывать тяжелую артиллерию только тогда, когда действительно надо tail_rule.strict_sequence.push v # PROBLEM fill_head() else head_rule.strict_sequence.push v for _rule in synth_rule_list if head_rule._head_cmp _rule found = _rule break synth_rule_list.push tail_rule if found tail_rule.sequence[0] = "#"+found.ret_hash_key break pass_hash_key = "PI:KEY:<KEY>END_PIhead_rule.sequence.join(',')}_PI:KEY:<KEY>END_PIuidPI:KEY:<KEY>END_PI++}" head_rule.ret_hash_key = pass_hash_key tail_rule.sequence[0] = "#"+pass_hash_key rule = head_rule if !found synth_rule_list.push rule for rule in synth_rule_list rule._mx() rule._strict() # ################################################################################################### @hash_key_list.clear() @hash_key_list.push '*' # special position for string constants @hash_key_list.uappend @extra_hash_key_list for rule in synth_rule_list @hash_key_list.upush rule.ret_hash_key for v in rule.sequence if v[0] == "#" @hash_key_list.upush v.substr 1 for rule in synth_rule_list rule.ret_hash_key_idx = @hash_key_list.idx rule.ret_hash_key # ################################################################################################### @rule_1_by_arg = [] for i in [0 ... @hash_key_list.length] @rule_1_by_arg.push [] @rule_2_by_arg = [] for i in [0 ... (@hash_key_list.length ** 2)] @rule_2_by_arg.push [] pos_to_idx = (pos)=> idx = 0 # if string const if pos[0] == "#" idx = @hash_key_list.idx pos.substr 1 if idx == -1 # DEBUG throw new Error "WTF idx == -1 pos=#{pos} #{JSON.stringify @hash_key_list}" idx mult = @hash_key_list.length for rule in synth_rule_list switch rule.sequence.length when 1 [pos] = rule.sequence idx = pos_to_idx pos @rule_1_by_arg[idx].push rule when 2 [pos_a, pos_b] = rule.sequence idx_a = pos_to_idx pos_a idx_b = pos_to_idx pos_b @rule_2_by_arg[idx_a*mult + idx_b].push rule return hypothesis_find : (node_hypothesis_list, opt={})-> @optimize() if !@_optimized mode_full = false mode_full = opt.mode_full if opt.mode_full? expected_token_idx = -1 if opt.expected_token? if -1 == expected_token_idx = @hash_key_list.idx opt.expected_token throw new Error "unknown expected_token hash_key '#{opt.expected_token}' list=#{JSON.stringify @hash_key_list}" max_hki = @hash_key_list.length max_idx = node_hypothesis_list.length @t_hki_a_pos_old_list.length = max_hki @t_hki_a_pos_new_list.length = max_hki @t_hki_b_pos_old_list.length = max_hki @t_hki_b_pos_new_list.length = max_hki t_hki_a_new_count_list = [] t_hki_b_new_count_list = [] for i in [0 ... max_hki] t_hki_a_new_count_list.push 0 t_hki_b_new_count_list.push 0 init_max_idx = ()-> ret = [] for j in [0 .. max_idx] ret.push [] ret @new_new_list = [] # INCLUSIVE [a,b] for i in [0 ... max_hki] @t_hki_a_pos_old_list[i] = init_max_idx() @t_hki_a_pos_new_list[i] = init_max_idx() @t_hki_b_pos_old_list[i] = init_max_idx() @t_hki_b_pos_new_list[i] = init_max_idx() for v_list,idx in node_hypothesis_list for v in v_list v.a = idx v.b = idx+1 v.hash_key_idx = @hash_key_list.idx v.mx_hash.hash_key if v.hash_key_idx == -1 throw new Error "WTF v.hash_key_idx == -1 v.mx_hash.hash_key=#{v.mx_hash.hash_key} list=#{JSON.stringify @hash_key_list}" @t_hki_a_pos_new_list[v.hash_key_idx][idx ].push v @t_hki_b_pos_new_list[v.hash_key_idx][idx+1].push v if v.hash_key_idx != 0 @t_hki_a_pos_new_list[0][idx ].push v @t_hki_b_pos_new_list[0][idx+1].push v @new_new_list.push v # create hash_key_idx arrays for max_idx ret = [] fin_collect = ()=> ret.clear() if mode_full for pos_list_list,hash_key_idx in @t_hki_a_pos_old_list continue if expected_token_idx != -1 and hash_key_idx != expected_token_idx list = pos_list_list[0] for v in list continue if v.b != max_idx continue if v.hash_key_idx != hash_key_idx ret.push v for v in @new_new_list continue if v.a != 0 continue if v.b != max_idx continue if expected_token_idx != -1 and v.hash_key_idx != expected_token_idx ret.push v if mode_full then false else !!ret.length return ret if fin_collect() # BUG? правила вида term term лезут во все токены в поисках value даже в те, где есть только value_view limit = Gram.magic_attempt_limit_mult*max_idx for i in [1 .. limit] @new_new_list.clear() # MORE OPT jump list for hash_key_idx in [0 ... max_hki] count = 0 for v in @t_hki_a_pos_new_list[hash_key_idx] count += v.length t_hki_a_new_count_list[hash_key_idx] = count count = 0 for v in @t_hki_b_pos_new_list[hash_key_idx] count += v.length t_hki_b_new_count_list[hash_key_idx] = count # L2R rule_2_idx = 0 len = @hash_key_list.length for hash_key_idx_1 in [0 ... len] for hash_key_idx_2 in [0 ... len] rule_list = @rule_2_by_arg[rule_2_idx++] continue if rule_list.length == 0 # new_list_b_count = 1 # new_list_a_count = 1 new_list_b_count = t_hki_b_new_count_list[hash_key_idx_1] new_list_a_count = t_hki_a_new_count_list[hash_key_idx_2] continue if new_list_a_count == 0 and new_list_b_count == 0 node_old_list_b = @t_hki_b_pos_old_list[hash_key_idx_1] node_new_list_b = @t_hki_b_pos_new_list[hash_key_idx_1] node_old_list_a = @t_hki_a_pos_old_list[hash_key_idx_2] node_new_list_a = @t_hki_a_pos_new_list[hash_key_idx_2] # OPT this call can be inlined # keeped for readability fn = (lla, llb)=> # TODO opt no new token at hash_key (count before rule) for list_a,joint_pos in llb continue if list_a.length == 0 list_b = lla[joint_pos] continue if list_b.length == 0 for rule in rule_list # can opt in strict_rule_fn for a in list_a for b in list_b value_array = [a, b] # PROD continue if !rule.strict_rule_fn value_array # DEBUG # try # res = rule.strict_rule_fn value_array # catch err # pp value_array[0] # p rule.strict_rule_fn.toString() # throw err # continue if !res # new_node = new Node new_node.value_view = "#{a.value or a.value_view} #{b.value or b.value_view}" new_node.value_array = value_array rule.mx_rule_fn value_array, new_node.mx_hash new_node.mx_hash.hash_key = rule.ret_hash_key new_node.hash_key_idx = rule.ret_hash_key_idx new_node.a = a.a new_node.b = b.b @new_new_list.push new_node return if new_list_b_count fn node_old_list_a, node_new_list_b if new_list_a_count fn node_new_list_a, node_old_list_b if new_list_a_count and new_list_b_count fn node_new_list_a, node_new_list_b # R2L ничего не даст т.к. new_new_list # singles for rule_list, hash_key_idx in @rule_1_by_arg for node_list in @t_hki_a_pos_new_list[hash_key_idx] for rule in rule_list # can opt in strict_rule_fn for node in node_list value_array = [node] continue if !rule.strict_rule_fn value_array new_node = new Node new_node.value_view = node.value or node.value_view new_node.value_array = value_array rule.mx_rule_fn value_array, new_node.mx_hash new_node.mx_hash.hash_key = rule.ret_hash_key new_node.hash_key_idx = rule.ret_hash_key_idx new_node.a = node.a new_node.b = node.b @new_new_list.push new_node return ret if fin_collect() for hki in [0 ... max_hki] for pos in [0 .. max_idx] if @t_hki_a_pos_new_list[hki][pos].length @t_hki_a_pos_old_list[hki][pos].append @t_hki_a_pos_new_list[hki][pos] @t_hki_a_pos_new_list[hki][pos].clear() if @t_hki_b_pos_new_list[hki][pos].length @t_hki_b_pos_old_list[hki][pos].append @t_hki_b_pos_new_list[hki][pos] @t_hki_b_pos_new_list[hki][pos].clear() for node in @new_new_list @t_hki_a_pos_new_list[node.hash_key_idx][node.a].push node @t_hki_b_pos_new_list[node.hash_key_idx][node.b].push node @t_hki_a_pos_new_list[0][node.a].push node @t_hki_b_pos_new_list[0][node.b].push node if @new_new_list.length == 0 # p "# ###################################################################################################" # pp @t_hki_a_pos_old_list @new_new_list.clear() fin_collect() return ret throw new Error "magic_attempt_limit_mult exceed" go : (node_hypothesis_list, opt={})-> opt.reemerge ?= true ret = @hypothesis_find node_hypothesis_list, opt if opt.reemerge walk = (tree)-> for v in tree.value_array walk v if tree.mx_hash.is_proxy_rule delete tree.mx_hash.is_proxy_rule [head, tail] = tree.value_array tree.value_array.clear() tree.value_array.append head.value_array tree.value_array.push tail str_list = [] for v in tree.value_array str_list.push v.value or v.value_view tree.value_view = str_list.join ' ' return for tree,k in ret ret[k] = tree = tree.deep_clone() walk tree ret
[ { "context": "from version 0.0.1 of ck\n##\n## https://github.com/kaleb/ck\n## sha: 3b83bb352928a856f92f5fa4dd4a5bdf6aacb7", "end": 235, "score": 0.9081936478614807, "start": 230, "tag": "USERNAME", "value": "kaleb" }, { "context": "6f92f5fa4dd4a5bdf6aacb7d1\n##\n## Copyright (c) 2011 James Campos <james.r.campos@gmail.com>\n##\n## MIT Licensed\n\n#[", "end": 325, "score": 0.9998446106910706, "start": 313, "tag": "NAME", "value": "James Campos" }, { "context": "df6aacb7d1\n##\n## Copyright (c) 2011 James Campos <james.r.campos@gmail.com>\n##\n## MIT Licensed\n\n#[coffeekup](http://github.c", "end": 351, "score": 0.9999303221702576, "start": 327, "tag": "EMAIL", "value": "james.r.campos@gmail.com" } ]
modules/gui/tools/ck.coffee
nero-networks/floyd
0
## coffeescript and fs -less ck clone for callback usage ## no files, no raw coffee.. but it runs in the browser ## and it compiles js functions into kup templates ## ## derrifed from version 0.0.1 of ck ## ## https://github.com/kaleb/ck ## sha: 3b83bb352928a856f92f5fa4dd4a5bdf6aacb7d1 ## ## Copyright (c) 2011 James Campos <james.r.campos@gmail.com> ## ## MIT Licensed #[coffeekup](http://github.com/mauricemach/coffeekup) rewrite doctypes = '1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' '5': '<!DOCTYPE html>' 'basic': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">' 'frameset': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">' 'mobile': '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">' 'strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' 'transitional': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' 'xml': '<?xml version="1.0" encoding="utf-8" ?>' tagsNormal = 'a abbr acronym address applet article aside audio b bdo big blockquote body button canvas caption center cite code colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frameset h1 h2 h3 h4 h5 h6 head header hgroup html i iframe ins keygen kbd label legend li map mark menu meter nav noframes noscript object ol optgroup option output p pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr tt u ul var video wbr xmp'.split ' ' tagsSelfClosing = 'area base basefont br col frame hr img input link meta param'.split ' ' TEMPLATES = {} module.exports = (code, config=true)-> if typeof cached is 'boolean' config = cached: config || config isnt false if typeof code is 'function' code = '('+code.toString()+').call(this);' if !config.cached || !TEMPLATES[hash = floyd.tools.strings.hash code] ## html = null indent = null newline = null options = {} nest = (arg) -> if typeof arg is 'function' indent += ' ' if options.format arg = arg.call options.context indent = indent.slice(0, -4) if options.format html += "#{newline}#{indent}" if arg && !(typeof arg is 'object') html += if options.autoescape then esc arg else arg compileTag = (tag, selfClosing) -> scope[tag] = (args...) -> html += "#{newline}#{indent}<#{tag}" if typeof args[0] is 'object' for key, val of args.shift() if typeof val is 'boolean' html += " #{key}" if val is true else html += " #{key}=\"#{val}\"" html += ">" return if selfClosing nest arg for arg in args html += "</#{tag}>" return scope = comment: (str) -> html += "#{newline}#{indent}<!--#{str}-->" return doctype: (key=5) -> html += "#{indent}#{doctypes[key]}" return text: (str)-> html += str return raw: (str)-> html += str return esc: (str) -> str.replace /[&<>"']/g, (c) -> switch c when '&' then '&amp;' when '<' then '&lt;' when '>' then '&gt;' when '"' then '&quot;' when "'" then '&#39;' ie: (expr, arg) -> html += "#{newline}#{indent}<!--[if #{expr}]>" nest arg html += "<![endif]-->" return if config.tags for tag in config.tags compileTag tag, false # don't self close if config.tagsSelfClosing for tag in tagsSelfClosing compileTag tag, true # self close for tag in tagsNormal compileTag tag, false # don't self close for tag in tagsSelfClosing compileTag tag, true # self close handler = new Function 'scope', "with (scope) { #{code}; return }" template = (_options, _fn) -> options = _options # this is needed, because of some strange scoping behaviour fn = _fn # when using arguments[] (_options) directly.. dunno why :-( # if you remove this and use _options directly _options.context is lost inside the # template after first tag callback: # # p @id <p>ctx1</p> # div -> <div> # p @id <p>undefined</p> # </div> html = '' indent = '' newline = if options.format then '\n' else '' handler.call options.context, scope if fn fn null, html.trim() else return html.trim() ## if config.cached TEMPLATES[hash] = template return template else return TEMPLATES[hash]
77182
## coffeescript and fs -less ck clone for callback usage ## no files, no raw coffee.. but it runs in the browser ## and it compiles js functions into kup templates ## ## derrifed from version 0.0.1 of ck ## ## https://github.com/kaleb/ck ## sha: 3b83bb352928a856f92f5fa4dd4a5bdf6aacb7d1 ## ## Copyright (c) 2011 <NAME> <<EMAIL>> ## ## MIT Licensed #[coffeekup](http://github.com/mauricemach/coffeekup) rewrite doctypes = '1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' '5': '<!DOCTYPE html>' 'basic': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">' 'frameset': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">' 'mobile': '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">' 'strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' 'transitional': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' 'xml': '<?xml version="1.0" encoding="utf-8" ?>' tagsNormal = 'a abbr acronym address applet article aside audio b bdo big blockquote body button canvas caption center cite code colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frameset h1 h2 h3 h4 h5 h6 head header hgroup html i iframe ins keygen kbd label legend li map mark menu meter nav noframes noscript object ol optgroup option output p pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr tt u ul var video wbr xmp'.split ' ' tagsSelfClosing = 'area base basefont br col frame hr img input link meta param'.split ' ' TEMPLATES = {} module.exports = (code, config=true)-> if typeof cached is 'boolean' config = cached: config || config isnt false if typeof code is 'function' code = '('+code.toString()+').call(this);' if !config.cached || !TEMPLATES[hash = floyd.tools.strings.hash code] ## html = null indent = null newline = null options = {} nest = (arg) -> if typeof arg is 'function' indent += ' ' if options.format arg = arg.call options.context indent = indent.slice(0, -4) if options.format html += "#{newline}#{indent}" if arg && !(typeof arg is 'object') html += if options.autoescape then esc arg else arg compileTag = (tag, selfClosing) -> scope[tag] = (args...) -> html += "#{newline}#{indent}<#{tag}" if typeof args[0] is 'object' for key, val of args.shift() if typeof val is 'boolean' html += " #{key}" if val is true else html += " #{key}=\"#{val}\"" html += ">" return if selfClosing nest arg for arg in args html += "</#{tag}>" return scope = comment: (str) -> html += "#{newline}#{indent}<!--#{str}-->" return doctype: (key=5) -> html += "#{indent}#{doctypes[key]}" return text: (str)-> html += str return raw: (str)-> html += str return esc: (str) -> str.replace /[&<>"']/g, (c) -> switch c when '&' then '&amp;' when '<' then '&lt;' when '>' then '&gt;' when '"' then '&quot;' when "'" then '&#39;' ie: (expr, arg) -> html += "#{newline}#{indent}<!--[if #{expr}]>" nest arg html += "<![endif]-->" return if config.tags for tag in config.tags compileTag tag, false # don't self close if config.tagsSelfClosing for tag in tagsSelfClosing compileTag tag, true # self close for tag in tagsNormal compileTag tag, false # don't self close for tag in tagsSelfClosing compileTag tag, true # self close handler = new Function 'scope', "with (scope) { #{code}; return }" template = (_options, _fn) -> options = _options # this is needed, because of some strange scoping behaviour fn = _fn # when using arguments[] (_options) directly.. dunno why :-( # if you remove this and use _options directly _options.context is lost inside the # template after first tag callback: # # p @id <p>ctx1</p> # div -> <div> # p @id <p>undefined</p> # </div> html = '' indent = '' newline = if options.format then '\n' else '' handler.call options.context, scope if fn fn null, html.trim() else return html.trim() ## if config.cached TEMPLATES[hash] = template return template else return TEMPLATES[hash]
true
## coffeescript and fs -less ck clone for callback usage ## no files, no raw coffee.. but it runs in the browser ## and it compiles js functions into kup templates ## ## derrifed from version 0.0.1 of ck ## ## https://github.com/kaleb/ck ## sha: 3b83bb352928a856f92f5fa4dd4a5bdf6aacb7d1 ## ## Copyright (c) 2011 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ## ## MIT Licensed #[coffeekup](http://github.com/mauricemach/coffeekup) rewrite doctypes = '1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' '5': '<!DOCTYPE html>' 'basic': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">' 'frameset': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">' 'mobile': '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">' 'strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' 'transitional': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' 'xml': '<?xml version="1.0" encoding="utf-8" ?>' tagsNormal = 'a abbr acronym address applet article aside audio b bdo big blockquote body button canvas caption center cite code colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frameset h1 h2 h3 h4 h5 h6 head header hgroup html i iframe ins keygen kbd label legend li map mark menu meter nav noframes noscript object ol optgroup option output p pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr tt u ul var video wbr xmp'.split ' ' tagsSelfClosing = 'area base basefont br col frame hr img input link meta param'.split ' ' TEMPLATES = {} module.exports = (code, config=true)-> if typeof cached is 'boolean' config = cached: config || config isnt false if typeof code is 'function' code = '('+code.toString()+').call(this);' if !config.cached || !TEMPLATES[hash = floyd.tools.strings.hash code] ## html = null indent = null newline = null options = {} nest = (arg) -> if typeof arg is 'function' indent += ' ' if options.format arg = arg.call options.context indent = indent.slice(0, -4) if options.format html += "#{newline}#{indent}" if arg && !(typeof arg is 'object') html += if options.autoescape then esc arg else arg compileTag = (tag, selfClosing) -> scope[tag] = (args...) -> html += "#{newline}#{indent}<#{tag}" if typeof args[0] is 'object' for key, val of args.shift() if typeof val is 'boolean' html += " #{key}" if val is true else html += " #{key}=\"#{val}\"" html += ">" return if selfClosing nest arg for arg in args html += "</#{tag}>" return scope = comment: (str) -> html += "#{newline}#{indent}<!--#{str}-->" return doctype: (key=5) -> html += "#{indent}#{doctypes[key]}" return text: (str)-> html += str return raw: (str)-> html += str return esc: (str) -> str.replace /[&<>"']/g, (c) -> switch c when '&' then '&amp;' when '<' then '&lt;' when '>' then '&gt;' when '"' then '&quot;' when "'" then '&#39;' ie: (expr, arg) -> html += "#{newline}#{indent}<!--[if #{expr}]>" nest arg html += "<![endif]-->" return if config.tags for tag in config.tags compileTag tag, false # don't self close if config.tagsSelfClosing for tag in tagsSelfClosing compileTag tag, true # self close for tag in tagsNormal compileTag tag, false # don't self close for tag in tagsSelfClosing compileTag tag, true # self close handler = new Function 'scope', "with (scope) { #{code}; return }" template = (_options, _fn) -> options = _options # this is needed, because of some strange scoping behaviour fn = _fn # when using arguments[] (_options) directly.. dunno why :-( # if you remove this and use _options directly _options.context is lost inside the # template after first tag callback: # # p @id <p>ctx1</p> # div -> <div> # p @id <p>undefined</p> # </div> html = '' indent = '' newline = if options.format then '\n' else '' handler.call options.context, scope if fn fn null, html.trim() else return html.trim() ## if config.cached TEMPLATES[hash] = template return template else return TEMPLATES[hash]
[ { "context": "#\n# Copyright 2014 Carsten Klein\n#\n# Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9998569488525391, "start": 19, "tag": "NAME", "value": "Carsten Klein" }, { "context": "calns instanceof Namespace)\n\n key = localName\n if currentContext instanceof Name", "end": 13094, "score": 0.9714950323104858, "start": 13085, "tag": "KEY", "value": "localName" }, { "context": "xt instanceof Namespace\n\n key = \"#{currentContext.nsQualifiedName}.#{localName}\"\n\n ", "end": 13180, "score": 0.8113235831260681, "start": 13177, "tag": "KEY", "value": "\"#{" }, { "context": "ce\n\n key = \"#{currentContext.nsQualifiedName}.#{localName}\"\n\n throw new Error \"will not redecl", "end": 13225, "score": 0.8230480551719666, "start": 13197, "tag": "KEY", "value": "QualifiedName}.#{localName}\"" } ]
src/namespaces.coffee
vibejs/vibejs-namespaces
0
# # Copyright 2014 Carsten Klein # # 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. # # we export most of this to the global namespace exports = window ? global # guard preventing us from exporting twice unless exports.namespace? # The default context **nsDefaultContext** being used for declaring namespaces in. # On the server this will default to **global**, whereas on the client aka browser # this will default to **window**. # # @type Object # @readonly # @memberof vibejs.lang nsDefaultContext = exports # Guard preventing Namespace constructor from being called directly. nsDeclaring = false # The regular expression used for validating user provided namespace # identifiers. # # /^[a-zA-Z_$]+[a-zA-Z_$0-9]*(?:[.][a-zA-Z_$]+[a-zA-Z_$0-9]*)*$/ # # @type {RegExp} # @readonly # @memberof vibejs.lang.constants NS_QNAME_RE = /^[a-zA-Z_$]+[a-zA-Z_$0-9]*(?:[.][a-zA-Z_$]+[a-zA-Z_$0-9]*)*$/ # The class **Namespace** models a container for user defined properties and # namespaces. # # Instances of this can only be created using {@link Namespaces.nsDeclare}. # # exposed for testing purposes and instanceof checks only # # @class # @property {String} nsQualifiedName - the qualified name of this (readonly) # @property {Namespaces.Namespace} nsParent - the parent namespace or null (readonly) # @property {Object} nsNamespaces - the direct child namespaces of this or the empty hash (readonly) # @property {Object} nsClasses - the classes declared in this or the empty hash (readonly) # @property {Object} nsFunctions - the functions declared in this or the empty hash (readonly) # @property {Object} nsObjects - the objects declared in this or the empty hash (readonly) # @property {Object} nsScalars - the scalars declared in this or the empty hash (readonly) # @memberof vibejs.lang class Namespace constructor: (localName, parent, logger) -> if not nsDeclaring throw new TypeError 'Namespace must not be instantiated directly. Use namespace instead.' cachedQualifiedName = null frozen = false if parent and not (parent instanceof Namespace) throw new TypeError 'parent must be an instance of vibejs.lang.namespace.Namespace' # make sure that the logger has a debug method if logger and not 'function' == typeof logger.debug throw new TypeError 'logger does not have a debug(...) method.' # @property String _logger optional logger used for debugging # @private # @readonly Object.defineProperty @, '_logger', enumerable : false get : -> logger @_logger?.debug "Namespace:constructor:localName = #{localName}" @_logger?.debug "Namespace:constructor:parent = #{parent?.nsQualifiedName}" # @property String nsLocalName the local name of this # @readonly Object.defineProperty @, 'nsLocalName', enumerable : false get : -> localName # @property Namespace nsParent the parent namespace of this or null # @readonly Object.defineProperty @, 'nsParent', enumerable : false get : -> parent # @property String nsQualifiedName the qualified name of this # @readonly Object.defineProperty @, 'nsQualifiedName', enumerable : false get : -> if cachedQualifiedName is null @_logger?.debug "Namespace:nsQualifiedName:building qualified name" components = [] ns = @ while ns? components.push ns.nsLocalName ns = ns.nsParent components.reverse() cachedQualifiedName = components.join '.' @_logger?.debug "Namespace:nsQualifiedName:built qualified name #{cachedQualifiedName}" cachedQualifiedName # @property String name alias for nsQualifiedName # @readonly Object.defineProperty @, 'name', enumerable : false get : -> @nsQualifiedName # @property Boolean nsFrozen true whether this was frozen, false otherwise # @readonly Object.defineProperty @, 'nsFrozen', enumerable : false get : -> frozen # Extends this by the specified declarations. Will not override existing members of # this unless told otherwise. # # @method nsExtend # @param Object # @return this # @throws Error thrown in case that this was frozen Object.defineProperty @, 'nsExtend', enumerable : false get : -> if @nsFrozen @_logger?.debug "Namespace:nsExtend:attempted to extend frozen namespace #{@nsQualifiedName}" throw new Error "namespace #{@nsQualifiedName} is frozen and cannot be extended." (options = {}) -> @_logger?.debug "Namespace:nsExtend:extending namespace #{@nsQualifiedName}" override = if options.override == true then true else false configurable = if options.configurable == false then false else true declarations = options.extend || {} for key of declarations if @[key] is undefined or override enumerable = /^_/.exec(key) is null @_logger?.debug "Namespace:nsExtend:defining #{key} = #{declarations[key]}" if not enumerable @_logger?.debug "Namespace:nsExtend:defining #{key} non enumerable" if not configurable @_logger?.debug "Namespace:nsExtend:defining #{key} non configurable" if not configurable or not enumerable applier = (key, value) -> Object.defineProperty @, key, enumerable : enumerable configurable : configurable writable : configurable value : value applier.call @, key, declarations[key] @_logger?.debug "Namespace:nsExtend:defined #{key}" else @[key] = declarations[key] @_logger?.debug "Namespace:nsExtend:defined #{key}" else @_logger?.debug "Namespace:nsExtend:not overriding existing #{key}" @ # Freezes this so that it can no longer be extended or modified. # Calling this multiple times has no effect. # # @return this Object.defineProperty @, 'nsFreeze', enumerable : false get : -> -> if not frozen @_logger?.debug "Namespace:nsFreeze:trying to freeze namespace #{@nsQualifiedName}" freezer = Object.freeze || Object.seal if freezer frozen = true freezer @ @_logger?.debug "Namespace:nsFreeze:namespace #{@nsQualifiedName} was frozen" else @_logger?.debug "Namespace:nsFreeze:neither Object.freeze nor Object.seal are available" @ # Returns an object containing the children of this or this if no filter object or function was # specified. # # The filter function or method must accept two arguments, namely key and value. # # @method nsChildren # @param Function|Object:null a filter function or object with a filter method or function # @return Object the filtered children or this # @throws Error thrown in case that filter is not null and not a function or object # with either a filter function or method Object.defineProperty @, 'nsChildren', enumerable : false get : -> (filter = null) -> result = @ actualFilter = filter if filter != null and 'object' == typeof filter actualFilter = filter.filter if actualFilter is undefined throw new TypeError 'filter must be either a function or object with a filter method or function' if actualFilter result = {} for key of @ if actualFilter(key, @[key]) result[key] = @[key] result # The function namespace models a factory for instances of type Namespace. # # TODO:document # # @param String qname the qualified name of the namespace # @param Object options additional parameters # @option options Object|Namespace:nsDefaultContext context the context to which the resulting namespace will be assigned to # @option options Boolean:false freeze determines whether the resulting namespace will be frozen so that # it cannot be extended # @option options Object:null extend optional namespace extension # @option options Object:null logger optional logger for outputting debug information # @memberof vibejs.lang exports.namespace = (qname, options = {})-> result = null logger = options.logger || null context = options.context || nsDefaultContext # make sure that the logger has a debug method if logger and not 'function' == typeof logger.debug throw new TypeError 'logger does not have a debug(...) method.' logger?.debug "namespace:get or declare namespace #{qname} in context #{context.name || if context == nsDefaultContext then 'default' else 'user defined'}" # make sure that qname is valid if qname is null or qname is undefined or null == NS_QNAME_RE.exec qname throw new TypeError "invalid qname '#{qname}'." # declare namespaces in their reverse order currentContext = context components = qname.split '.' components.reverse() while components.length # TODO:logging localName = components.pop() localns = currentContext[localName] if localns is undefined # associate parent namespace parent = null if currentContext instanceof Namespace parent = currentContext # fail early in case that parent is frozen if parent.nsFrozen throw new Error "namespace #{parent.nsQualifiedName} is frozen and cannot be extended." # declare and finalize namespace nsDeclaring = true localns = new Namespace localName, parent, logger nsDeclaring = false if /^_/.exec(localName) is null currentContext[localName] = localns else Object.defineProperty currentContext, localName, enumerable : false value : localns else if not (localns instanceof Namespace) key = localName if currentContext instanceof Namespace key = "#{currentContext.nsQualifiedName}.#{localName}" throw new Error "will not redeclare existing value for key #{key} in the specified context" currentContext = result = localns if options.extend result.nsExtend options if options.freeze == true result.nsFreeze() result # @namespace vibejs.lang namespace 'vibejs.lang', configurable : false extend : nsDefaultContext : nsDefaultContext Namespace : Namespace namespace : namespace # @namespace vibejs.lang.constants namespace 'vibejs.lang.constants', configurable : false extend : NS_QNAME_RE : NS_QNAME_RE
65283
# # Copyright 2014 <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. # # we export most of this to the global namespace exports = window ? global # guard preventing us from exporting twice unless exports.namespace? # The default context **nsDefaultContext** being used for declaring namespaces in. # On the server this will default to **global**, whereas on the client aka browser # this will default to **window**. # # @type Object # @readonly # @memberof vibejs.lang nsDefaultContext = exports # Guard preventing Namespace constructor from being called directly. nsDeclaring = false # The regular expression used for validating user provided namespace # identifiers. # # /^[a-zA-Z_$]+[a-zA-Z_$0-9]*(?:[.][a-zA-Z_$]+[a-zA-Z_$0-9]*)*$/ # # @type {RegExp} # @readonly # @memberof vibejs.lang.constants NS_QNAME_RE = /^[a-zA-Z_$]+[a-zA-Z_$0-9]*(?:[.][a-zA-Z_$]+[a-zA-Z_$0-9]*)*$/ # The class **Namespace** models a container for user defined properties and # namespaces. # # Instances of this can only be created using {@link Namespaces.nsDeclare}. # # exposed for testing purposes and instanceof checks only # # @class # @property {String} nsQualifiedName - the qualified name of this (readonly) # @property {Namespaces.Namespace} nsParent - the parent namespace or null (readonly) # @property {Object} nsNamespaces - the direct child namespaces of this or the empty hash (readonly) # @property {Object} nsClasses - the classes declared in this or the empty hash (readonly) # @property {Object} nsFunctions - the functions declared in this or the empty hash (readonly) # @property {Object} nsObjects - the objects declared in this or the empty hash (readonly) # @property {Object} nsScalars - the scalars declared in this or the empty hash (readonly) # @memberof vibejs.lang class Namespace constructor: (localName, parent, logger) -> if not nsDeclaring throw new TypeError 'Namespace must not be instantiated directly. Use namespace instead.' cachedQualifiedName = null frozen = false if parent and not (parent instanceof Namespace) throw new TypeError 'parent must be an instance of vibejs.lang.namespace.Namespace' # make sure that the logger has a debug method if logger and not 'function' == typeof logger.debug throw new TypeError 'logger does not have a debug(...) method.' # @property String _logger optional logger used for debugging # @private # @readonly Object.defineProperty @, '_logger', enumerable : false get : -> logger @_logger?.debug "Namespace:constructor:localName = #{localName}" @_logger?.debug "Namespace:constructor:parent = #{parent?.nsQualifiedName}" # @property String nsLocalName the local name of this # @readonly Object.defineProperty @, 'nsLocalName', enumerable : false get : -> localName # @property Namespace nsParent the parent namespace of this or null # @readonly Object.defineProperty @, 'nsParent', enumerable : false get : -> parent # @property String nsQualifiedName the qualified name of this # @readonly Object.defineProperty @, 'nsQualifiedName', enumerable : false get : -> if cachedQualifiedName is null @_logger?.debug "Namespace:nsQualifiedName:building qualified name" components = [] ns = @ while ns? components.push ns.nsLocalName ns = ns.nsParent components.reverse() cachedQualifiedName = components.join '.' @_logger?.debug "Namespace:nsQualifiedName:built qualified name #{cachedQualifiedName}" cachedQualifiedName # @property String name alias for nsQualifiedName # @readonly Object.defineProperty @, 'name', enumerable : false get : -> @nsQualifiedName # @property Boolean nsFrozen true whether this was frozen, false otherwise # @readonly Object.defineProperty @, 'nsFrozen', enumerable : false get : -> frozen # Extends this by the specified declarations. Will not override existing members of # this unless told otherwise. # # @method nsExtend # @param Object # @return this # @throws Error thrown in case that this was frozen Object.defineProperty @, 'nsExtend', enumerable : false get : -> if @nsFrozen @_logger?.debug "Namespace:nsExtend:attempted to extend frozen namespace #{@nsQualifiedName}" throw new Error "namespace #{@nsQualifiedName} is frozen and cannot be extended." (options = {}) -> @_logger?.debug "Namespace:nsExtend:extending namespace #{@nsQualifiedName}" override = if options.override == true then true else false configurable = if options.configurable == false then false else true declarations = options.extend || {} for key of declarations if @[key] is undefined or override enumerable = /^_/.exec(key) is null @_logger?.debug "Namespace:nsExtend:defining #{key} = #{declarations[key]}" if not enumerable @_logger?.debug "Namespace:nsExtend:defining #{key} non enumerable" if not configurable @_logger?.debug "Namespace:nsExtend:defining #{key} non configurable" if not configurable or not enumerable applier = (key, value) -> Object.defineProperty @, key, enumerable : enumerable configurable : configurable writable : configurable value : value applier.call @, key, declarations[key] @_logger?.debug "Namespace:nsExtend:defined #{key}" else @[key] = declarations[key] @_logger?.debug "Namespace:nsExtend:defined #{key}" else @_logger?.debug "Namespace:nsExtend:not overriding existing #{key}" @ # Freezes this so that it can no longer be extended or modified. # Calling this multiple times has no effect. # # @return this Object.defineProperty @, 'nsFreeze', enumerable : false get : -> -> if not frozen @_logger?.debug "Namespace:nsFreeze:trying to freeze namespace #{@nsQualifiedName}" freezer = Object.freeze || Object.seal if freezer frozen = true freezer @ @_logger?.debug "Namespace:nsFreeze:namespace #{@nsQualifiedName} was frozen" else @_logger?.debug "Namespace:nsFreeze:neither Object.freeze nor Object.seal are available" @ # Returns an object containing the children of this or this if no filter object or function was # specified. # # The filter function or method must accept two arguments, namely key and value. # # @method nsChildren # @param Function|Object:null a filter function or object with a filter method or function # @return Object the filtered children or this # @throws Error thrown in case that filter is not null and not a function or object # with either a filter function or method Object.defineProperty @, 'nsChildren', enumerable : false get : -> (filter = null) -> result = @ actualFilter = filter if filter != null and 'object' == typeof filter actualFilter = filter.filter if actualFilter is undefined throw new TypeError 'filter must be either a function or object with a filter method or function' if actualFilter result = {} for key of @ if actualFilter(key, @[key]) result[key] = @[key] result # The function namespace models a factory for instances of type Namespace. # # TODO:document # # @param String qname the qualified name of the namespace # @param Object options additional parameters # @option options Object|Namespace:nsDefaultContext context the context to which the resulting namespace will be assigned to # @option options Boolean:false freeze determines whether the resulting namespace will be frozen so that # it cannot be extended # @option options Object:null extend optional namespace extension # @option options Object:null logger optional logger for outputting debug information # @memberof vibejs.lang exports.namespace = (qname, options = {})-> result = null logger = options.logger || null context = options.context || nsDefaultContext # make sure that the logger has a debug method if logger and not 'function' == typeof logger.debug throw new TypeError 'logger does not have a debug(...) method.' logger?.debug "namespace:get or declare namespace #{qname} in context #{context.name || if context == nsDefaultContext then 'default' else 'user defined'}" # make sure that qname is valid if qname is null or qname is undefined or null == NS_QNAME_RE.exec qname throw new TypeError "invalid qname '#{qname}'." # declare namespaces in their reverse order currentContext = context components = qname.split '.' components.reverse() while components.length # TODO:logging localName = components.pop() localns = currentContext[localName] if localns is undefined # associate parent namespace parent = null if currentContext instanceof Namespace parent = currentContext # fail early in case that parent is frozen if parent.nsFrozen throw new Error "namespace #{parent.nsQualifiedName} is frozen and cannot be extended." # declare and finalize namespace nsDeclaring = true localns = new Namespace localName, parent, logger nsDeclaring = false if /^_/.exec(localName) is null currentContext[localName] = localns else Object.defineProperty currentContext, localName, enumerable : false value : localns else if not (localns instanceof Namespace) key = <KEY> if currentContext instanceof Namespace key = <KEY>currentContext.ns<KEY> throw new Error "will not redeclare existing value for key #{key} in the specified context" currentContext = result = localns if options.extend result.nsExtend options if options.freeze == true result.nsFreeze() result # @namespace vibejs.lang namespace 'vibejs.lang', configurable : false extend : nsDefaultContext : nsDefaultContext Namespace : Namespace namespace : namespace # @namespace vibejs.lang.constants namespace 'vibejs.lang.constants', configurable : false extend : NS_QNAME_RE : NS_QNAME_RE
true
# # Copyright 2014 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. # # we export most of this to the global namespace exports = window ? global # guard preventing us from exporting twice unless exports.namespace? # The default context **nsDefaultContext** being used for declaring namespaces in. # On the server this will default to **global**, whereas on the client aka browser # this will default to **window**. # # @type Object # @readonly # @memberof vibejs.lang nsDefaultContext = exports # Guard preventing Namespace constructor from being called directly. nsDeclaring = false # The regular expression used for validating user provided namespace # identifiers. # # /^[a-zA-Z_$]+[a-zA-Z_$0-9]*(?:[.][a-zA-Z_$]+[a-zA-Z_$0-9]*)*$/ # # @type {RegExp} # @readonly # @memberof vibejs.lang.constants NS_QNAME_RE = /^[a-zA-Z_$]+[a-zA-Z_$0-9]*(?:[.][a-zA-Z_$]+[a-zA-Z_$0-9]*)*$/ # The class **Namespace** models a container for user defined properties and # namespaces. # # Instances of this can only be created using {@link Namespaces.nsDeclare}. # # exposed for testing purposes and instanceof checks only # # @class # @property {String} nsQualifiedName - the qualified name of this (readonly) # @property {Namespaces.Namespace} nsParent - the parent namespace or null (readonly) # @property {Object} nsNamespaces - the direct child namespaces of this or the empty hash (readonly) # @property {Object} nsClasses - the classes declared in this or the empty hash (readonly) # @property {Object} nsFunctions - the functions declared in this or the empty hash (readonly) # @property {Object} nsObjects - the objects declared in this or the empty hash (readonly) # @property {Object} nsScalars - the scalars declared in this or the empty hash (readonly) # @memberof vibejs.lang class Namespace constructor: (localName, parent, logger) -> if not nsDeclaring throw new TypeError 'Namespace must not be instantiated directly. Use namespace instead.' cachedQualifiedName = null frozen = false if parent and not (parent instanceof Namespace) throw new TypeError 'parent must be an instance of vibejs.lang.namespace.Namespace' # make sure that the logger has a debug method if logger and not 'function' == typeof logger.debug throw new TypeError 'logger does not have a debug(...) method.' # @property String _logger optional logger used for debugging # @private # @readonly Object.defineProperty @, '_logger', enumerable : false get : -> logger @_logger?.debug "Namespace:constructor:localName = #{localName}" @_logger?.debug "Namespace:constructor:parent = #{parent?.nsQualifiedName}" # @property String nsLocalName the local name of this # @readonly Object.defineProperty @, 'nsLocalName', enumerable : false get : -> localName # @property Namespace nsParent the parent namespace of this or null # @readonly Object.defineProperty @, 'nsParent', enumerable : false get : -> parent # @property String nsQualifiedName the qualified name of this # @readonly Object.defineProperty @, 'nsQualifiedName', enumerable : false get : -> if cachedQualifiedName is null @_logger?.debug "Namespace:nsQualifiedName:building qualified name" components = [] ns = @ while ns? components.push ns.nsLocalName ns = ns.nsParent components.reverse() cachedQualifiedName = components.join '.' @_logger?.debug "Namespace:nsQualifiedName:built qualified name #{cachedQualifiedName}" cachedQualifiedName # @property String name alias for nsQualifiedName # @readonly Object.defineProperty @, 'name', enumerable : false get : -> @nsQualifiedName # @property Boolean nsFrozen true whether this was frozen, false otherwise # @readonly Object.defineProperty @, 'nsFrozen', enumerable : false get : -> frozen # Extends this by the specified declarations. Will not override existing members of # this unless told otherwise. # # @method nsExtend # @param Object # @return this # @throws Error thrown in case that this was frozen Object.defineProperty @, 'nsExtend', enumerable : false get : -> if @nsFrozen @_logger?.debug "Namespace:nsExtend:attempted to extend frozen namespace #{@nsQualifiedName}" throw new Error "namespace #{@nsQualifiedName} is frozen and cannot be extended." (options = {}) -> @_logger?.debug "Namespace:nsExtend:extending namespace #{@nsQualifiedName}" override = if options.override == true then true else false configurable = if options.configurable == false then false else true declarations = options.extend || {} for key of declarations if @[key] is undefined or override enumerable = /^_/.exec(key) is null @_logger?.debug "Namespace:nsExtend:defining #{key} = #{declarations[key]}" if not enumerable @_logger?.debug "Namespace:nsExtend:defining #{key} non enumerable" if not configurable @_logger?.debug "Namespace:nsExtend:defining #{key} non configurable" if not configurable or not enumerable applier = (key, value) -> Object.defineProperty @, key, enumerable : enumerable configurable : configurable writable : configurable value : value applier.call @, key, declarations[key] @_logger?.debug "Namespace:nsExtend:defined #{key}" else @[key] = declarations[key] @_logger?.debug "Namespace:nsExtend:defined #{key}" else @_logger?.debug "Namespace:nsExtend:not overriding existing #{key}" @ # Freezes this so that it can no longer be extended or modified. # Calling this multiple times has no effect. # # @return this Object.defineProperty @, 'nsFreeze', enumerable : false get : -> -> if not frozen @_logger?.debug "Namespace:nsFreeze:trying to freeze namespace #{@nsQualifiedName}" freezer = Object.freeze || Object.seal if freezer frozen = true freezer @ @_logger?.debug "Namespace:nsFreeze:namespace #{@nsQualifiedName} was frozen" else @_logger?.debug "Namespace:nsFreeze:neither Object.freeze nor Object.seal are available" @ # Returns an object containing the children of this or this if no filter object or function was # specified. # # The filter function or method must accept two arguments, namely key and value. # # @method nsChildren # @param Function|Object:null a filter function or object with a filter method or function # @return Object the filtered children or this # @throws Error thrown in case that filter is not null and not a function or object # with either a filter function or method Object.defineProperty @, 'nsChildren', enumerable : false get : -> (filter = null) -> result = @ actualFilter = filter if filter != null and 'object' == typeof filter actualFilter = filter.filter if actualFilter is undefined throw new TypeError 'filter must be either a function or object with a filter method or function' if actualFilter result = {} for key of @ if actualFilter(key, @[key]) result[key] = @[key] result # The function namespace models a factory for instances of type Namespace. # # TODO:document # # @param String qname the qualified name of the namespace # @param Object options additional parameters # @option options Object|Namespace:nsDefaultContext context the context to which the resulting namespace will be assigned to # @option options Boolean:false freeze determines whether the resulting namespace will be frozen so that # it cannot be extended # @option options Object:null extend optional namespace extension # @option options Object:null logger optional logger for outputting debug information # @memberof vibejs.lang exports.namespace = (qname, options = {})-> result = null logger = options.logger || null context = options.context || nsDefaultContext # make sure that the logger has a debug method if logger and not 'function' == typeof logger.debug throw new TypeError 'logger does not have a debug(...) method.' logger?.debug "namespace:get or declare namespace #{qname} in context #{context.name || if context == nsDefaultContext then 'default' else 'user defined'}" # make sure that qname is valid if qname is null or qname is undefined or null == NS_QNAME_RE.exec qname throw new TypeError "invalid qname '#{qname}'." # declare namespaces in their reverse order currentContext = context components = qname.split '.' components.reverse() while components.length # TODO:logging localName = components.pop() localns = currentContext[localName] if localns is undefined # associate parent namespace parent = null if currentContext instanceof Namespace parent = currentContext # fail early in case that parent is frozen if parent.nsFrozen throw new Error "namespace #{parent.nsQualifiedName} is frozen and cannot be extended." # declare and finalize namespace nsDeclaring = true localns = new Namespace localName, parent, logger nsDeclaring = false if /^_/.exec(localName) is null currentContext[localName] = localns else Object.defineProperty currentContext, localName, enumerable : false value : localns else if not (localns instanceof Namespace) key = PI:KEY:<KEY>END_PI if currentContext instanceof Namespace key = PI:KEY:<KEY>END_PIcurrentContext.nsPI:KEY:<KEY>END_PI throw new Error "will not redeclare existing value for key #{key} in the specified context" currentContext = result = localns if options.extend result.nsExtend options if options.freeze == true result.nsFreeze() result # @namespace vibejs.lang namespace 'vibejs.lang', configurable : false extend : nsDefaultContext : nsDefaultContext Namespace : Namespace namespace : namespace # @namespace vibejs.lang.constants namespace 'vibejs.lang.constants', configurable : false extend : NS_QNAME_RE : NS_QNAME_RE
[ { "context": "API Blueprint fixtures as well)\n sensitiveKey = 'token'\n sensitiveHeaderName = 'authorization'\n sensit", "end": 340, "score": 0.6263347268104553, "start": 335, "tag": "KEY", "value": "token" }, { "context": "eHeaderName = 'authorization'\n sensitiveValue = '5229c6e8e4b0bd7dbb07e29c'\n\n # recording events sent to reporters\n events", "end": 426, "score": 0.9963432550430298, "start": 402, "tag": "KEY", "value": "5229c6e8e4b0bd7dbb07e29c" }, { "context": "te')\n app = createServerFromResponse({token: 123, name: 'Bob'}) # 'token' should be string → faili", "end": 6487, "score": 0.9221096634864807, "start": 6484, "tag": "PASSWORD", "value": "123" }, { "context": "pp = createServerFromResponse({token: 123, name: 'Bob'}) # 'token' should be string → failing test\n\n ", "end": 6499, "score": 0.6970839500427246, "start": 6496, "tag": "NAME", "value": "Bob" }, { "context": "rs')\n app = createServerFromResponse({name: 'Bob'}) # Authorization header is missing → failing te", "end": 10719, "score": 0.9921517372131348, "start": 10716, "tag": "NAME", "value": "Bob" }, { "context": "ng')\n app = createServerFromResponse({name: 'Bob'}) # passing test\n\n runDreddWithServer(dredd", "end": 16098, "score": 0.9987887740135193, "start": 16095, "tag": "NAME", "value": "Bob" }, { "context": "er')\n app = createServerFromResponse({name: 'Bob'}) # passing test\n\n runDreddWithServer(dredd", "end": 18848, "score": 0.9988721013069153, "start": 18845, "tag": "NAME", "value": "Bob" }, { "context": "ks')\n app = createServerFromResponse({name: 'Bob'}) # passing test\n\n runDreddWithServer(dredd", "end": 21839, "score": 0.7274104952812195, "start": 21836, "tag": "NAME", "value": "Bob" }, { "context": "ks')\n app = createServerFromResponse({name: 'Bob'}) # passing test\n\n runDreddWithServer(dredd", "end": 22986, "score": 0.9984544515609741, "start": 22983, "tag": "NAME", "value": "Bob" } ]
test/integration/sanitation-test.coffee
DMG-Cloud-Services/dmg-dredd
1
{assert} = require('chai') clone = require('clone') {EventEmitter} = require('events') {runDredd, createServer, runDreddWithServer} = require('./helpers') Dredd = require('../../src/dredd') describe('Sanitation of Reported Data', -> # sample sensitive data (this value is used in API Blueprint fixtures as well) sensitiveKey = 'token' sensitiveHeaderName = 'authorization' sensitiveValue = '5229c6e8e4b0bd7dbb07e29c' # recording events sent to reporters events = undefined emitter = undefined beforeEach( -> events = [] emitter = new EventEmitter() # Dredd emits 'test *' events and reporters listen on them. To test whether # sensitive data will or won't make it to reporters, we need to capture all # the emitted events. We're using 'clone' to prevent propagation of subsequent # modifications of the 'test' object (Dredd can change the data after they're # reported and by reference they would change also here in the 'events' array). emitter.on('test start', (test) -> events.push({name: 'test start', test: clone(test)})) emitter.on('test pass', (test) -> events.push({name: 'test pass', test: clone(test)})) emitter.on('test skip', (test) -> events.push({name: 'test skip', test: clone(test)})) emitter.on('test fail', (test) -> events.push({name: 'test fail', test: clone(test)})) emitter.on('test error', (err, test) -> events.push({name: 'test error', test: clone(test), err})) # 'start' and 'end' events are asynchronous and they do not carry any data # significant for following scenarios emitter.on('start', (apiDescription, cb) -> events.push({name: 'start'}); cb() ) emitter.on('end', (cb) -> events.push({name: 'end'}); cb() ) ) # helper for preparing Dredd instance with our custom emitter createDreddFromFixture = (fixtureName) -> new Dredd({ emitter options: { path: "./test/fixtures/sanitation/#{fixtureName}.apib" hookfiles: "./test/fixtures/sanitation/#{fixtureName}.js" } }) # helper for preparing the server under test createServerFromResponse = (response) -> app = createServer() app.put('/resource', (req, res) -> res.json(response)) return app describe('Sanitation of the Entire Request Body', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('entire-request-body') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of the Entire Response Body', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('entire-response-body') app = createServerFromResponse({token: 123}) # 'token' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain response body', -> assert.equal(events[2].test.actual.body, '') assert.equal(events[2].test.expected.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of a Request Body Attribute', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('request-body-attribute') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential body attribute', -> attrs = Object.keys(JSON.parse(events[2].test.request.body)) assert.deepEqual(attrs, ['name']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of a Response Body Attribute', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('response-body-attribute') app = createServerFromResponse({token: 123, name: 'Bob'}) # 'token' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential body attribute', -> attrs = Object.keys(JSON.parse(events[2].test.actual.body)) assert.deepEqual(attrs, ['name']) attrs = Object.keys(JSON.parse(events[2].test.expected.body)) assert.deepEqual(attrs, ['name']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Plain Text Response Body by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('plain-text-response-body') app = createServerFromResponse("#{sensitiveKey}=42#{sensitiveValue}") # should be without '42' → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(events[2].test.actual.body, '--- CENSORED ---') assert.include(events[2].test.expected.body, '--- CENSORED ---') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Request Headers', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('request-headers') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential header', -> names = (name.toLowerCase() for name of events[2].test.request.headers) assert.notInclude(names, sensitiveHeaderName) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events).toLowerCase() assert.notInclude(test, sensitiveHeaderName) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> logging = dreddRuntimeInfo.logging.toLowerCase() assert.notInclude(logging, sensitiveHeaderName) assert.notInclude(logging, sensitiveValue) ) ) describe('Sanitation of Response Headers', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('response-headers') app = createServerFromResponse({name: 'Bob'}) # Authorization header is missing → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential header', -> names = (name.toLowerCase() for name of events[2].test.actual.headers) assert.notInclude(names, sensitiveHeaderName) names = (name.toLowerCase() for name of events[2].test.expected.headers) assert.notInclude(names, sensitiveHeaderName) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events).toLowerCase() assert.notInclude(test, sensitiveHeaderName) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> logging = dreddRuntimeInfo.logging.toLowerCase() assert.notInclude(logging, sensitiveHeaderName) assert.notInclude(logging, sensitiveValue) ) ) describe('Sanitation of URI Parameters by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('uri-parameters') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(events[2].test.request.uri, 'CENSORED') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) # This fails because it's not possible to do 'transaction.test = myOwnTestObject;' # at the moment, Dredd ignores the new object. describe('Sanitation of Any Content by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('any-content-pattern-matching') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(JSON.stringify(events), 'CENSORED') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Ultimate \'afterEach\' Guard Using Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('any-content-guard-pattern-matching') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) it('custom error message is printed', -> assert.include(dreddRuntimeInfo.logging, 'Sensitive data would be sent to Dredd reporter') ) ) describe('Sanitation of Test Data of Passing Transaction', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-passing') app = createServerFromResponse({name: 'Bob'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one passing test', -> assert.equal(dreddRuntimeInfo.stats.passes, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test pass', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Failed in \'before\' Hook', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-failed-before') runDredd(dredd, (args...) -> [err, dreddRuntimeInfo] = args done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test is failed', -> assert.equal(events[2].test.status, 'fail') assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'fail') ) it('emitted test data results contain just \'general\' section', -> assert.deepEqual(Object.keys(events[2].test.results), ['general']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Failed in \'after\' Hook', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-failed-after') app = createServerFromResponse({name: 'Bob'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('emitted test is failed', -> assert.equal(events[2].test.status, 'fail') assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'fail') ) it('emitted test data results contain all regular sections', -> assert.deepEqual(Object.keys(events[2].test.results), ['general', 'headers', 'body', 'statusCode']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Skipped', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-skipped') runDredd(dredd, (args...) -> [err, dreddRuntimeInfo] = args done() ) ) it('results in one skipped test', -> assert.equal(dreddRuntimeInfo.stats.skipped, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test skip', 'end' ]) ) it('emitted test is skipped', -> assert.equal(events[2].test.status, 'skip') assert.deepEqual(Object.keys(events[2].test.results), ['general']) assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'skip') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data of Transaction With Erroring Hooks', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-erroring-hooks') app = createServerFromResponse({name: 'Bob'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one erroring test', -> assert.equal(dreddRuntimeInfo.stats.errors, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test error', 'end' ]) ) it('sensitive data leak to emitted test data', -> test = JSON.stringify(events) assert.include(test, sensitiveKey) assert.include(test, sensitiveValue) ) it('sensitive data leak to Dredd output', -> assert.include(dreddRuntimeInfo.logging, sensitiveKey) assert.include(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data of Transaction With Secured Erroring Hooks', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-secured-erroring-hooks') app = createServerFromResponse({name: 'Bob'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) it('custom error message is printed', -> assert.include(dreddRuntimeInfo.logging, 'Unexpected exception in hooks') ) ) )
93149
{assert} = require('chai') clone = require('clone') {EventEmitter} = require('events') {runDredd, createServer, runDreddWithServer} = require('./helpers') Dredd = require('../../src/dredd') describe('Sanitation of Reported Data', -> # sample sensitive data (this value is used in API Blueprint fixtures as well) sensitiveKey = '<KEY>' sensitiveHeaderName = 'authorization' sensitiveValue = '<KEY>' # recording events sent to reporters events = undefined emitter = undefined beforeEach( -> events = [] emitter = new EventEmitter() # Dredd emits 'test *' events and reporters listen on them. To test whether # sensitive data will or won't make it to reporters, we need to capture all # the emitted events. We're using 'clone' to prevent propagation of subsequent # modifications of the 'test' object (Dredd can change the data after they're # reported and by reference they would change also here in the 'events' array). emitter.on('test start', (test) -> events.push({name: 'test start', test: clone(test)})) emitter.on('test pass', (test) -> events.push({name: 'test pass', test: clone(test)})) emitter.on('test skip', (test) -> events.push({name: 'test skip', test: clone(test)})) emitter.on('test fail', (test) -> events.push({name: 'test fail', test: clone(test)})) emitter.on('test error', (err, test) -> events.push({name: 'test error', test: clone(test), err})) # 'start' and 'end' events are asynchronous and they do not carry any data # significant for following scenarios emitter.on('start', (apiDescription, cb) -> events.push({name: 'start'}); cb() ) emitter.on('end', (cb) -> events.push({name: 'end'}); cb() ) ) # helper for preparing Dredd instance with our custom emitter createDreddFromFixture = (fixtureName) -> new Dredd({ emitter options: { path: "./test/fixtures/sanitation/#{fixtureName}.apib" hookfiles: "./test/fixtures/sanitation/#{fixtureName}.js" } }) # helper for preparing the server under test createServerFromResponse = (response) -> app = createServer() app.put('/resource', (req, res) -> res.json(response)) return app describe('Sanitation of the Entire Request Body', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('entire-request-body') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of the Entire Response Body', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('entire-response-body') app = createServerFromResponse({token: 123}) # 'token' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain response body', -> assert.equal(events[2].test.actual.body, '') assert.equal(events[2].test.expected.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of a Request Body Attribute', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('request-body-attribute') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential body attribute', -> attrs = Object.keys(JSON.parse(events[2].test.request.body)) assert.deepEqual(attrs, ['name']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of a Response Body Attribute', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('response-body-attribute') app = createServerFromResponse({token: <PASSWORD>, name: '<NAME>'}) # 'token' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential body attribute', -> attrs = Object.keys(JSON.parse(events[2].test.actual.body)) assert.deepEqual(attrs, ['name']) attrs = Object.keys(JSON.parse(events[2].test.expected.body)) assert.deepEqual(attrs, ['name']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Plain Text Response Body by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('plain-text-response-body') app = createServerFromResponse("#{sensitiveKey}=42#{sensitiveValue}") # should be without '42' → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(events[2].test.actual.body, '--- CENSORED ---') assert.include(events[2].test.expected.body, '--- CENSORED ---') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Request Headers', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('request-headers') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential header', -> names = (name.toLowerCase() for name of events[2].test.request.headers) assert.notInclude(names, sensitiveHeaderName) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events).toLowerCase() assert.notInclude(test, sensitiveHeaderName) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> logging = dreddRuntimeInfo.logging.toLowerCase() assert.notInclude(logging, sensitiveHeaderName) assert.notInclude(logging, sensitiveValue) ) ) describe('Sanitation of Response Headers', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('response-headers') app = createServerFromResponse({name: '<NAME>'}) # Authorization header is missing → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential header', -> names = (name.toLowerCase() for name of events[2].test.actual.headers) assert.notInclude(names, sensitiveHeaderName) names = (name.toLowerCase() for name of events[2].test.expected.headers) assert.notInclude(names, sensitiveHeaderName) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events).toLowerCase() assert.notInclude(test, sensitiveHeaderName) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> logging = dreddRuntimeInfo.logging.toLowerCase() assert.notInclude(logging, sensitiveHeaderName) assert.notInclude(logging, sensitiveValue) ) ) describe('Sanitation of URI Parameters by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('uri-parameters') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(events[2].test.request.uri, 'CENSORED') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) # This fails because it's not possible to do 'transaction.test = myOwnTestObject;' # at the moment, Dredd ignores the new object. describe('Sanitation of Any Content by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('any-content-pattern-matching') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(JSON.stringify(events), 'CENSORED') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Ultimate \'afterEach\' Guard Using Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('any-content-guard-pattern-matching') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) it('custom error message is printed', -> assert.include(dreddRuntimeInfo.logging, 'Sensitive data would be sent to Dredd reporter') ) ) describe('Sanitation of Test Data of Passing Transaction', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-passing') app = createServerFromResponse({name: '<NAME>'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one passing test', -> assert.equal(dreddRuntimeInfo.stats.passes, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test pass', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Failed in \'before\' Hook', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-failed-before') runDredd(dredd, (args...) -> [err, dreddRuntimeInfo] = args done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test is failed', -> assert.equal(events[2].test.status, 'fail') assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'fail') ) it('emitted test data results contain just \'general\' section', -> assert.deepEqual(Object.keys(events[2].test.results), ['general']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Failed in \'after\' Hook', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-failed-after') app = createServerFromResponse({name: '<NAME>'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('emitted test is failed', -> assert.equal(events[2].test.status, 'fail') assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'fail') ) it('emitted test data results contain all regular sections', -> assert.deepEqual(Object.keys(events[2].test.results), ['general', 'headers', 'body', 'statusCode']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Skipped', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-skipped') runDredd(dredd, (args...) -> [err, dreddRuntimeInfo] = args done() ) ) it('results in one skipped test', -> assert.equal(dreddRuntimeInfo.stats.skipped, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test skip', 'end' ]) ) it('emitted test is skipped', -> assert.equal(events[2].test.status, 'skip') assert.deepEqual(Object.keys(events[2].test.results), ['general']) assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'skip') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data of Transaction With Erroring Hooks', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-erroring-hooks') app = createServerFromResponse({name: '<NAME>'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one erroring test', -> assert.equal(dreddRuntimeInfo.stats.errors, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test error', 'end' ]) ) it('sensitive data leak to emitted test data', -> test = JSON.stringify(events) assert.include(test, sensitiveKey) assert.include(test, sensitiveValue) ) it('sensitive data leak to Dredd output', -> assert.include(dreddRuntimeInfo.logging, sensitiveKey) assert.include(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data of Transaction With Secured Erroring Hooks', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-secured-erroring-hooks') app = createServerFromResponse({name: '<NAME>'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) it('custom error message is printed', -> assert.include(dreddRuntimeInfo.logging, 'Unexpected exception in hooks') ) ) )
true
{assert} = require('chai') clone = require('clone') {EventEmitter} = require('events') {runDredd, createServer, runDreddWithServer} = require('./helpers') Dredd = require('../../src/dredd') describe('Sanitation of Reported Data', -> # sample sensitive data (this value is used in API Blueprint fixtures as well) sensitiveKey = 'PI:KEY:<KEY>END_PI' sensitiveHeaderName = 'authorization' sensitiveValue = 'PI:KEY:<KEY>END_PI' # recording events sent to reporters events = undefined emitter = undefined beforeEach( -> events = [] emitter = new EventEmitter() # Dredd emits 'test *' events and reporters listen on them. To test whether # sensitive data will or won't make it to reporters, we need to capture all # the emitted events. We're using 'clone' to prevent propagation of subsequent # modifications of the 'test' object (Dredd can change the data after they're # reported and by reference they would change also here in the 'events' array). emitter.on('test start', (test) -> events.push({name: 'test start', test: clone(test)})) emitter.on('test pass', (test) -> events.push({name: 'test pass', test: clone(test)})) emitter.on('test skip', (test) -> events.push({name: 'test skip', test: clone(test)})) emitter.on('test fail', (test) -> events.push({name: 'test fail', test: clone(test)})) emitter.on('test error', (err, test) -> events.push({name: 'test error', test: clone(test), err})) # 'start' and 'end' events are asynchronous and they do not carry any data # significant for following scenarios emitter.on('start', (apiDescription, cb) -> events.push({name: 'start'}); cb() ) emitter.on('end', (cb) -> events.push({name: 'end'}); cb() ) ) # helper for preparing Dredd instance with our custom emitter createDreddFromFixture = (fixtureName) -> new Dredd({ emitter options: { path: "./test/fixtures/sanitation/#{fixtureName}.apib" hookfiles: "./test/fixtures/sanitation/#{fixtureName}.js" } }) # helper for preparing the server under test createServerFromResponse = (response) -> app = createServer() app.put('/resource', (req, res) -> res.json(response)) return app describe('Sanitation of the Entire Request Body', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('entire-request-body') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of the Entire Response Body', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('entire-response-body') app = createServerFromResponse({token: 123}) # 'token' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain response body', -> assert.equal(events[2].test.actual.body, '') assert.equal(events[2].test.expected.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of a Request Body Attribute', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('request-body-attribute') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential body attribute', -> attrs = Object.keys(JSON.parse(events[2].test.request.body)) assert.deepEqual(attrs, ['name']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of a Response Body Attribute', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('response-body-attribute') app = createServerFromResponse({token: PI:PASSWORD:<PASSWORD>END_PI, name: 'PI:NAME:<NAME>END_PI'}) # 'token' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential body attribute', -> attrs = Object.keys(JSON.parse(events[2].test.actual.body)) assert.deepEqual(attrs, ['name']) attrs = Object.keys(JSON.parse(events[2].test.expected.body)) assert.deepEqual(attrs, ['name']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Plain Text Response Body by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('plain-text-response-body') app = createServerFromResponse("#{sensitiveKey}=42#{sensitiveValue}") # should be without '42' → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(events[2].test.actual.body, '--- CENSORED ---') assert.include(events[2].test.expected.body, '--- CENSORED ---') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Request Headers', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('request-headers') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential header', -> names = (name.toLowerCase() for name of events[2].test.request.headers) assert.notInclude(names, sensitiveHeaderName) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events).toLowerCase() assert.notInclude(test, sensitiveHeaderName) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> logging = dreddRuntimeInfo.logging.toLowerCase() assert.notInclude(logging, sensitiveHeaderName) assert.notInclude(logging, sensitiveValue) ) ) describe('Sanitation of Response Headers', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('response-headers') app = createServerFromResponse({name: 'PI:NAME:<NAME>END_PI'}) # Authorization header is missing → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain confidential header', -> names = (name.toLowerCase() for name of events[2].test.actual.headers) assert.notInclude(names, sensitiveHeaderName) names = (name.toLowerCase() for name of events[2].test.expected.headers) assert.notInclude(names, sensitiveHeaderName) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events).toLowerCase() assert.notInclude(test, sensitiveHeaderName) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> logging = dreddRuntimeInfo.logging.toLowerCase() assert.notInclude(logging, sensitiveHeaderName) assert.notInclude(logging, sensitiveValue) ) ) describe('Sanitation of URI Parameters by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('uri-parameters') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(events[2].test.request.uri, 'CENSORED') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) # This fails because it's not possible to do 'transaction.test = myOwnTestObject;' # at the moment, Dredd ignores the new object. describe('Sanitation of Any Content by Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('any-content-pattern-matching') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does contain the sensitive data censored', -> assert.include(JSON.stringify(events), 'CENSORED') ) it('sensitive data cannot be found anywhere in the emitted test data', -> assert.notInclude(JSON.stringify(events), sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Ultimate \'afterEach\' Guard Using Pattern Matching', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('any-content-guard-pattern-matching') app = createServerFromResponse({name: 123}) # 'name' should be string → failing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) it('custom error message is printed', -> assert.include(dreddRuntimeInfo.logging, 'Sensitive data would be sent to Dredd reporter') ) ) describe('Sanitation of Test Data of Passing Transaction', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-passing') app = createServerFromResponse({name: 'PI:NAME:<NAME>END_PI'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one passing test', -> assert.equal(dreddRuntimeInfo.stats.passes, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test pass', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Failed in \'before\' Hook', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-failed-before') runDredd(dredd, (args...) -> [err, dreddRuntimeInfo] = args done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test is failed', -> assert.equal(events[2].test.status, 'fail') assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'fail') ) it('emitted test data results contain just \'general\' section', -> assert.deepEqual(Object.keys(events[2].test.results), ['general']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Failed in \'after\' Hook', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-failed-after') app = createServerFromResponse({name: 'PI:NAME:<NAME>END_PI'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('emitted test data does not contain request body', -> assert.equal(events[2].test.request.body, '') ) it('emitted test is failed', -> assert.equal(events[2].test.status, 'fail') assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'fail') ) it('emitted test data results contain all regular sections', -> assert.deepEqual(Object.keys(events[2].test.results), ['general', 'headers', 'body', 'statusCode']) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data When Transaction Is Marked as Skipped', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-marked-skipped') runDredd(dredd, (args...) -> [err, dreddRuntimeInfo] = args done() ) ) it('results in one skipped test', -> assert.equal(dreddRuntimeInfo.stats.skipped, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test skip', 'end' ]) ) it('emitted test is skipped', -> assert.equal(events[2].test.status, 'skip') assert.deepEqual(Object.keys(events[2].test.results), ['general']) assert.include(events[2].test.results.general.results[0].message.toLowerCase(), 'skip') ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data of Transaction With Erroring Hooks', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-erroring-hooks') app = createServerFromResponse({name: 'PI:NAME:<NAME>END_PI'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one erroring test', -> assert.equal(dreddRuntimeInfo.stats.errors, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test error', 'end' ]) ) it('sensitive data leak to emitted test data', -> test = JSON.stringify(events) assert.include(test, sensitiveKey) assert.include(test, sensitiveValue) ) it('sensitive data leak to Dredd output', -> assert.include(dreddRuntimeInfo.logging, sensitiveKey) assert.include(dreddRuntimeInfo.logging, sensitiveValue) ) ) describe('Sanitation of Test Data of Transaction With Secured Erroring Hooks', -> dreddRuntimeInfo = undefined beforeEach((done) -> dredd = createDreddFromFixture('transaction-secured-erroring-hooks') app = createServerFromResponse({name: 'PI:NAME:<NAME>END_PI'}) # passing test runDreddWithServer(dredd, app, (err, runtimeInfo) -> return done(err) if err dreddRuntimeInfo = runtimeInfo.dredd done() ) ) it('results in one failed test', -> assert.equal(dreddRuntimeInfo.stats.failures, 1) assert.equal(dreddRuntimeInfo.stats.tests, 1) ) it('emits expected events in expected order', -> assert.deepEqual((event.name for event in events), [ 'start', 'test start', 'test fail', 'end' ]) ) it('sensitive data cannot be found anywhere in the emitted test data', -> test = JSON.stringify(events) assert.notInclude(test, sensitiveKey) assert.notInclude(test, sensitiveValue) ) it('sensitive data cannot be found anywhere in Dredd output', -> assert.notInclude(dreddRuntimeInfo.logging, sensitiveKey) assert.notInclude(dreddRuntimeInfo.logging, sensitiveValue) ) it('custom error message is printed', -> assert.include(dreddRuntimeInfo.logging, 'Unexpected exception in hooks') ) ) )
[ { "context": "nt#on` method overload\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nfor Unit in [Element, Document, Window]\n do (U", "end": 96, "score": 0.9998923540115356, "start": 79, "tag": "NAME", "value": "Nikolay Nemshilov" }, { "context": "e.indexOf(',') is -1\n key = name.split(/[\\+\\-\\_ ]+/)\n key = (key[key.length - 1] || '').", "end": 355, "score": 0.6176129579544067, "start": 355, "tag": "KEY", "value": "" } ]
ui/core/src/element.coffee
lovely-io/lovely.io-stl
2
# # The 'dom' package `Element#on` method overload # # Copyright (C) 2011-2012 Nikolay Nemshilov # for Unit in [Element, Document, Window] do (Unit)-> original_method = Unit::on Unit::on = (name)-> args = A(arguments) name = args[0] if typeof(name) is 'string' if name.indexOf(',') is -1 key = name.split(/[\+\-\_ ]+/) key = (key[key.length - 1] || '').toUpperCase() if key of Event.Keys || /^[A-Z0-9]$/.test(key) meta = /(^|\+|\-| )(meta|alt)(\+|\-| )/i.test(name) ctrl = /(^|\+|\-| )(ctl|ctrl)(\+|\-| )/i.test(name) shift = /(^|\+|\-| )(shift)(\+|\-| )/i.test(name) code = Event.Keys[key] || key.charCodeAt(0) orig = args.slice(1) method = orig.shift() if typeof(method) is 'string' method = this[method] || -> # replacing the arguments args = ['keydown', (event)-> if (event.keyCode is code) and (!meta or event.metaKey or event.altKey) and (!ctrl or event.ctrlKey) and (!shift or event.shiftKey) return method.apply(this, [event].concat(orig)) ] else for key in name.split(',') args[0] = key; @on.apply(@, args) original_method.apply(this, args)
164102
# # The 'dom' package `Element#on` method overload # # Copyright (C) 2011-2012 <NAME> # for Unit in [Element, Document, Window] do (Unit)-> original_method = Unit::on Unit::on = (name)-> args = A(arguments) name = args[0] if typeof(name) is 'string' if name.indexOf(',') is -1 key = name.split(/[<KEY>\+\-\_ ]+/) key = (key[key.length - 1] || '').toUpperCase() if key of Event.Keys || /^[A-Z0-9]$/.test(key) meta = /(^|\+|\-| )(meta|alt)(\+|\-| )/i.test(name) ctrl = /(^|\+|\-| )(ctl|ctrl)(\+|\-| )/i.test(name) shift = /(^|\+|\-| )(shift)(\+|\-| )/i.test(name) code = Event.Keys[key] || key.charCodeAt(0) orig = args.slice(1) method = orig.shift() if typeof(method) is 'string' method = this[method] || -> # replacing the arguments args = ['keydown', (event)-> if (event.keyCode is code) and (!meta or event.metaKey or event.altKey) and (!ctrl or event.ctrlKey) and (!shift or event.shiftKey) return method.apply(this, [event].concat(orig)) ] else for key in name.split(',') args[0] = key; @on.apply(@, args) original_method.apply(this, args)
true
# # The 'dom' package `Element#on` method overload # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # for Unit in [Element, Document, Window] do (Unit)-> original_method = Unit::on Unit::on = (name)-> args = A(arguments) name = args[0] if typeof(name) is 'string' if name.indexOf(',') is -1 key = name.split(/[PI:KEY:<KEY>END_PI\+\-\_ ]+/) key = (key[key.length - 1] || '').toUpperCase() if key of Event.Keys || /^[A-Z0-9]$/.test(key) meta = /(^|\+|\-| )(meta|alt)(\+|\-| )/i.test(name) ctrl = /(^|\+|\-| )(ctl|ctrl)(\+|\-| )/i.test(name) shift = /(^|\+|\-| )(shift)(\+|\-| )/i.test(name) code = Event.Keys[key] || key.charCodeAt(0) orig = args.slice(1) method = orig.shift() if typeof(method) is 'string' method = this[method] || -> # replacing the arguments args = ['keydown', (event)-> if (event.keyCode is code) and (!meta or event.metaKey or event.altKey) and (!ctrl or event.ctrlKey) and (!shift or event.shiftKey) return method.apply(this, [event].concat(orig)) ] else for key in name.split(',') args[0] = key; @on.apply(@, args) original_method.apply(this, args)
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992449879646301, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-stream2-read-sync-stack.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") Readable = require("stream").Readable r = new Readable() N = 256 * 1024 # Go ahead and allow the pathological case for this test. # Yes, it's an infinite loop, that's the point. process.maxTickDepth = N + 2 reads = 0 r._read = (n) -> chunk = (if reads++ is N then null else new Buffer(1)) r.push chunk return r.on "readable", onReadable = -> console.error "readable", r._readableState.length unless r._readableState.length % 256 r.read N * 2 return ended = false r.on "end", onEnd = -> ended = true return r.read 0 process.on "exit", -> assert ended console.log "ok" return
159939
# 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") Readable = require("stream").Readable r = new Readable() N = 256 * 1024 # Go ahead and allow the pathological case for this test. # Yes, it's an infinite loop, that's the point. process.maxTickDepth = N + 2 reads = 0 r._read = (n) -> chunk = (if reads++ is N then null else new Buffer(1)) r.push chunk return r.on "readable", onReadable = -> console.error "readable", r._readableState.length unless r._readableState.length % 256 r.read N * 2 return ended = false r.on "end", onEnd = -> ended = true return r.read 0 process.on "exit", -> assert ended console.log "ok" 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") Readable = require("stream").Readable r = new Readable() N = 256 * 1024 # Go ahead and allow the pathological case for this test. # Yes, it's an infinite loop, that's the point. process.maxTickDepth = N + 2 reads = 0 r._read = (n) -> chunk = (if reads++ is N then null else new Buffer(1)) r.push chunk return r.on "readable", onReadable = -> console.error "readable", r._readableState.length unless r._readableState.length % 256 r.read N * 2 return ended = false r.on "end", onEnd = -> ended = true return r.read 0 process.on "exit", -> assert ended console.log "ok" return
[ { "context": "ices.SessionStorage() \n @data =\n username: username \n password: password\n\n $.ajax @loginUrl,\n", "end": 222, "score": 0.9986990094184875, "start": 214, "tag": "USERNAME", "value": "username" }, { "context": " @data =\n username: username \n password: password\n\n $.ajax @loginUrl,\n type: 'POST',\n ", "end": 248, "score": 0.9990635514259338, "start": 240, "tag": "PASSWORD", "value": "password" } ]
app/assets/javascripts/models/user.coffee
okapusta/skirace
0
class Skirace.Models.User extends Backbone.Model loginUrl: '/login' urlRoot: '/users' login: (username, password) -> session_storage = new Skirace.Services.SessionStorage() @data = username: username password: password $.ajax @loginUrl, type: 'POST', dataType: 'json' data: JSON.stringify(@data) success: (data) -> session_storage.set('current_user', JSON.stringify(data.user)) window.location.reload()
112153
class Skirace.Models.User extends Backbone.Model loginUrl: '/login' urlRoot: '/users' login: (username, password) -> session_storage = new Skirace.Services.SessionStorage() @data = username: username password: <PASSWORD> $.ajax @loginUrl, type: 'POST', dataType: 'json' data: JSON.stringify(@data) success: (data) -> session_storage.set('current_user', JSON.stringify(data.user)) window.location.reload()
true
class Skirace.Models.User extends Backbone.Model loginUrl: '/login' urlRoot: '/users' login: (username, password) -> session_storage = new Skirace.Services.SessionStorage() @data = username: username password: PI:PASSWORD:<PASSWORD>END_PI $.ajax @loginUrl, type: 'POST', dataType: 'json' data: JSON.stringify(@data) success: (data) -> session_storage.set('current_user', JSON.stringify(data.user)) window.location.reload()
[ { "context": "3-2014 TheGrid (Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed und", "end": 129, "score": 0.9998387098312378, "start": 116, "tag": "NAME", "value": "Henri Bergius" }, { "context": "(Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed under the M", "end": 137, "score": 0.9988489151000977, "start": 131, "tag": "NAME", "value": "Nemein" } ]
src/lib/Graph.coffee
ensonic/noflo
0
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 Henri Bergius, Nemein # NoFlo may be freely distributed under the MIT license # # NoFlo graphs are Event Emitters, providing signals when the graph # definition changes. # {EventEmitter} = require 'events' clone = require('./Utils').clone platform = require './Platform' # This class represents an abstract NoFlo graph containing nodes # connected to each other with edges. # # These graphs can be used for visualization and sketching, but # also are the way to start a NoFlo network. class Graph extends EventEmitter name: '' properties: {} nodes: [] edges: [] initializers: [] exports: [] inports: {} outports: {} groups: [] # ## Creating new graphs # # Graphs are created by simply instantiating the Graph class # and giving it a name: # # myGraph = new Graph 'My very cool graph' constructor: (@name = '') -> @properties = {} @nodes = [] @edges = [] @initializers = [] @exports = [] @inports = {} @outports = {} @groups = [] @transaction = id: null depth: 0 # ## Group graph changes into transactions # # If no transaction is explicitly opened, each call to # the graph API will implicitly create a transaction for that change startTransaction: (id, metadata) -> if @transaction.id throw Error("Nested transactions not supported") @transaction.id = id @transaction.depth = 1 @emit 'startTransaction', id, metadata endTransaction: (id, metadata) -> if not @transaction.id throw Error("Attempted to end non-existing transaction") @transaction.id = null @transaction.depth = 0 @emit 'endTransaction', id, metadata checkTransactionStart: () -> if not @transaction.id @startTransaction 'implicit' else if @transaction.id == 'implicit' @transaction.depth += 1 checkTransactionEnd: () -> if @transaction.id == 'implicit' @transaction.depth -= 1 if @transaction.depth == 0 @endTransaction 'implicit' # ## Modifying Graph properties # # This method allows changing properties of the graph. setProperties: (properties) -> @checkTransactionStart() before = clone @properties for item, val of properties @properties[item] = val @emit 'changeProperties', @properties, before @checkTransactionEnd() # ## Exporting a port from subgraph # # This allows subgraphs to expose a cleaner API by having reasonably # named ports shown instead of all the free ports of the graph # # The ports exported using this way are ambiguous in their direciton. Use # `addInport` or `addOutport` instead to disambiguate. addExport: (publicPort, nodeKey, portKey, metadata = {x:0,y:0}) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() exported = public: publicPort process: nodeKey port: portKey metadata: metadata @exports.push exported @emit 'addExport', exported @checkTransactionEnd() removeExport: (publicPort) -> publicPort = publicPort.toLowerCase() found = null for exported, idx in @exports found = exported if exported.public is publicPort return unless found @checkTransactionStart() @exports.splice @exports.indexOf(found), 1 @emit 'removeExport', found @checkTransactionEnd() addInport: (publicPort, nodeKey, portKey, metadata) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() @inports[publicPort] = process: nodeKey port: portKey metadata: metadata @emit 'addInport', publicPort, @inports[publicPort] @checkTransactionEnd() removeInport: (publicPort) -> publicPort = publicPort.toLowerCase() return unless @inports[publicPort] @checkTransactionStart() port = @inports[publicPort] @setInportMetadata publicPort, {} delete @inports[publicPort] @emit 'removeInport', publicPort, port @checkTransactionEnd() renameInport: (oldPort, newPort) -> return unless @inports[oldPort] @checkTransactionStart() @inports[newPort] = @inports[oldPort] delete @inports[oldPort] @emit 'renameInport', oldPort, newPort @checkTransactionEnd() setInportMetadata: (publicPort, metadata) -> return unless @inports[publicPort] @checkTransactionStart() before = clone @inports[publicPort].metadata @inports[publicPort].metadata = {} unless @inports[publicPort].metadata for item, val of metadata if val? @inports[publicPort].metadata[item] = val else delete @inports[publicPort].metadata[item] @emit 'changeInport', publicPort, @inports[publicPort], before @checkTransactionEnd() addOutport: (publicPort, nodeKey, portKey, metadata) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() @outports[publicPort] = process: nodeKey port: portKey metadata: metadata @emit 'addOutport', publicPort, @outports[publicPort] @checkTransactionEnd() removeOutport: (publicPort) -> publicPort = publicPort.toLowerCase() return unless @outports[publicPort] @checkTransactionStart() port = @outports[publicPort] @setOutportMetadata publicPort, {} delete @outports[publicPort] @emit 'removeOutport', publicPort, port @checkTransactionEnd() renameOutport: (oldPort, newPort) -> return unless @outports[oldPort] @checkTransactionStart() @outports[newPort] = @outports[oldPort] delete @outports[oldPort] @emit 'renameOutport', oldPort, newPort @checkTransactionEnd() setOutportMetadata: (publicPort, metadata) -> return unless @outports[publicPort] @checkTransactionStart() before = clone @outports[publicPort].metadata @outports[publicPort].metadata = {} unless @outports[publicPort].metadata for item, val of metadata if val? @outports[publicPort].metadata[item] = val else delete @outports[publicPort].metadata[item] @emit 'changeOutport', publicPort, @outports[publicPort], before @checkTransactionEnd() # ## Grouping nodes in a graph # addGroup: (group, nodes, metadata) -> @checkTransactionStart() g = name: group nodes: nodes metadata: metadata @groups.push g @emit 'addGroup', g @checkTransactionEnd() renameGroup: (oldName, newName) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is oldName group.name = newName @emit 'renameGroup', oldName, newName @checkTransactionEnd() removeGroup: (groupName) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is groupName @setGroupMetadata group.name, {} @groups.splice @groups.indexOf(group), 1 @emit 'removeGroup', group @checkTransactionEnd() setGroupMetadata: (groupName, metadata) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is groupName before = clone group.metadata for item, val of metadata if val? group.metadata[item] = val else delete group.metadata[item] @emit 'changeGroup', group, before @checkTransactionEnd() # ## Adding a node to the graph # # Nodes are identified by an ID unique to the graph. Additionally, # a node may contain information on what NoFlo component it is and # possible display coordinates. # # For example: # # myGraph.addNode 'Read, 'ReadFile', # x: 91 # y: 154 # # Addition of a node will emit the `addNode` event. addNode: (id, component, metadata) -> @checkTransactionStart() metadata = {} unless metadata node = id: id component: component metadata: metadata @nodes.push node @emit 'addNode', node @checkTransactionEnd() node # ## Removing a node from the graph # # Existing nodes can be removed from a graph by their ID. This # will remove the node and also remove all edges connected to it. # # myGraph.removeNode 'Read' # # Once the node has been removed, the `removeNode` event will be # emitted. removeNode: (id) -> node = @getNode id return unless node @checkTransactionStart() toRemove = [] for edge in @edges if (edge.from.node is node.id) or (edge.to.node is node.id) toRemove.push edge for edge in toRemove @removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port toRemove = [] for initializer in @initializers if initializer.to.node is node.id toRemove.push initializer for initializer in toRemove @removeInitial initializer.to.node, initializer.to.port toRemove = [] for exported in @exports if id.toLowerCase() is exported.process toRemove.push exported for exported in toRemove @removeExports exported.public toRemove = [] for pub, priv of @inports if priv.process is id toRemove.push pub for pub in toRemove @removeInport pub toRemove = [] for pub, priv of @outports if priv.process is id toRemove.push pub for pub in toRemove @removeOutport pub for group in @groups continue unless group index = group.nodes.indexOf(id) continue if index is -1 group.nodes.splice index, 1 @setNodeMetadata id, {} if -1 isnt @nodes.indexOf node @nodes.splice @nodes.indexOf(node), 1 @emit 'removeNode', node @checkTransactionEnd() # ## Getting a node # # Nodes objects can be retrieved from the graph by their ID: # # myNode = myGraph.getNode 'Read' getNode: (id) -> for node in @nodes continue unless node return node if node.id is id return null # ## Renaming a node # # Nodes IDs can be changed by calling this method. renameNode: (oldId, newId) -> @checkTransactionStart() node = @getNode oldId return unless node node.id = newId for edge in @edges continue unless edge if edge.from.node is oldId edge.from.node = newId if edge.to.node is oldId edge.to.node = newId for iip in @initializers continue unless iip if iip.to.node is oldId iip.to.node = newId for pub, priv of @inports if priv.process is oldId priv.process = newId for pub, priv of @outports if priv.process is oldId priv.process = newId for exported in @exports if exported.process is oldId exported.process = newId for group in @groups continue unless group index = group.nodes.indexOf(oldId) continue if index is -1 group.nodes[index] = newId @emit 'renameNode', oldId, newId @checkTransactionEnd() # ## Changing a node's metadata # # Node metadata can be set or changed by calling this method. setNodeMetadata: (id, metadata) -> node = @getNode id return unless node @checkTransactionStart() before = clone node.metadata node.metadata = {} unless node.metadata for item, val of metadata if val? node.metadata[item] = val else delete node.metadata[item] @emit 'changeNode', node, before @checkTransactionEnd() # ## Connecting nodes # # Nodes can be connected by adding edges between a node's outport # and another node's inport: # # myGraph.addEdge 'Read', 'out', 'Display', 'in' # myGraph.addEdgeIndex 'Read', 'out', null, 'Display', 'in', 2 # # Adding an edge will emit the `addEdge` event. addEdge: (outNode, outPort, inNode, inPort, metadata = {}) -> for edge in @edges # don't add a duplicate edge return if (edge.from.node is outNode and edge.from.port is outPort and edge.to.node is inNode and edge.to.port is inPort) return unless @getNode outNode return unless @getNode inNode @checkTransactionStart() edge = from: node: outNode port: outPort to: node: inNode port: inPort metadata: metadata @edges.push edge @emit 'addEdge', edge @checkTransactionEnd() edge # Adding an edge will emit the `addEdge` event. addEdgeIndex: (outNode, outPort, outIndex, inNode, inPort, inIndex, metadata = {}) -> return unless @getNode outNode return unless @getNode inNode inIndex = undefined if inIndex is null outIndex = undefined if outIndex is null metadata = {} unless metadata @checkTransactionStart() edge = from: node: outNode port: outPort index: outIndex to: node: inNode port: inPort index: inIndex metadata: metadata @edges.push edge @emit 'addEdge', edge @checkTransactionEnd() edge # ## Disconnected nodes # # Connections between nodes can be removed by providing the # nodes and ports to disconnect. # # myGraph.removeEdge 'Display', 'out', 'Foo', 'in' # # Removing a connection will emit the `removeEdge` event. removeEdge: (node, port, node2, port2) -> @checkTransactionStart() toRemove = [] toKeep = [] if node2 and port2 for edge,index in @edges if edge.from.node is node and edge.from.port is port and edge.to.node is node2 and edge.to.port is port2 @setEdgeMetadata edge.from.node, edge.from.port, edge.to.node, edge.to.port, {} toRemove.push edge else toKeep.push edge else for edge,index in @edges if (edge.from.node is node and edge.from.port is port) or (edge.to.node is node and edge.to.port is port) @setEdgeMetadata edge.from.node, edge.from.port, edge.to.node, edge.to.port, {} toRemove.push edge else toKeep.push edge @edges = toKeep for edge in toRemove @emit 'removeEdge', edge @checkTransactionEnd() # ## Getting an edge # # Edge objects can be retrieved from the graph by the node and port IDs: # # myEdge = myGraph.getEdge 'Read', 'out', 'Write', 'in' getEdge: (node, port, node2, port2) -> for edge,index in @edges continue unless edge if edge.from.node is node and edge.from.port is port if edge.to.node is node2 and edge.to.port is port2 return edge return null # ## Changing an edge's metadata # # Edge metadata can be set or changed by calling this method. setEdgeMetadata: (node, port, node2, port2, metadata) -> edge = @getEdge node, port, node2, port2 return unless edge @checkTransactionStart() before = clone edge.metadata edge.metadata = {} unless edge.metadata for item, val of metadata if val? edge.metadata[item] = val else delete edge.metadata[item] @emit 'changeEdge', edge, before @checkTransactionEnd() # ## Adding Initial Information Packets # # Initial Information Packets (IIPs) can be used for sending data # to specified node inports without a sending node instance. # # IIPs are especially useful for sending configuration information # to components at NoFlo network start-up time. This could include # filenames to read, or network ports to listen to. # # myGraph.addInitial 'somefile.txt', 'Read', 'source' # myGraph.addInitialIndex 'somefile.txt', 'Read', 'source', 2 # # If inports are defined on the graph, IIPs can be applied calling # the `addGraphInitial` or `addGraphInitialIndex` methods. # # myGraph.addGraphInitial 'somefile.txt', 'file' # myGraph.addGraphInitialIndex 'somefile.txt', 'file', 2 # # Adding an IIP will emit a `addInitial` event. addInitial: (data, node, port, metadata) -> return unless @getNode node @checkTransactionStart() initializer = from: data: data to: node: node port: port metadata: metadata @initializers.push initializer @emit 'addInitial', initializer @checkTransactionEnd() initializer addInitialIndex: (data, node, port, index, metadata) -> return unless @getNode node index = undefined if index is null @checkTransactionStart() initializer = from: data: data to: node: node port: port index: index metadata: metadata @initializers.push initializer @emit 'addInitial', initializer @checkTransactionEnd() initializer addGraphInitial: (data, node, metadata) -> inport = @inports[node] return unless inport @addInitial data, inport.process, inport.port, metadata addGraphInitialIndex: (data, node, index, metadata) -> inport = @inports[node] return unless inport @addInitialIndex data, inport.process, inport.port, index, metadata # ## Removing Initial Information Packets # # IIPs can be removed by calling the `removeInitial` method. # # myGraph.removeInitial 'Read', 'source' # # If the IIP was applied via the `addGraphInitial` or # `addGraphInitialIndex` functions, it can be removed using # the `removeGraphInitial` method. # # myGraph.removeGraphInitial 'file' # # Remove an IIP will emit a `removeInitial` event. removeInitial: (node, port) -> @checkTransactionStart() toRemove = [] toKeep = [] for edge, index in @initializers if edge.to.node is node and edge.to.port is port toRemove.push edge else toKeep.push edge @initializers = toKeep for edge in toRemove @emit 'removeInitial', edge @checkTransactionEnd() removeGraphInitial: (node) -> inport = @inports[node] return unless inport @removeInitial inport.process, inport.port toDOT: -> cleanID = (id) -> id.replace /\s*/g, "" cleanPort = (port) -> port.replace /\./g, "" dot = "digraph {\n" for node in @nodes dot += " #{cleanID(node.id)} [label=#{node.id} shape=box]\n" for initializer, id in @initializers if typeof initializer.from.data is 'function' data = 'Function' else data = initializer.from.data dot += " data#{id} [label=\"'#{data}'\" shape=plaintext]\n" dot += " data#{id} -> #{cleanID(initializer.to.node)}[headlabel=#{cleanPort(initializer.to.port)} labelfontcolor=blue labelfontsize=8.0]\n" for edge in @edges dot += " #{cleanID(edge.from.node)} -> #{cleanID(edge.to.node)}[taillabel=#{cleanPort(edge.from.port)} headlabel=#{cleanPort(edge.to.port)} labelfontcolor=blue labelfontsize=8.0]\n" dot += "}" return dot toYUML: -> yuml = [] for initializer in @initializers yuml.push "(start)[#{initializer.to.port}]->(#{initializer.to.node})" for edge in @edges yuml.push "(#{edge.from.node})[#{edge.from.port}]->(#{edge.to.node})" yuml.join "," toJSON: -> json = properties: {} inports: {} outports: {} groups: [] processes: {} connections: [] json.properties.name = @name if @name for property, value of @properties json.properties[property] = value for pub, priv of @inports json.inports[pub] = priv for pub, priv of @outports json.outports[pub] = priv # Legacy exported ports for exported in @exports json.exports = [] unless json.exports json.exports.push exported for group in @groups groupData = name: group.name nodes: group.nodes if Object.keys(group.metadata).length groupData.metadata = group.metadata json.groups.push groupData for node in @nodes json.processes[node.id] = component: node.component if node.metadata json.processes[node.id].metadata = node.metadata for edge in @edges connection = src: process: edge.from.node port: edge.from.port index: edge.from.index tgt: process: edge.to.node port: edge.to.port index: edge.to.index connection.metadata = edge.metadata if Object.keys(edge.metadata).length json.connections.push connection for initializer in @initializers json.connections.push data: initializer.from.data tgt: process: initializer.to.node port: initializer.to.port index: initializer.to.index json save: (file, success) -> json = JSON.stringify @toJSON(), null, 4 require('fs').writeFile "#{file}.json", json, "utf-8", (err, data) -> throw err if err success file exports.Graph = Graph exports.createGraph = (name) -> new Graph name exports.loadJSON = (definition, success, metadata = {}) -> definition = JSON.parse definition if typeof definition is 'string' definition.properties = {} unless definition.properties definition.processes = {} unless definition.processes definition.connections = [] unless definition.connections graph = new Graph definition.properties.name graph.startTransaction 'loadJSON', metadata properties = {} for property, value of definition.properties continue if property is 'name' properties[property] = value graph.setProperties properties for id, def of definition.processes def.metadata = {} unless def.metadata graph.addNode id, def.component, def.metadata for conn in definition.connections metadata = if conn.metadata then conn.metadata else {} if conn.data isnt undefined if typeof conn.tgt.index is 'number' graph.addInitialIndex conn.data, conn.tgt.process, conn.tgt.port.toLowerCase(), conn.tgt.index, metadata else graph.addInitial conn.data, conn.tgt.process, conn.tgt.port.toLowerCase(), metadata continue if typeof conn.src.index is 'number' or typeof conn.tgt.index is 'number' graph.addEdgeIndex conn.src.process, conn.src.port.toLowerCase(), conn.src.index, conn.tgt.process, conn.tgt.port.toLowerCase(), conn.tgt.index, metadata continue graph.addEdge conn.src.process, conn.src.port.toLowerCase(), conn.tgt.process, conn.tgt.port.toLowerCase(), metadata if definition.exports and definition.exports.length for exported in definition.exports if exported.private # Translate legacy ports to new split = exported.private.split('.') continue unless split.length is 2 processId = split[0] portId = split[1] # Get properly cased process id for id of definition.processes if id.toLowerCase() is processId.toLowerCase() processId = id else processId = exported.process portId = exported.port graph.addExport exported.public, processId, portId, exported.metadata if definition.inports for pub, priv of definition.inports graph.addInport pub, priv.process, priv.port, priv.metadata if definition.outports for pub, priv of definition.outports graph.addOutport pub, priv.process, priv.port, priv.metadata if definition.groups for group in definition.groups graph.addGroup group.name, group.nodes, group.metadata || {} graph.endTransaction 'loadJSON' success graph exports.loadFBP = (fbpData, success) -> definition = require('fbp').parse fbpData exports.loadJSON definition, success exports.loadHTTP = (url, success) -> req = new XMLHttpRequest req.onreadystatechange = -> return unless req.readyState is 4 return success() unless req.status is 200 success req.responseText req.open 'GET', url, true req.send() exports.loadFile = (file, success, metadata = {}) -> if platform.isBrowser() try # Graph exposed via Component packaging definition = require file catch e # Graph available via HTTP exports.loadHTTP file, (data) -> unless data throw new Error "Failed to load graph #{file}" return if file.split('.').pop() is 'fbp' return exports.loadFBP data, success, metadata definition = JSON.parse data exports.loadJSON definition, success, metadata return exports.loadJSON definition, success, metadata return # Node.js graph file require('fs').readFile file, "utf-8", (err, data) -> throw err if err if file.split('.').pop() is 'fbp' return exports.loadFBP data, success definition = JSON.parse data exports.loadJSON definition, success # remove everything in the graph resetGraph = (graph) -> # Edges and similar first, to have control over the order # If we'd do nodes first, it will implicitly delete edges # Important to make journal transactions invertible for group in (clone graph.groups).reverse() graph.removeGroup group.name if group? for port, v of clone graph.outports graph.removeOutport port for port, v of clone graph.inports graph.removeInport port for exp in clone (graph.exports).reverse() graph.removeExports exp.public # XXX: does this actually null the props?? graph.setProperties {} for iip in (clone graph.initializers).reverse() graph.removeInitial iip.to.node, iip.to.port for edge in (clone graph.edges).reverse() graph.removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port for node in (clone graph.nodes).reverse() graph.removeNode node.id # Note: Caller should create transaction # First removes everything in @base, before building it up to mirror @to mergeResolveTheirsNaive = (base, to) -> resetGraph base for node in to.nodes base.addNode node.id, node.component, node.metadata for edge in to.edges base.addEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port, edge.metadata for iip in to.initializers base.addInitial iip.from.data, iip.to.node, iip.to.port, iip.metadata for exp in to.exports base.addExport exp.public, exp.node, exp.port, exp.metadata base.setProperties to.properties for pub, priv of to.inports base.addInport pub, priv.process, priv.port, priv.metadata for pub, priv of to.outports base.addOutport pub, priv.process, priv.port, priv.metadata for group in to.groups base.addGroup group.name, group.nodes, group.metadata exports.equivalent = (a, b, options = {}) -> # TODO: add option to only compare known fields # TODO: add option to ignore metadata A = JSON.stringify a B = JSON.stringify b return A == B exports.mergeResolveTheirs = mergeResolveTheirsNaive
39734
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 <NAME>, <NAME> # NoFlo may be freely distributed under the MIT license # # NoFlo graphs are Event Emitters, providing signals when the graph # definition changes. # {EventEmitter} = require 'events' clone = require('./Utils').clone platform = require './Platform' # This class represents an abstract NoFlo graph containing nodes # connected to each other with edges. # # These graphs can be used for visualization and sketching, but # also are the way to start a NoFlo network. class Graph extends EventEmitter name: '' properties: {} nodes: [] edges: [] initializers: [] exports: [] inports: {} outports: {} groups: [] # ## Creating new graphs # # Graphs are created by simply instantiating the Graph class # and giving it a name: # # myGraph = new Graph 'My very cool graph' constructor: (@name = '') -> @properties = {} @nodes = [] @edges = [] @initializers = [] @exports = [] @inports = {} @outports = {} @groups = [] @transaction = id: null depth: 0 # ## Group graph changes into transactions # # If no transaction is explicitly opened, each call to # the graph API will implicitly create a transaction for that change startTransaction: (id, metadata) -> if @transaction.id throw Error("Nested transactions not supported") @transaction.id = id @transaction.depth = 1 @emit 'startTransaction', id, metadata endTransaction: (id, metadata) -> if not @transaction.id throw Error("Attempted to end non-existing transaction") @transaction.id = null @transaction.depth = 0 @emit 'endTransaction', id, metadata checkTransactionStart: () -> if not @transaction.id @startTransaction 'implicit' else if @transaction.id == 'implicit' @transaction.depth += 1 checkTransactionEnd: () -> if @transaction.id == 'implicit' @transaction.depth -= 1 if @transaction.depth == 0 @endTransaction 'implicit' # ## Modifying Graph properties # # This method allows changing properties of the graph. setProperties: (properties) -> @checkTransactionStart() before = clone @properties for item, val of properties @properties[item] = val @emit 'changeProperties', @properties, before @checkTransactionEnd() # ## Exporting a port from subgraph # # This allows subgraphs to expose a cleaner API by having reasonably # named ports shown instead of all the free ports of the graph # # The ports exported using this way are ambiguous in their direciton. Use # `addInport` or `addOutport` instead to disambiguate. addExport: (publicPort, nodeKey, portKey, metadata = {x:0,y:0}) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() exported = public: publicPort process: nodeKey port: portKey metadata: metadata @exports.push exported @emit 'addExport', exported @checkTransactionEnd() removeExport: (publicPort) -> publicPort = publicPort.toLowerCase() found = null for exported, idx in @exports found = exported if exported.public is publicPort return unless found @checkTransactionStart() @exports.splice @exports.indexOf(found), 1 @emit 'removeExport', found @checkTransactionEnd() addInport: (publicPort, nodeKey, portKey, metadata) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() @inports[publicPort] = process: nodeKey port: portKey metadata: metadata @emit 'addInport', publicPort, @inports[publicPort] @checkTransactionEnd() removeInport: (publicPort) -> publicPort = publicPort.toLowerCase() return unless @inports[publicPort] @checkTransactionStart() port = @inports[publicPort] @setInportMetadata publicPort, {} delete @inports[publicPort] @emit 'removeInport', publicPort, port @checkTransactionEnd() renameInport: (oldPort, newPort) -> return unless @inports[oldPort] @checkTransactionStart() @inports[newPort] = @inports[oldPort] delete @inports[oldPort] @emit 'renameInport', oldPort, newPort @checkTransactionEnd() setInportMetadata: (publicPort, metadata) -> return unless @inports[publicPort] @checkTransactionStart() before = clone @inports[publicPort].metadata @inports[publicPort].metadata = {} unless @inports[publicPort].metadata for item, val of metadata if val? @inports[publicPort].metadata[item] = val else delete @inports[publicPort].metadata[item] @emit 'changeInport', publicPort, @inports[publicPort], before @checkTransactionEnd() addOutport: (publicPort, nodeKey, portKey, metadata) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() @outports[publicPort] = process: nodeKey port: portKey metadata: metadata @emit 'addOutport', publicPort, @outports[publicPort] @checkTransactionEnd() removeOutport: (publicPort) -> publicPort = publicPort.toLowerCase() return unless @outports[publicPort] @checkTransactionStart() port = @outports[publicPort] @setOutportMetadata publicPort, {} delete @outports[publicPort] @emit 'removeOutport', publicPort, port @checkTransactionEnd() renameOutport: (oldPort, newPort) -> return unless @outports[oldPort] @checkTransactionStart() @outports[newPort] = @outports[oldPort] delete @outports[oldPort] @emit 'renameOutport', oldPort, newPort @checkTransactionEnd() setOutportMetadata: (publicPort, metadata) -> return unless @outports[publicPort] @checkTransactionStart() before = clone @outports[publicPort].metadata @outports[publicPort].metadata = {} unless @outports[publicPort].metadata for item, val of metadata if val? @outports[publicPort].metadata[item] = val else delete @outports[publicPort].metadata[item] @emit 'changeOutport', publicPort, @outports[publicPort], before @checkTransactionEnd() # ## Grouping nodes in a graph # addGroup: (group, nodes, metadata) -> @checkTransactionStart() g = name: group nodes: nodes metadata: metadata @groups.push g @emit 'addGroup', g @checkTransactionEnd() renameGroup: (oldName, newName) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is oldName group.name = newName @emit 'renameGroup', oldName, newName @checkTransactionEnd() removeGroup: (groupName) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is groupName @setGroupMetadata group.name, {} @groups.splice @groups.indexOf(group), 1 @emit 'removeGroup', group @checkTransactionEnd() setGroupMetadata: (groupName, metadata) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is groupName before = clone group.metadata for item, val of metadata if val? group.metadata[item] = val else delete group.metadata[item] @emit 'changeGroup', group, before @checkTransactionEnd() # ## Adding a node to the graph # # Nodes are identified by an ID unique to the graph. Additionally, # a node may contain information on what NoFlo component it is and # possible display coordinates. # # For example: # # myGraph.addNode 'Read, 'ReadFile', # x: 91 # y: 154 # # Addition of a node will emit the `addNode` event. addNode: (id, component, metadata) -> @checkTransactionStart() metadata = {} unless metadata node = id: id component: component metadata: metadata @nodes.push node @emit 'addNode', node @checkTransactionEnd() node # ## Removing a node from the graph # # Existing nodes can be removed from a graph by their ID. This # will remove the node and also remove all edges connected to it. # # myGraph.removeNode 'Read' # # Once the node has been removed, the `removeNode` event will be # emitted. removeNode: (id) -> node = @getNode id return unless node @checkTransactionStart() toRemove = [] for edge in @edges if (edge.from.node is node.id) or (edge.to.node is node.id) toRemove.push edge for edge in toRemove @removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port toRemove = [] for initializer in @initializers if initializer.to.node is node.id toRemove.push initializer for initializer in toRemove @removeInitial initializer.to.node, initializer.to.port toRemove = [] for exported in @exports if id.toLowerCase() is exported.process toRemove.push exported for exported in toRemove @removeExports exported.public toRemove = [] for pub, priv of @inports if priv.process is id toRemove.push pub for pub in toRemove @removeInport pub toRemove = [] for pub, priv of @outports if priv.process is id toRemove.push pub for pub in toRemove @removeOutport pub for group in @groups continue unless group index = group.nodes.indexOf(id) continue if index is -1 group.nodes.splice index, 1 @setNodeMetadata id, {} if -1 isnt @nodes.indexOf node @nodes.splice @nodes.indexOf(node), 1 @emit 'removeNode', node @checkTransactionEnd() # ## Getting a node # # Nodes objects can be retrieved from the graph by their ID: # # myNode = myGraph.getNode 'Read' getNode: (id) -> for node in @nodes continue unless node return node if node.id is id return null # ## Renaming a node # # Nodes IDs can be changed by calling this method. renameNode: (oldId, newId) -> @checkTransactionStart() node = @getNode oldId return unless node node.id = newId for edge in @edges continue unless edge if edge.from.node is oldId edge.from.node = newId if edge.to.node is oldId edge.to.node = newId for iip in @initializers continue unless iip if iip.to.node is oldId iip.to.node = newId for pub, priv of @inports if priv.process is oldId priv.process = newId for pub, priv of @outports if priv.process is oldId priv.process = newId for exported in @exports if exported.process is oldId exported.process = newId for group in @groups continue unless group index = group.nodes.indexOf(oldId) continue if index is -1 group.nodes[index] = newId @emit 'renameNode', oldId, newId @checkTransactionEnd() # ## Changing a node's metadata # # Node metadata can be set or changed by calling this method. setNodeMetadata: (id, metadata) -> node = @getNode id return unless node @checkTransactionStart() before = clone node.metadata node.metadata = {} unless node.metadata for item, val of metadata if val? node.metadata[item] = val else delete node.metadata[item] @emit 'changeNode', node, before @checkTransactionEnd() # ## Connecting nodes # # Nodes can be connected by adding edges between a node's outport # and another node's inport: # # myGraph.addEdge 'Read', 'out', 'Display', 'in' # myGraph.addEdgeIndex 'Read', 'out', null, 'Display', 'in', 2 # # Adding an edge will emit the `addEdge` event. addEdge: (outNode, outPort, inNode, inPort, metadata = {}) -> for edge in @edges # don't add a duplicate edge return if (edge.from.node is outNode and edge.from.port is outPort and edge.to.node is inNode and edge.to.port is inPort) return unless @getNode outNode return unless @getNode inNode @checkTransactionStart() edge = from: node: outNode port: outPort to: node: inNode port: inPort metadata: metadata @edges.push edge @emit 'addEdge', edge @checkTransactionEnd() edge # Adding an edge will emit the `addEdge` event. addEdgeIndex: (outNode, outPort, outIndex, inNode, inPort, inIndex, metadata = {}) -> return unless @getNode outNode return unless @getNode inNode inIndex = undefined if inIndex is null outIndex = undefined if outIndex is null metadata = {} unless metadata @checkTransactionStart() edge = from: node: outNode port: outPort index: outIndex to: node: inNode port: inPort index: inIndex metadata: metadata @edges.push edge @emit 'addEdge', edge @checkTransactionEnd() edge # ## Disconnected nodes # # Connections between nodes can be removed by providing the # nodes and ports to disconnect. # # myGraph.removeEdge 'Display', 'out', 'Foo', 'in' # # Removing a connection will emit the `removeEdge` event. removeEdge: (node, port, node2, port2) -> @checkTransactionStart() toRemove = [] toKeep = [] if node2 and port2 for edge,index in @edges if edge.from.node is node and edge.from.port is port and edge.to.node is node2 and edge.to.port is port2 @setEdgeMetadata edge.from.node, edge.from.port, edge.to.node, edge.to.port, {} toRemove.push edge else toKeep.push edge else for edge,index in @edges if (edge.from.node is node and edge.from.port is port) or (edge.to.node is node and edge.to.port is port) @setEdgeMetadata edge.from.node, edge.from.port, edge.to.node, edge.to.port, {} toRemove.push edge else toKeep.push edge @edges = toKeep for edge in toRemove @emit 'removeEdge', edge @checkTransactionEnd() # ## Getting an edge # # Edge objects can be retrieved from the graph by the node and port IDs: # # myEdge = myGraph.getEdge 'Read', 'out', 'Write', 'in' getEdge: (node, port, node2, port2) -> for edge,index in @edges continue unless edge if edge.from.node is node and edge.from.port is port if edge.to.node is node2 and edge.to.port is port2 return edge return null # ## Changing an edge's metadata # # Edge metadata can be set or changed by calling this method. setEdgeMetadata: (node, port, node2, port2, metadata) -> edge = @getEdge node, port, node2, port2 return unless edge @checkTransactionStart() before = clone edge.metadata edge.metadata = {} unless edge.metadata for item, val of metadata if val? edge.metadata[item] = val else delete edge.metadata[item] @emit 'changeEdge', edge, before @checkTransactionEnd() # ## Adding Initial Information Packets # # Initial Information Packets (IIPs) can be used for sending data # to specified node inports without a sending node instance. # # IIPs are especially useful for sending configuration information # to components at NoFlo network start-up time. This could include # filenames to read, or network ports to listen to. # # myGraph.addInitial 'somefile.txt', 'Read', 'source' # myGraph.addInitialIndex 'somefile.txt', 'Read', 'source', 2 # # If inports are defined on the graph, IIPs can be applied calling # the `addGraphInitial` or `addGraphInitialIndex` methods. # # myGraph.addGraphInitial 'somefile.txt', 'file' # myGraph.addGraphInitialIndex 'somefile.txt', 'file', 2 # # Adding an IIP will emit a `addInitial` event. addInitial: (data, node, port, metadata) -> return unless @getNode node @checkTransactionStart() initializer = from: data: data to: node: node port: port metadata: metadata @initializers.push initializer @emit 'addInitial', initializer @checkTransactionEnd() initializer addInitialIndex: (data, node, port, index, metadata) -> return unless @getNode node index = undefined if index is null @checkTransactionStart() initializer = from: data: data to: node: node port: port index: index metadata: metadata @initializers.push initializer @emit 'addInitial', initializer @checkTransactionEnd() initializer addGraphInitial: (data, node, metadata) -> inport = @inports[node] return unless inport @addInitial data, inport.process, inport.port, metadata addGraphInitialIndex: (data, node, index, metadata) -> inport = @inports[node] return unless inport @addInitialIndex data, inport.process, inport.port, index, metadata # ## Removing Initial Information Packets # # IIPs can be removed by calling the `removeInitial` method. # # myGraph.removeInitial 'Read', 'source' # # If the IIP was applied via the `addGraphInitial` or # `addGraphInitialIndex` functions, it can be removed using # the `removeGraphInitial` method. # # myGraph.removeGraphInitial 'file' # # Remove an IIP will emit a `removeInitial` event. removeInitial: (node, port) -> @checkTransactionStart() toRemove = [] toKeep = [] for edge, index in @initializers if edge.to.node is node and edge.to.port is port toRemove.push edge else toKeep.push edge @initializers = toKeep for edge in toRemove @emit 'removeInitial', edge @checkTransactionEnd() removeGraphInitial: (node) -> inport = @inports[node] return unless inport @removeInitial inport.process, inport.port toDOT: -> cleanID = (id) -> id.replace /\s*/g, "" cleanPort = (port) -> port.replace /\./g, "" dot = "digraph {\n" for node in @nodes dot += " #{cleanID(node.id)} [label=#{node.id} shape=box]\n" for initializer, id in @initializers if typeof initializer.from.data is 'function' data = 'Function' else data = initializer.from.data dot += " data#{id} [label=\"'#{data}'\" shape=plaintext]\n" dot += " data#{id} -> #{cleanID(initializer.to.node)}[headlabel=#{cleanPort(initializer.to.port)} labelfontcolor=blue labelfontsize=8.0]\n" for edge in @edges dot += " #{cleanID(edge.from.node)} -> #{cleanID(edge.to.node)}[taillabel=#{cleanPort(edge.from.port)} headlabel=#{cleanPort(edge.to.port)} labelfontcolor=blue labelfontsize=8.0]\n" dot += "}" return dot toYUML: -> yuml = [] for initializer in @initializers yuml.push "(start)[#{initializer.to.port}]->(#{initializer.to.node})" for edge in @edges yuml.push "(#{edge.from.node})[#{edge.from.port}]->(#{edge.to.node})" yuml.join "," toJSON: -> json = properties: {} inports: {} outports: {} groups: [] processes: {} connections: [] json.properties.name = @name if @name for property, value of @properties json.properties[property] = value for pub, priv of @inports json.inports[pub] = priv for pub, priv of @outports json.outports[pub] = priv # Legacy exported ports for exported in @exports json.exports = [] unless json.exports json.exports.push exported for group in @groups groupData = name: group.name nodes: group.nodes if Object.keys(group.metadata).length groupData.metadata = group.metadata json.groups.push groupData for node in @nodes json.processes[node.id] = component: node.component if node.metadata json.processes[node.id].metadata = node.metadata for edge in @edges connection = src: process: edge.from.node port: edge.from.port index: edge.from.index tgt: process: edge.to.node port: edge.to.port index: edge.to.index connection.metadata = edge.metadata if Object.keys(edge.metadata).length json.connections.push connection for initializer in @initializers json.connections.push data: initializer.from.data tgt: process: initializer.to.node port: initializer.to.port index: initializer.to.index json save: (file, success) -> json = JSON.stringify @toJSON(), null, 4 require('fs').writeFile "#{file}.json", json, "utf-8", (err, data) -> throw err if err success file exports.Graph = Graph exports.createGraph = (name) -> new Graph name exports.loadJSON = (definition, success, metadata = {}) -> definition = JSON.parse definition if typeof definition is 'string' definition.properties = {} unless definition.properties definition.processes = {} unless definition.processes definition.connections = [] unless definition.connections graph = new Graph definition.properties.name graph.startTransaction 'loadJSON', metadata properties = {} for property, value of definition.properties continue if property is 'name' properties[property] = value graph.setProperties properties for id, def of definition.processes def.metadata = {} unless def.metadata graph.addNode id, def.component, def.metadata for conn in definition.connections metadata = if conn.metadata then conn.metadata else {} if conn.data isnt undefined if typeof conn.tgt.index is 'number' graph.addInitialIndex conn.data, conn.tgt.process, conn.tgt.port.toLowerCase(), conn.tgt.index, metadata else graph.addInitial conn.data, conn.tgt.process, conn.tgt.port.toLowerCase(), metadata continue if typeof conn.src.index is 'number' or typeof conn.tgt.index is 'number' graph.addEdgeIndex conn.src.process, conn.src.port.toLowerCase(), conn.src.index, conn.tgt.process, conn.tgt.port.toLowerCase(), conn.tgt.index, metadata continue graph.addEdge conn.src.process, conn.src.port.toLowerCase(), conn.tgt.process, conn.tgt.port.toLowerCase(), metadata if definition.exports and definition.exports.length for exported in definition.exports if exported.private # Translate legacy ports to new split = exported.private.split('.') continue unless split.length is 2 processId = split[0] portId = split[1] # Get properly cased process id for id of definition.processes if id.toLowerCase() is processId.toLowerCase() processId = id else processId = exported.process portId = exported.port graph.addExport exported.public, processId, portId, exported.metadata if definition.inports for pub, priv of definition.inports graph.addInport pub, priv.process, priv.port, priv.metadata if definition.outports for pub, priv of definition.outports graph.addOutport pub, priv.process, priv.port, priv.metadata if definition.groups for group in definition.groups graph.addGroup group.name, group.nodes, group.metadata || {} graph.endTransaction 'loadJSON' success graph exports.loadFBP = (fbpData, success) -> definition = require('fbp').parse fbpData exports.loadJSON definition, success exports.loadHTTP = (url, success) -> req = new XMLHttpRequest req.onreadystatechange = -> return unless req.readyState is 4 return success() unless req.status is 200 success req.responseText req.open 'GET', url, true req.send() exports.loadFile = (file, success, metadata = {}) -> if platform.isBrowser() try # Graph exposed via Component packaging definition = require file catch e # Graph available via HTTP exports.loadHTTP file, (data) -> unless data throw new Error "Failed to load graph #{file}" return if file.split('.').pop() is 'fbp' return exports.loadFBP data, success, metadata definition = JSON.parse data exports.loadJSON definition, success, metadata return exports.loadJSON definition, success, metadata return # Node.js graph file require('fs').readFile file, "utf-8", (err, data) -> throw err if err if file.split('.').pop() is 'fbp' return exports.loadFBP data, success definition = JSON.parse data exports.loadJSON definition, success # remove everything in the graph resetGraph = (graph) -> # Edges and similar first, to have control over the order # If we'd do nodes first, it will implicitly delete edges # Important to make journal transactions invertible for group in (clone graph.groups).reverse() graph.removeGroup group.name if group? for port, v of clone graph.outports graph.removeOutport port for port, v of clone graph.inports graph.removeInport port for exp in clone (graph.exports).reverse() graph.removeExports exp.public # XXX: does this actually null the props?? graph.setProperties {} for iip in (clone graph.initializers).reverse() graph.removeInitial iip.to.node, iip.to.port for edge in (clone graph.edges).reverse() graph.removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port for node in (clone graph.nodes).reverse() graph.removeNode node.id # Note: Caller should create transaction # First removes everything in @base, before building it up to mirror @to mergeResolveTheirsNaive = (base, to) -> resetGraph base for node in to.nodes base.addNode node.id, node.component, node.metadata for edge in to.edges base.addEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port, edge.metadata for iip in to.initializers base.addInitial iip.from.data, iip.to.node, iip.to.port, iip.metadata for exp in to.exports base.addExport exp.public, exp.node, exp.port, exp.metadata base.setProperties to.properties for pub, priv of to.inports base.addInport pub, priv.process, priv.port, priv.metadata for pub, priv of to.outports base.addOutport pub, priv.process, priv.port, priv.metadata for group in to.groups base.addGroup group.name, group.nodes, group.metadata exports.equivalent = (a, b, options = {}) -> # TODO: add option to only compare known fields # TODO: add option to ignore metadata A = JSON.stringify a B = JSON.stringify b return A == B exports.mergeResolveTheirs = mergeResolveTheirsNaive
true
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # NoFlo may be freely distributed under the MIT license # # NoFlo graphs are Event Emitters, providing signals when the graph # definition changes. # {EventEmitter} = require 'events' clone = require('./Utils').clone platform = require './Platform' # This class represents an abstract NoFlo graph containing nodes # connected to each other with edges. # # These graphs can be used for visualization and sketching, but # also are the way to start a NoFlo network. class Graph extends EventEmitter name: '' properties: {} nodes: [] edges: [] initializers: [] exports: [] inports: {} outports: {} groups: [] # ## Creating new graphs # # Graphs are created by simply instantiating the Graph class # and giving it a name: # # myGraph = new Graph 'My very cool graph' constructor: (@name = '') -> @properties = {} @nodes = [] @edges = [] @initializers = [] @exports = [] @inports = {} @outports = {} @groups = [] @transaction = id: null depth: 0 # ## Group graph changes into transactions # # If no transaction is explicitly opened, each call to # the graph API will implicitly create a transaction for that change startTransaction: (id, metadata) -> if @transaction.id throw Error("Nested transactions not supported") @transaction.id = id @transaction.depth = 1 @emit 'startTransaction', id, metadata endTransaction: (id, metadata) -> if not @transaction.id throw Error("Attempted to end non-existing transaction") @transaction.id = null @transaction.depth = 0 @emit 'endTransaction', id, metadata checkTransactionStart: () -> if not @transaction.id @startTransaction 'implicit' else if @transaction.id == 'implicit' @transaction.depth += 1 checkTransactionEnd: () -> if @transaction.id == 'implicit' @transaction.depth -= 1 if @transaction.depth == 0 @endTransaction 'implicit' # ## Modifying Graph properties # # This method allows changing properties of the graph. setProperties: (properties) -> @checkTransactionStart() before = clone @properties for item, val of properties @properties[item] = val @emit 'changeProperties', @properties, before @checkTransactionEnd() # ## Exporting a port from subgraph # # This allows subgraphs to expose a cleaner API by having reasonably # named ports shown instead of all the free ports of the graph # # The ports exported using this way are ambiguous in their direciton. Use # `addInport` or `addOutport` instead to disambiguate. addExport: (publicPort, nodeKey, portKey, metadata = {x:0,y:0}) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() exported = public: publicPort process: nodeKey port: portKey metadata: metadata @exports.push exported @emit 'addExport', exported @checkTransactionEnd() removeExport: (publicPort) -> publicPort = publicPort.toLowerCase() found = null for exported, idx in @exports found = exported if exported.public is publicPort return unless found @checkTransactionStart() @exports.splice @exports.indexOf(found), 1 @emit 'removeExport', found @checkTransactionEnd() addInport: (publicPort, nodeKey, portKey, metadata) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() @inports[publicPort] = process: nodeKey port: portKey metadata: metadata @emit 'addInport', publicPort, @inports[publicPort] @checkTransactionEnd() removeInport: (publicPort) -> publicPort = publicPort.toLowerCase() return unless @inports[publicPort] @checkTransactionStart() port = @inports[publicPort] @setInportMetadata publicPort, {} delete @inports[publicPort] @emit 'removeInport', publicPort, port @checkTransactionEnd() renameInport: (oldPort, newPort) -> return unless @inports[oldPort] @checkTransactionStart() @inports[newPort] = @inports[oldPort] delete @inports[oldPort] @emit 'renameInport', oldPort, newPort @checkTransactionEnd() setInportMetadata: (publicPort, metadata) -> return unless @inports[publicPort] @checkTransactionStart() before = clone @inports[publicPort].metadata @inports[publicPort].metadata = {} unless @inports[publicPort].metadata for item, val of metadata if val? @inports[publicPort].metadata[item] = val else delete @inports[publicPort].metadata[item] @emit 'changeInport', publicPort, @inports[publicPort], before @checkTransactionEnd() addOutport: (publicPort, nodeKey, portKey, metadata) -> # Check that node exists return unless @getNode nodeKey @checkTransactionStart() @outports[publicPort] = process: nodeKey port: portKey metadata: metadata @emit 'addOutport', publicPort, @outports[publicPort] @checkTransactionEnd() removeOutport: (publicPort) -> publicPort = publicPort.toLowerCase() return unless @outports[publicPort] @checkTransactionStart() port = @outports[publicPort] @setOutportMetadata publicPort, {} delete @outports[publicPort] @emit 'removeOutport', publicPort, port @checkTransactionEnd() renameOutport: (oldPort, newPort) -> return unless @outports[oldPort] @checkTransactionStart() @outports[newPort] = @outports[oldPort] delete @outports[oldPort] @emit 'renameOutport', oldPort, newPort @checkTransactionEnd() setOutportMetadata: (publicPort, metadata) -> return unless @outports[publicPort] @checkTransactionStart() before = clone @outports[publicPort].metadata @outports[publicPort].metadata = {} unless @outports[publicPort].metadata for item, val of metadata if val? @outports[publicPort].metadata[item] = val else delete @outports[publicPort].metadata[item] @emit 'changeOutport', publicPort, @outports[publicPort], before @checkTransactionEnd() # ## Grouping nodes in a graph # addGroup: (group, nodes, metadata) -> @checkTransactionStart() g = name: group nodes: nodes metadata: metadata @groups.push g @emit 'addGroup', g @checkTransactionEnd() renameGroup: (oldName, newName) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is oldName group.name = newName @emit 'renameGroup', oldName, newName @checkTransactionEnd() removeGroup: (groupName) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is groupName @setGroupMetadata group.name, {} @groups.splice @groups.indexOf(group), 1 @emit 'removeGroup', group @checkTransactionEnd() setGroupMetadata: (groupName, metadata) -> @checkTransactionStart() for group in @groups continue unless group continue unless group.name is groupName before = clone group.metadata for item, val of metadata if val? group.metadata[item] = val else delete group.metadata[item] @emit 'changeGroup', group, before @checkTransactionEnd() # ## Adding a node to the graph # # Nodes are identified by an ID unique to the graph. Additionally, # a node may contain information on what NoFlo component it is and # possible display coordinates. # # For example: # # myGraph.addNode 'Read, 'ReadFile', # x: 91 # y: 154 # # Addition of a node will emit the `addNode` event. addNode: (id, component, metadata) -> @checkTransactionStart() metadata = {} unless metadata node = id: id component: component metadata: metadata @nodes.push node @emit 'addNode', node @checkTransactionEnd() node # ## Removing a node from the graph # # Existing nodes can be removed from a graph by their ID. This # will remove the node and also remove all edges connected to it. # # myGraph.removeNode 'Read' # # Once the node has been removed, the `removeNode` event will be # emitted. removeNode: (id) -> node = @getNode id return unless node @checkTransactionStart() toRemove = [] for edge in @edges if (edge.from.node is node.id) or (edge.to.node is node.id) toRemove.push edge for edge in toRemove @removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port toRemove = [] for initializer in @initializers if initializer.to.node is node.id toRemove.push initializer for initializer in toRemove @removeInitial initializer.to.node, initializer.to.port toRemove = [] for exported in @exports if id.toLowerCase() is exported.process toRemove.push exported for exported in toRemove @removeExports exported.public toRemove = [] for pub, priv of @inports if priv.process is id toRemove.push pub for pub in toRemove @removeInport pub toRemove = [] for pub, priv of @outports if priv.process is id toRemove.push pub for pub in toRemove @removeOutport pub for group in @groups continue unless group index = group.nodes.indexOf(id) continue if index is -1 group.nodes.splice index, 1 @setNodeMetadata id, {} if -1 isnt @nodes.indexOf node @nodes.splice @nodes.indexOf(node), 1 @emit 'removeNode', node @checkTransactionEnd() # ## Getting a node # # Nodes objects can be retrieved from the graph by their ID: # # myNode = myGraph.getNode 'Read' getNode: (id) -> for node in @nodes continue unless node return node if node.id is id return null # ## Renaming a node # # Nodes IDs can be changed by calling this method. renameNode: (oldId, newId) -> @checkTransactionStart() node = @getNode oldId return unless node node.id = newId for edge in @edges continue unless edge if edge.from.node is oldId edge.from.node = newId if edge.to.node is oldId edge.to.node = newId for iip in @initializers continue unless iip if iip.to.node is oldId iip.to.node = newId for pub, priv of @inports if priv.process is oldId priv.process = newId for pub, priv of @outports if priv.process is oldId priv.process = newId for exported in @exports if exported.process is oldId exported.process = newId for group in @groups continue unless group index = group.nodes.indexOf(oldId) continue if index is -1 group.nodes[index] = newId @emit 'renameNode', oldId, newId @checkTransactionEnd() # ## Changing a node's metadata # # Node metadata can be set or changed by calling this method. setNodeMetadata: (id, metadata) -> node = @getNode id return unless node @checkTransactionStart() before = clone node.metadata node.metadata = {} unless node.metadata for item, val of metadata if val? node.metadata[item] = val else delete node.metadata[item] @emit 'changeNode', node, before @checkTransactionEnd() # ## Connecting nodes # # Nodes can be connected by adding edges between a node's outport # and another node's inport: # # myGraph.addEdge 'Read', 'out', 'Display', 'in' # myGraph.addEdgeIndex 'Read', 'out', null, 'Display', 'in', 2 # # Adding an edge will emit the `addEdge` event. addEdge: (outNode, outPort, inNode, inPort, metadata = {}) -> for edge in @edges # don't add a duplicate edge return if (edge.from.node is outNode and edge.from.port is outPort and edge.to.node is inNode and edge.to.port is inPort) return unless @getNode outNode return unless @getNode inNode @checkTransactionStart() edge = from: node: outNode port: outPort to: node: inNode port: inPort metadata: metadata @edges.push edge @emit 'addEdge', edge @checkTransactionEnd() edge # Adding an edge will emit the `addEdge` event. addEdgeIndex: (outNode, outPort, outIndex, inNode, inPort, inIndex, metadata = {}) -> return unless @getNode outNode return unless @getNode inNode inIndex = undefined if inIndex is null outIndex = undefined if outIndex is null metadata = {} unless metadata @checkTransactionStart() edge = from: node: outNode port: outPort index: outIndex to: node: inNode port: inPort index: inIndex metadata: metadata @edges.push edge @emit 'addEdge', edge @checkTransactionEnd() edge # ## Disconnected nodes # # Connections between nodes can be removed by providing the # nodes and ports to disconnect. # # myGraph.removeEdge 'Display', 'out', 'Foo', 'in' # # Removing a connection will emit the `removeEdge` event. removeEdge: (node, port, node2, port2) -> @checkTransactionStart() toRemove = [] toKeep = [] if node2 and port2 for edge,index in @edges if edge.from.node is node and edge.from.port is port and edge.to.node is node2 and edge.to.port is port2 @setEdgeMetadata edge.from.node, edge.from.port, edge.to.node, edge.to.port, {} toRemove.push edge else toKeep.push edge else for edge,index in @edges if (edge.from.node is node and edge.from.port is port) or (edge.to.node is node and edge.to.port is port) @setEdgeMetadata edge.from.node, edge.from.port, edge.to.node, edge.to.port, {} toRemove.push edge else toKeep.push edge @edges = toKeep for edge in toRemove @emit 'removeEdge', edge @checkTransactionEnd() # ## Getting an edge # # Edge objects can be retrieved from the graph by the node and port IDs: # # myEdge = myGraph.getEdge 'Read', 'out', 'Write', 'in' getEdge: (node, port, node2, port2) -> for edge,index in @edges continue unless edge if edge.from.node is node and edge.from.port is port if edge.to.node is node2 and edge.to.port is port2 return edge return null # ## Changing an edge's metadata # # Edge metadata can be set or changed by calling this method. setEdgeMetadata: (node, port, node2, port2, metadata) -> edge = @getEdge node, port, node2, port2 return unless edge @checkTransactionStart() before = clone edge.metadata edge.metadata = {} unless edge.metadata for item, val of metadata if val? edge.metadata[item] = val else delete edge.metadata[item] @emit 'changeEdge', edge, before @checkTransactionEnd() # ## Adding Initial Information Packets # # Initial Information Packets (IIPs) can be used for sending data # to specified node inports without a sending node instance. # # IIPs are especially useful for sending configuration information # to components at NoFlo network start-up time. This could include # filenames to read, or network ports to listen to. # # myGraph.addInitial 'somefile.txt', 'Read', 'source' # myGraph.addInitialIndex 'somefile.txt', 'Read', 'source', 2 # # If inports are defined on the graph, IIPs can be applied calling # the `addGraphInitial` or `addGraphInitialIndex` methods. # # myGraph.addGraphInitial 'somefile.txt', 'file' # myGraph.addGraphInitialIndex 'somefile.txt', 'file', 2 # # Adding an IIP will emit a `addInitial` event. addInitial: (data, node, port, metadata) -> return unless @getNode node @checkTransactionStart() initializer = from: data: data to: node: node port: port metadata: metadata @initializers.push initializer @emit 'addInitial', initializer @checkTransactionEnd() initializer addInitialIndex: (data, node, port, index, metadata) -> return unless @getNode node index = undefined if index is null @checkTransactionStart() initializer = from: data: data to: node: node port: port index: index metadata: metadata @initializers.push initializer @emit 'addInitial', initializer @checkTransactionEnd() initializer addGraphInitial: (data, node, metadata) -> inport = @inports[node] return unless inport @addInitial data, inport.process, inport.port, metadata addGraphInitialIndex: (data, node, index, metadata) -> inport = @inports[node] return unless inport @addInitialIndex data, inport.process, inport.port, index, metadata # ## Removing Initial Information Packets # # IIPs can be removed by calling the `removeInitial` method. # # myGraph.removeInitial 'Read', 'source' # # If the IIP was applied via the `addGraphInitial` or # `addGraphInitialIndex` functions, it can be removed using # the `removeGraphInitial` method. # # myGraph.removeGraphInitial 'file' # # Remove an IIP will emit a `removeInitial` event. removeInitial: (node, port) -> @checkTransactionStart() toRemove = [] toKeep = [] for edge, index in @initializers if edge.to.node is node and edge.to.port is port toRemove.push edge else toKeep.push edge @initializers = toKeep for edge in toRemove @emit 'removeInitial', edge @checkTransactionEnd() removeGraphInitial: (node) -> inport = @inports[node] return unless inport @removeInitial inport.process, inport.port toDOT: -> cleanID = (id) -> id.replace /\s*/g, "" cleanPort = (port) -> port.replace /\./g, "" dot = "digraph {\n" for node in @nodes dot += " #{cleanID(node.id)} [label=#{node.id} shape=box]\n" for initializer, id in @initializers if typeof initializer.from.data is 'function' data = 'Function' else data = initializer.from.data dot += " data#{id} [label=\"'#{data}'\" shape=plaintext]\n" dot += " data#{id} -> #{cleanID(initializer.to.node)}[headlabel=#{cleanPort(initializer.to.port)} labelfontcolor=blue labelfontsize=8.0]\n" for edge in @edges dot += " #{cleanID(edge.from.node)} -> #{cleanID(edge.to.node)}[taillabel=#{cleanPort(edge.from.port)} headlabel=#{cleanPort(edge.to.port)} labelfontcolor=blue labelfontsize=8.0]\n" dot += "}" return dot toYUML: -> yuml = [] for initializer in @initializers yuml.push "(start)[#{initializer.to.port}]->(#{initializer.to.node})" for edge in @edges yuml.push "(#{edge.from.node})[#{edge.from.port}]->(#{edge.to.node})" yuml.join "," toJSON: -> json = properties: {} inports: {} outports: {} groups: [] processes: {} connections: [] json.properties.name = @name if @name for property, value of @properties json.properties[property] = value for pub, priv of @inports json.inports[pub] = priv for pub, priv of @outports json.outports[pub] = priv # Legacy exported ports for exported in @exports json.exports = [] unless json.exports json.exports.push exported for group in @groups groupData = name: group.name nodes: group.nodes if Object.keys(group.metadata).length groupData.metadata = group.metadata json.groups.push groupData for node in @nodes json.processes[node.id] = component: node.component if node.metadata json.processes[node.id].metadata = node.metadata for edge in @edges connection = src: process: edge.from.node port: edge.from.port index: edge.from.index tgt: process: edge.to.node port: edge.to.port index: edge.to.index connection.metadata = edge.metadata if Object.keys(edge.metadata).length json.connections.push connection for initializer in @initializers json.connections.push data: initializer.from.data tgt: process: initializer.to.node port: initializer.to.port index: initializer.to.index json save: (file, success) -> json = JSON.stringify @toJSON(), null, 4 require('fs').writeFile "#{file}.json", json, "utf-8", (err, data) -> throw err if err success file exports.Graph = Graph exports.createGraph = (name) -> new Graph name exports.loadJSON = (definition, success, metadata = {}) -> definition = JSON.parse definition if typeof definition is 'string' definition.properties = {} unless definition.properties definition.processes = {} unless definition.processes definition.connections = [] unless definition.connections graph = new Graph definition.properties.name graph.startTransaction 'loadJSON', metadata properties = {} for property, value of definition.properties continue if property is 'name' properties[property] = value graph.setProperties properties for id, def of definition.processes def.metadata = {} unless def.metadata graph.addNode id, def.component, def.metadata for conn in definition.connections metadata = if conn.metadata then conn.metadata else {} if conn.data isnt undefined if typeof conn.tgt.index is 'number' graph.addInitialIndex conn.data, conn.tgt.process, conn.tgt.port.toLowerCase(), conn.tgt.index, metadata else graph.addInitial conn.data, conn.tgt.process, conn.tgt.port.toLowerCase(), metadata continue if typeof conn.src.index is 'number' or typeof conn.tgt.index is 'number' graph.addEdgeIndex conn.src.process, conn.src.port.toLowerCase(), conn.src.index, conn.tgt.process, conn.tgt.port.toLowerCase(), conn.tgt.index, metadata continue graph.addEdge conn.src.process, conn.src.port.toLowerCase(), conn.tgt.process, conn.tgt.port.toLowerCase(), metadata if definition.exports and definition.exports.length for exported in definition.exports if exported.private # Translate legacy ports to new split = exported.private.split('.') continue unless split.length is 2 processId = split[0] portId = split[1] # Get properly cased process id for id of definition.processes if id.toLowerCase() is processId.toLowerCase() processId = id else processId = exported.process portId = exported.port graph.addExport exported.public, processId, portId, exported.metadata if definition.inports for pub, priv of definition.inports graph.addInport pub, priv.process, priv.port, priv.metadata if definition.outports for pub, priv of definition.outports graph.addOutport pub, priv.process, priv.port, priv.metadata if definition.groups for group in definition.groups graph.addGroup group.name, group.nodes, group.metadata || {} graph.endTransaction 'loadJSON' success graph exports.loadFBP = (fbpData, success) -> definition = require('fbp').parse fbpData exports.loadJSON definition, success exports.loadHTTP = (url, success) -> req = new XMLHttpRequest req.onreadystatechange = -> return unless req.readyState is 4 return success() unless req.status is 200 success req.responseText req.open 'GET', url, true req.send() exports.loadFile = (file, success, metadata = {}) -> if platform.isBrowser() try # Graph exposed via Component packaging definition = require file catch e # Graph available via HTTP exports.loadHTTP file, (data) -> unless data throw new Error "Failed to load graph #{file}" return if file.split('.').pop() is 'fbp' return exports.loadFBP data, success, metadata definition = JSON.parse data exports.loadJSON definition, success, metadata return exports.loadJSON definition, success, metadata return # Node.js graph file require('fs').readFile file, "utf-8", (err, data) -> throw err if err if file.split('.').pop() is 'fbp' return exports.loadFBP data, success definition = JSON.parse data exports.loadJSON definition, success # remove everything in the graph resetGraph = (graph) -> # Edges and similar first, to have control over the order # If we'd do nodes first, it will implicitly delete edges # Important to make journal transactions invertible for group in (clone graph.groups).reverse() graph.removeGroup group.name if group? for port, v of clone graph.outports graph.removeOutport port for port, v of clone graph.inports graph.removeInport port for exp in clone (graph.exports).reverse() graph.removeExports exp.public # XXX: does this actually null the props?? graph.setProperties {} for iip in (clone graph.initializers).reverse() graph.removeInitial iip.to.node, iip.to.port for edge in (clone graph.edges).reverse() graph.removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port for node in (clone graph.nodes).reverse() graph.removeNode node.id # Note: Caller should create transaction # First removes everything in @base, before building it up to mirror @to mergeResolveTheirsNaive = (base, to) -> resetGraph base for node in to.nodes base.addNode node.id, node.component, node.metadata for edge in to.edges base.addEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port, edge.metadata for iip in to.initializers base.addInitial iip.from.data, iip.to.node, iip.to.port, iip.metadata for exp in to.exports base.addExport exp.public, exp.node, exp.port, exp.metadata base.setProperties to.properties for pub, priv of to.inports base.addInport pub, priv.process, priv.port, priv.metadata for pub, priv of to.outports base.addOutport pub, priv.process, priv.port, priv.metadata for group in to.groups base.addGroup group.name, group.nodes, group.metadata exports.equivalent = (a, b, options = {}) -> # TODO: add option to only compare known fields # TODO: add option to ignore metadata A = JSON.stringify a B = JSON.stringify b return A == B exports.mergeResolveTheirs = mergeResolveTheirsNaive
[ { "context": " ret\n\n pushFileCaching: (file, f) ->\n key = JSON.stringify {pushFileCaching: @userPath(file)}\n ", "end": 14599, "score": 0.5892186164855957, "start": 14595, "tag": "KEY", "value": "JSON" }, { "context": "t\n\n pushFileCaching: (file, f) ->\n key = JSON.stringify {pushFileCaching: @userPath(file)}\n @cache[key", "end": 14609, "score": 0.5053763389587402, "start": 14600, "tag": "KEY", "value": "stringify" } ]
root/usr/src/template-package/lib/cfn-transformer.coffee
showmethemodel/cfn-tool
0
yaml = require 'js-yaml' fs = require 'fs' os = require 'os' path = require 'path' assert = require 'assert' crypto = require 'crypto' {spawnSync} = require 'child_process' YamlTransformer = require './yaml-transformer' {ResourceTypes} = require './schema/CloudFormationResourceSpecification.json' #=============================================================================# # Helper functions. # #=============================================================================# topLevelResourceProperties = [ 'Type' 'Condition' 'CreationPolicy' 'DeletionPolicy' 'DependsOn' 'Metadata' 'UpdatePolicy' 'UpdateReplacePolicy' ] assoc = (xs, k, v) -> xs[k] = v xs conj = (xs, x) -> xs.push(x) xs readFile = (file) -> fs.readFileSync(file).toString('utf-8') typeOf = (thing) -> Object::toString.call(thing)[8...-1] fileExt = (file) -> if (e = split(path.basename(file), '.', 2)[1])? then ".#{e}" merge = (args...) -> Object.assign.apply(null, args) deepMerge = (args...) -> dm = (x, y) -> if not (isObject(x) and isObject(y)) y else ret = Object.assign({}, x) ret[k] = dm(x[k], v) for k, v of y ret args.reduce(((xs, x) -> dm(xs, x)), {}) hashMap = (args...) -> ret = {} ret[args[2*i]] = args[2*i+1] for i in [0...args.length/2] ret isDirectory = (file) -> fs.statSync(file).isDirectory() reduceKv = (map, f) -> Object.keys(map).reduce(((xs, k) -> f(xs, k, map[k])), {}) notEmpty = (map) -> Object.keys(map or {}).length > 0 md5 = (data) -> crypto.createHash("md5").update(data).digest("hex") md5File = (filePath) -> md5(fs.readFileSync(filePath)) md5Dir = (dirPath) -> origDir = process.cwd() try process.chdir(dirPath) add2tree = (tree, path) -> assoc(tree, path, md5Path(path)) md5(JSON.stringify(fs.readdirSync('.').sort().reduce(add2tree, {}))) finally process.chdir(origDir) md5Path = (path) -> (if isDirectory(path) then md5Dir else md5File)(path) peek = (ary) -> ary[ary.length - 1] getIn = (obj, ks) -> ks.reduce(((xs, x) -> xs[x]), obj) split = (str, sep, count=Infinity) -> toks = str.split(sep) n = Math.min(toks.length, count) - 1 toks[0...n].concat(toks[n..].join(sep)) isString = (x) -> typeOf(x) is 'String' isArray = (x) -> typeOf(x) is 'Array' isObject = (x) -> typeOf(x) is 'Object' isBoolean = (x) -> typeOf(x) is 'Boolean' assertObject = (thing) -> assert.ok(typeOf(thing) in [ 'Object' 'Undefined' 'Null' ], "expected an Object, got #{JSON.stringify(thing)}") thing assertArray = (thing) -> assert.ok(isArray(thing), "expected an Array, got #{JSON.stringify(thing)}") thing parseKeyOpt = (opt) -> if (multi = opt.match(/^\[(.*)\]$/)) then multi[1].split(',') else opt parseKeyOpts = (opts) -> opts.reduce(((xs, x) -> [k, v] = x.split('=') v ?= k merge(xs, hashMap(k, parseKeyOpt(v))) ), {}) mergeStrings = (toks, sep = '') -> reducer = (xs, x) -> y = xs.pop() xs.concat(if isString(x) and isString(y) then [[y,x].join(sep)] else [y,x]) toks.reduce(reducer, []).filter((x) -> x? and x isnt '') indexOfClosingCurly = (form) -> depth = 0 for i in [0...form.length] switch form[i] when '{' then depth++ when '}' then return i if not depth-- return -1 interpolateSub = (form) -> ret = [] while true if form.startsWith('${!') ret.push(form[0...3]) form = form[3..] else if form.startsWith('${') i = indexOfClosingCurly(form[2..]) assert.notEqual(i, -1, "no closing curly: #{JSON.stringify(form)}") ret.push({Ref: form[2...i+2]}) form = form[i+3..] else if (i = form.indexOf('${')) is -1 ret.push(form) break else ret.push(form[0...i]) form = form[i..] ret #=============================================================================# # AWS CLOUDFORMATION YAML TRANSFORMER BASE CLASS # #=============================================================================# class CfnTransformer extends YamlTransformer constructor: ({@basedir, @tempdir, @cache, @s3bucket, @s3prefix, @verbose, @linter} = {}) -> super() @cache ?= {} @basedir ?= process.cwd() @tempdir = path.resolve(@tempdir ? fs.mkdtempSync("#{os.tmpdir()}/")) @template = null @resourceMacros = [] @bindstack = [] #=========================================================================# # Redefine and extend built-in CloudFormation macros. # #=========================================================================# @defmacro 'Base64', (form) => form = if isArray(form) then form[0] else form {'Fn::Base64': form} @defmacro 'GetAZs', (form) => form = if isArray(form) then form[0] else form {'Fn::GetAZs': form} @defmacro 'ImportValue', (form) => form = if isArray(form) then form[0] else form {'Fn::ImportValue': form} @defmacro 'GetAtt', (form) => form = if isArray(form) and form.length is 1 then form[0] else form {'Fn::GetAtt': if isString(form) then split(form, '.', 2) else form} @defmacro 'RefAll', (form) => form = if isArray(form) then form[0] else form {'Fn::RefAll': form} @defmacro 'Join', (form) => [sep, toks] = form switch (xs = mergeStrings(toks, sep)).length when 0 then '' when 1 then xs[0] else {'Fn::Join': [sep, xs]} @defmacro 'Condition', 'Condition', (form) => {Condition: if isArray(form) then form[0] else form} @defmacro 'Ref', 'Ref', (form) => form = if isArray(form) then form[0] else form if isString(form) [ref, ks...] = form.split('.') switch when form.startsWith('$') then {'Fn::Env': form[1..]} when form.startsWith('%') then {'Fn::Get': form[1..]} when form.startsWith('@') then {'Fn::Attr': form[1..]} when peek(@bindstack)[ref]? then getIn(peek(@bindstack)[ref], ks) else {Ref: form} else form @defmacro 'Sub', (form) => form = if isArray(form) and form.length is 1 then form[0] else form switch typeOf(form) when 'String' then {'Fn::Join': ['', interpolateSub(form)]} else {'Fn::Sub': form} #=========================================================================# # Define special forms. # #=========================================================================# @defspecial 'Let', (form) => form = if isArray(form) and form.length is 1 then form[0] else form if isArray(form) @withBindings(@walk(form[0]), => @walk(form[1])) else merge(peek(@bindstack), assertObject(@walk(form))) null @defspecial 'Do', (form) => assertArray(form).reduce(((xs, x) => @walk(x)), null) #=========================================================================# # Define custom macros. # #=========================================================================# @defmacro 'Require', (form) => form = [form] unless isArray(form) require(path.resolve(v))(@) for v in form null @defmacro 'Parameters', (form) => Parameters: form.reduce(((xs, param) => [name, opts...] = param.split(/ +/) opts = merge({Type: 'String'}, parseKeyOpts(opts)) merge(xs, hashMap(name, opts)) ), {}) @defmacro 'Return', (form) => Outputs: reduceKv form, (xs, k, v) => [name, opts...] = k.split(/ +/) xport = if notEmpty(opts = parseKeyOpts(opts)) opts.Name = @walk {'Fn::Sub': opts.Name} if opts.Name {Export: opts} merge(xs, hashMap(name, merge({Value: v}, xport))) @defmacro 'Resources', (form) => ret = {} for id, body of form [id, Type, opts...] = id.split(/ +/) id = @walk {'Fn::Sub': id} ret[id] = if not Type if (m = @resourceMacros[body.Type]) then m(body) else body else body = merge({Type}, parseKeyOpts(opts), {Properties: body}) if (m = @resourceMacros[Type]) then m(body) else body Resources: ret @defmacro 'Attr', (form) => form = if isArray(form) then form[0] else form {'Fn::GetAtt': split(form, '.', 2).map((x) => {'Fn::Sub': x})} @defmacro 'Get', (form) => form = if isArray(form) and form.length is 1 then form[0] else form form = form.split('.') if isString(form) {'Fn::FindInMap': form.map((x) => {'Fn::Sub': x})} @defmacro 'Env', (form) => form = if isArray(form) then form[0] else form ret = process.env[form] assert.ok(ret?, "required environment variable not set: #{form}") ret @defmacro 'Var', (form) => form = if isArray(form) then form[0] else form {'Fn::ImportValue': {'Fn::Sub': form}} @defmacro 'Shell', (form) => form = if isArray(form) then form[0] else form key = JSON.stringify {shell: [@template, form]} @cache[key] = (@execShell(form) or '').replace(/\n$/, '') unless @cache[key]? @cache[key] @defmacro 'Package', (form) => form = if isArray(form) then form[0] else form form = {Path: form} if isString(form) {Path, CacheKey, Parse} = form key = JSON.stringify {package: [@userPath(Path), CacheKey, Parse]} if not @cache[key]? @cache[key] = ( if isDirectory(Path) @writeDir(Path, CacheKey) else if Parse @writeTemplate(Path, CacheKey) else @writeFile(Path, CacheKey) ).code @cache[key] @defmacro 'PackageURL', (form) => form = if isArray(form) then form[0] else form @walk 'Fn::Let': [ {'Fn::Package': form} {'Fn::Sub': 'https://s3.amazonaws.com/${S3Bucket}/${S3Key}'} ] @defmacro 'PackageURI', (form) => form = if isArray(form) then form[0] else form @walk 'Fn::Let': [ {'Fn::Package': form} {'Fn::Sub': 's3://${S3Bucket}/${S3Key}'} ] @defmacro 'PackageTemplateURL', (form) => form = if isArray(form) then form[0] else form form = {Path: form} if isString(form) @walk {'Fn::PackageURL': Object.assign({Parse: true}, form)} @defmacro 'YamlParse', (form) => form = if isArray(form) then form[0] else form yaml.safeLoad(form) @defmacro 'YamlDump', (form) => form = if isArray(form) then form[0] else form yaml.safeDump(form) @defmacro 'JsonParse', (form) => form = if isArray(form) then form[0] else form JSON.parse(form) @defmacro 'JsonDump', (form) => form = if isArray(form) then form[0] else form JSON.stringify(form) @defmacro 'File', (form) => form = if isArray(form) then form[0] else form fs.readFileSync(form) @defmacro 'TemplateFile', (form) => form = if isArray(form) then form[0] else form yaml.safeLoad(@transformTemplateFile(form)) @defmacro 'Merge', (form) => merge.apply(null, form) @defmacro 'DeepMerge', (form) => deepMerge.apply(null, form) @defmacro 'Tags', (form) => {Key: k, Value: form[k]} for k in Object.keys(form) @defresource 'Stack', (form) => Type = 'AWS::CloudFormation::Stack' Parameters = {} Properties = {Parameters} stackProps = Object.keys(ResourceTypes[Type].Properties) for k, v of (form.Properties or {}) (if k in stackProps then Properties else Parameters)[k] = v merge(form, {Type, Properties}) abort: (msg...) -> ks = ['$'].concat(@keystack.map((x) -> "[#{x}]")) msg.unshift("at #{ks.join('')}:") msg.unshift("\n in #{@template}:") if @template throw new Error(msg.join(' ')) debug: (msg...) -> console.error.apply(console, msg) if @verbose msg.join(' ') execShell: (command, opts, throwOnNonZeroStatus=true) -> try res = spawnSync(command, merge({stdio: 'pipe', shell: '/bin/bash'}, opts)) throw res if res.status isnt 0 and throwOnNonZeroStatus @debug x if (x = res.stderr?.toString('utf-8')) res.stdout?.toString('utf-8') catch e msg = "shell exec failed: #{command}" err = e.stderr.toString('utf-8') assert.fail(if err? then "#{msg}\n#{err}" else msg) withBindings: (bindings, f) -> @bindstack.push(merge({}, peek(@bindstack), assertObject(bindings))) ret = f() @bindstack.pop() ret canonicalKeyPath: () -> [@template].concat(@keystack) canonicalHash: (fileOrDir, key) -> if key then md5(JSON.stringify([@canonicalKeyPath(),key])) else md5Path(fileOrDir) writePaths: (fileName, ext = '') -> fileName = "#{fileName}#{ext}" tmpPath: @tmpPath(fileName), code: { S3Bucket: @s3bucket, S3Key: "#{@s3prefix}#{fileName}" } writeText: (text, ext, key) -> ret = @writePaths(md5(key or text), ext) fs.writeFileSync(ret.tmpPath, text) ret transformTemplateFile: (file) -> xformer = new @.constructor({@basedir, @tempdir, @cache, @s3bucket, @s3prefix, @verbose, @linter}) xformer.transformFile(file) writeTemplate: (file, key) -> ret = @writeText(@transformTemplateFile(file), fileExt(file), key) if @linter try console.log("LINTING: #{@userPath(file)}...") lint = (@execShell("#{@linter} #{ret.tmpPath}", null, false) or '').trimRight() console.log(lint) if lint catch e console.error(e.message) ret writeFile: (file, key) -> ret = @writePaths(@canonicalHash(file, key), fileExt(file)) fs.copyFileSync(file, ret.tmpPath) ret writeDir: (dir, key) -> tmpZip = @tmpPath("#{encodeURIComponent(@userPath(dir))}.zip") @debug "packg: #{dir}" @execShell("zip -r #{tmpZip} .", {cwd: dir}) ret = @writePaths(@canonicalHash(dir, key), '.zip') fs.renameSync(tmpZip, ret.tmpPath) ret userPath: (file) -> path.relative(@basedir, file) tmpPath: (name) -> path.join(@tempdir, name) pushFile: (file, f) -> tpl = @template dir = process.cwd() @template = @userPath(file) @debug "xform: #{@template}" process.chdir(path.dirname(file)) ret = f(path.basename(file)) process.chdir(dir) @template = tpl ret pushFileCaching: (file, f) -> key = JSON.stringify {pushFileCaching: @userPath(file)} @cache[key] = @pushFile(file, f) unless @cache[key] @cache[key] defresource: (type, emit) -> @resourceMacros[type] = emit @ transform: (text) -> @bindstack = [{}] super(text) transformFile: (templateFile, doc) -> @pushFileCaching templateFile, (file) => @transform(doc or fs.readFileSync(file).toString('utf-8')) module.exports = CfnTransformer
63106
yaml = require 'js-yaml' fs = require 'fs' os = require 'os' path = require 'path' assert = require 'assert' crypto = require 'crypto' {spawnSync} = require 'child_process' YamlTransformer = require './yaml-transformer' {ResourceTypes} = require './schema/CloudFormationResourceSpecification.json' #=============================================================================# # Helper functions. # #=============================================================================# topLevelResourceProperties = [ 'Type' 'Condition' 'CreationPolicy' 'DeletionPolicy' 'DependsOn' 'Metadata' 'UpdatePolicy' 'UpdateReplacePolicy' ] assoc = (xs, k, v) -> xs[k] = v xs conj = (xs, x) -> xs.push(x) xs readFile = (file) -> fs.readFileSync(file).toString('utf-8') typeOf = (thing) -> Object::toString.call(thing)[8...-1] fileExt = (file) -> if (e = split(path.basename(file), '.', 2)[1])? then ".#{e}" merge = (args...) -> Object.assign.apply(null, args) deepMerge = (args...) -> dm = (x, y) -> if not (isObject(x) and isObject(y)) y else ret = Object.assign({}, x) ret[k] = dm(x[k], v) for k, v of y ret args.reduce(((xs, x) -> dm(xs, x)), {}) hashMap = (args...) -> ret = {} ret[args[2*i]] = args[2*i+1] for i in [0...args.length/2] ret isDirectory = (file) -> fs.statSync(file).isDirectory() reduceKv = (map, f) -> Object.keys(map).reduce(((xs, k) -> f(xs, k, map[k])), {}) notEmpty = (map) -> Object.keys(map or {}).length > 0 md5 = (data) -> crypto.createHash("md5").update(data).digest("hex") md5File = (filePath) -> md5(fs.readFileSync(filePath)) md5Dir = (dirPath) -> origDir = process.cwd() try process.chdir(dirPath) add2tree = (tree, path) -> assoc(tree, path, md5Path(path)) md5(JSON.stringify(fs.readdirSync('.').sort().reduce(add2tree, {}))) finally process.chdir(origDir) md5Path = (path) -> (if isDirectory(path) then md5Dir else md5File)(path) peek = (ary) -> ary[ary.length - 1] getIn = (obj, ks) -> ks.reduce(((xs, x) -> xs[x]), obj) split = (str, sep, count=Infinity) -> toks = str.split(sep) n = Math.min(toks.length, count) - 1 toks[0...n].concat(toks[n..].join(sep)) isString = (x) -> typeOf(x) is 'String' isArray = (x) -> typeOf(x) is 'Array' isObject = (x) -> typeOf(x) is 'Object' isBoolean = (x) -> typeOf(x) is 'Boolean' assertObject = (thing) -> assert.ok(typeOf(thing) in [ 'Object' 'Undefined' 'Null' ], "expected an Object, got #{JSON.stringify(thing)}") thing assertArray = (thing) -> assert.ok(isArray(thing), "expected an Array, got #{JSON.stringify(thing)}") thing parseKeyOpt = (opt) -> if (multi = opt.match(/^\[(.*)\]$/)) then multi[1].split(',') else opt parseKeyOpts = (opts) -> opts.reduce(((xs, x) -> [k, v] = x.split('=') v ?= k merge(xs, hashMap(k, parseKeyOpt(v))) ), {}) mergeStrings = (toks, sep = '') -> reducer = (xs, x) -> y = xs.pop() xs.concat(if isString(x) and isString(y) then [[y,x].join(sep)] else [y,x]) toks.reduce(reducer, []).filter((x) -> x? and x isnt '') indexOfClosingCurly = (form) -> depth = 0 for i in [0...form.length] switch form[i] when '{' then depth++ when '}' then return i if not depth-- return -1 interpolateSub = (form) -> ret = [] while true if form.startsWith('${!') ret.push(form[0...3]) form = form[3..] else if form.startsWith('${') i = indexOfClosingCurly(form[2..]) assert.notEqual(i, -1, "no closing curly: #{JSON.stringify(form)}") ret.push({Ref: form[2...i+2]}) form = form[i+3..] else if (i = form.indexOf('${')) is -1 ret.push(form) break else ret.push(form[0...i]) form = form[i..] ret #=============================================================================# # AWS CLOUDFORMATION YAML TRANSFORMER BASE CLASS # #=============================================================================# class CfnTransformer extends YamlTransformer constructor: ({@basedir, @tempdir, @cache, @s3bucket, @s3prefix, @verbose, @linter} = {}) -> super() @cache ?= {} @basedir ?= process.cwd() @tempdir = path.resolve(@tempdir ? fs.mkdtempSync("#{os.tmpdir()}/")) @template = null @resourceMacros = [] @bindstack = [] #=========================================================================# # Redefine and extend built-in CloudFormation macros. # #=========================================================================# @defmacro 'Base64', (form) => form = if isArray(form) then form[0] else form {'Fn::Base64': form} @defmacro 'GetAZs', (form) => form = if isArray(form) then form[0] else form {'Fn::GetAZs': form} @defmacro 'ImportValue', (form) => form = if isArray(form) then form[0] else form {'Fn::ImportValue': form} @defmacro 'GetAtt', (form) => form = if isArray(form) and form.length is 1 then form[0] else form {'Fn::GetAtt': if isString(form) then split(form, '.', 2) else form} @defmacro 'RefAll', (form) => form = if isArray(form) then form[0] else form {'Fn::RefAll': form} @defmacro 'Join', (form) => [sep, toks] = form switch (xs = mergeStrings(toks, sep)).length when 0 then '' when 1 then xs[0] else {'Fn::Join': [sep, xs]} @defmacro 'Condition', 'Condition', (form) => {Condition: if isArray(form) then form[0] else form} @defmacro 'Ref', 'Ref', (form) => form = if isArray(form) then form[0] else form if isString(form) [ref, ks...] = form.split('.') switch when form.startsWith('$') then {'Fn::Env': form[1..]} when form.startsWith('%') then {'Fn::Get': form[1..]} when form.startsWith('@') then {'Fn::Attr': form[1..]} when peek(@bindstack)[ref]? then getIn(peek(@bindstack)[ref], ks) else {Ref: form} else form @defmacro 'Sub', (form) => form = if isArray(form) and form.length is 1 then form[0] else form switch typeOf(form) when 'String' then {'Fn::Join': ['', interpolateSub(form)]} else {'Fn::Sub': form} #=========================================================================# # Define special forms. # #=========================================================================# @defspecial 'Let', (form) => form = if isArray(form) and form.length is 1 then form[0] else form if isArray(form) @withBindings(@walk(form[0]), => @walk(form[1])) else merge(peek(@bindstack), assertObject(@walk(form))) null @defspecial 'Do', (form) => assertArray(form).reduce(((xs, x) => @walk(x)), null) #=========================================================================# # Define custom macros. # #=========================================================================# @defmacro 'Require', (form) => form = [form] unless isArray(form) require(path.resolve(v))(@) for v in form null @defmacro 'Parameters', (form) => Parameters: form.reduce(((xs, param) => [name, opts...] = param.split(/ +/) opts = merge({Type: 'String'}, parseKeyOpts(opts)) merge(xs, hashMap(name, opts)) ), {}) @defmacro 'Return', (form) => Outputs: reduceKv form, (xs, k, v) => [name, opts...] = k.split(/ +/) xport = if notEmpty(opts = parseKeyOpts(opts)) opts.Name = @walk {'Fn::Sub': opts.Name} if opts.Name {Export: opts} merge(xs, hashMap(name, merge({Value: v}, xport))) @defmacro 'Resources', (form) => ret = {} for id, body of form [id, Type, opts...] = id.split(/ +/) id = @walk {'Fn::Sub': id} ret[id] = if not Type if (m = @resourceMacros[body.Type]) then m(body) else body else body = merge({Type}, parseKeyOpts(opts), {Properties: body}) if (m = @resourceMacros[Type]) then m(body) else body Resources: ret @defmacro 'Attr', (form) => form = if isArray(form) then form[0] else form {'Fn::GetAtt': split(form, '.', 2).map((x) => {'Fn::Sub': x})} @defmacro 'Get', (form) => form = if isArray(form) and form.length is 1 then form[0] else form form = form.split('.') if isString(form) {'Fn::FindInMap': form.map((x) => {'Fn::Sub': x})} @defmacro 'Env', (form) => form = if isArray(form) then form[0] else form ret = process.env[form] assert.ok(ret?, "required environment variable not set: #{form}") ret @defmacro 'Var', (form) => form = if isArray(form) then form[0] else form {'Fn::ImportValue': {'Fn::Sub': form}} @defmacro 'Shell', (form) => form = if isArray(form) then form[0] else form key = JSON.stringify {shell: [@template, form]} @cache[key] = (@execShell(form) or '').replace(/\n$/, '') unless @cache[key]? @cache[key] @defmacro 'Package', (form) => form = if isArray(form) then form[0] else form form = {Path: form} if isString(form) {Path, CacheKey, Parse} = form key = JSON.stringify {package: [@userPath(Path), CacheKey, Parse]} if not @cache[key]? @cache[key] = ( if isDirectory(Path) @writeDir(Path, CacheKey) else if Parse @writeTemplate(Path, CacheKey) else @writeFile(Path, CacheKey) ).code @cache[key] @defmacro 'PackageURL', (form) => form = if isArray(form) then form[0] else form @walk 'Fn::Let': [ {'Fn::Package': form} {'Fn::Sub': 'https://s3.amazonaws.com/${S3Bucket}/${S3Key}'} ] @defmacro 'PackageURI', (form) => form = if isArray(form) then form[0] else form @walk 'Fn::Let': [ {'Fn::Package': form} {'Fn::Sub': 's3://${S3Bucket}/${S3Key}'} ] @defmacro 'PackageTemplateURL', (form) => form = if isArray(form) then form[0] else form form = {Path: form} if isString(form) @walk {'Fn::PackageURL': Object.assign({Parse: true}, form)} @defmacro 'YamlParse', (form) => form = if isArray(form) then form[0] else form yaml.safeLoad(form) @defmacro 'YamlDump', (form) => form = if isArray(form) then form[0] else form yaml.safeDump(form) @defmacro 'JsonParse', (form) => form = if isArray(form) then form[0] else form JSON.parse(form) @defmacro 'JsonDump', (form) => form = if isArray(form) then form[0] else form JSON.stringify(form) @defmacro 'File', (form) => form = if isArray(form) then form[0] else form fs.readFileSync(form) @defmacro 'TemplateFile', (form) => form = if isArray(form) then form[0] else form yaml.safeLoad(@transformTemplateFile(form)) @defmacro 'Merge', (form) => merge.apply(null, form) @defmacro 'DeepMerge', (form) => deepMerge.apply(null, form) @defmacro 'Tags', (form) => {Key: k, Value: form[k]} for k in Object.keys(form) @defresource 'Stack', (form) => Type = 'AWS::CloudFormation::Stack' Parameters = {} Properties = {Parameters} stackProps = Object.keys(ResourceTypes[Type].Properties) for k, v of (form.Properties or {}) (if k in stackProps then Properties else Parameters)[k] = v merge(form, {Type, Properties}) abort: (msg...) -> ks = ['$'].concat(@keystack.map((x) -> "[#{x}]")) msg.unshift("at #{ks.join('')}:") msg.unshift("\n in #{@template}:") if @template throw new Error(msg.join(' ')) debug: (msg...) -> console.error.apply(console, msg) if @verbose msg.join(' ') execShell: (command, opts, throwOnNonZeroStatus=true) -> try res = spawnSync(command, merge({stdio: 'pipe', shell: '/bin/bash'}, opts)) throw res if res.status isnt 0 and throwOnNonZeroStatus @debug x if (x = res.stderr?.toString('utf-8')) res.stdout?.toString('utf-8') catch e msg = "shell exec failed: #{command}" err = e.stderr.toString('utf-8') assert.fail(if err? then "#{msg}\n#{err}" else msg) withBindings: (bindings, f) -> @bindstack.push(merge({}, peek(@bindstack), assertObject(bindings))) ret = f() @bindstack.pop() ret canonicalKeyPath: () -> [@template].concat(@keystack) canonicalHash: (fileOrDir, key) -> if key then md5(JSON.stringify([@canonicalKeyPath(),key])) else md5Path(fileOrDir) writePaths: (fileName, ext = '') -> fileName = "#{fileName}#{ext}" tmpPath: @tmpPath(fileName), code: { S3Bucket: @s3bucket, S3Key: "#{@s3prefix}#{fileName}" } writeText: (text, ext, key) -> ret = @writePaths(md5(key or text), ext) fs.writeFileSync(ret.tmpPath, text) ret transformTemplateFile: (file) -> xformer = new @.constructor({@basedir, @tempdir, @cache, @s3bucket, @s3prefix, @verbose, @linter}) xformer.transformFile(file) writeTemplate: (file, key) -> ret = @writeText(@transformTemplateFile(file), fileExt(file), key) if @linter try console.log("LINTING: #{@userPath(file)}...") lint = (@execShell("#{@linter} #{ret.tmpPath}", null, false) or '').trimRight() console.log(lint) if lint catch e console.error(e.message) ret writeFile: (file, key) -> ret = @writePaths(@canonicalHash(file, key), fileExt(file)) fs.copyFileSync(file, ret.tmpPath) ret writeDir: (dir, key) -> tmpZip = @tmpPath("#{encodeURIComponent(@userPath(dir))}.zip") @debug "packg: #{dir}" @execShell("zip -r #{tmpZip} .", {cwd: dir}) ret = @writePaths(@canonicalHash(dir, key), '.zip') fs.renameSync(tmpZip, ret.tmpPath) ret userPath: (file) -> path.relative(@basedir, file) tmpPath: (name) -> path.join(@tempdir, name) pushFile: (file, f) -> tpl = @template dir = process.cwd() @template = @userPath(file) @debug "xform: #{@template}" process.chdir(path.dirname(file)) ret = f(path.basename(file)) process.chdir(dir) @template = tpl ret pushFileCaching: (file, f) -> key = <KEY>.<KEY> {pushFileCaching: @userPath(file)} @cache[key] = @pushFile(file, f) unless @cache[key] @cache[key] defresource: (type, emit) -> @resourceMacros[type] = emit @ transform: (text) -> @bindstack = [{}] super(text) transformFile: (templateFile, doc) -> @pushFileCaching templateFile, (file) => @transform(doc or fs.readFileSync(file).toString('utf-8')) module.exports = CfnTransformer
true
yaml = require 'js-yaml' fs = require 'fs' os = require 'os' path = require 'path' assert = require 'assert' crypto = require 'crypto' {spawnSync} = require 'child_process' YamlTransformer = require './yaml-transformer' {ResourceTypes} = require './schema/CloudFormationResourceSpecification.json' #=============================================================================# # Helper functions. # #=============================================================================# topLevelResourceProperties = [ 'Type' 'Condition' 'CreationPolicy' 'DeletionPolicy' 'DependsOn' 'Metadata' 'UpdatePolicy' 'UpdateReplacePolicy' ] assoc = (xs, k, v) -> xs[k] = v xs conj = (xs, x) -> xs.push(x) xs readFile = (file) -> fs.readFileSync(file).toString('utf-8') typeOf = (thing) -> Object::toString.call(thing)[8...-1] fileExt = (file) -> if (e = split(path.basename(file), '.', 2)[1])? then ".#{e}" merge = (args...) -> Object.assign.apply(null, args) deepMerge = (args...) -> dm = (x, y) -> if not (isObject(x) and isObject(y)) y else ret = Object.assign({}, x) ret[k] = dm(x[k], v) for k, v of y ret args.reduce(((xs, x) -> dm(xs, x)), {}) hashMap = (args...) -> ret = {} ret[args[2*i]] = args[2*i+1] for i in [0...args.length/2] ret isDirectory = (file) -> fs.statSync(file).isDirectory() reduceKv = (map, f) -> Object.keys(map).reduce(((xs, k) -> f(xs, k, map[k])), {}) notEmpty = (map) -> Object.keys(map or {}).length > 0 md5 = (data) -> crypto.createHash("md5").update(data).digest("hex") md5File = (filePath) -> md5(fs.readFileSync(filePath)) md5Dir = (dirPath) -> origDir = process.cwd() try process.chdir(dirPath) add2tree = (tree, path) -> assoc(tree, path, md5Path(path)) md5(JSON.stringify(fs.readdirSync('.').sort().reduce(add2tree, {}))) finally process.chdir(origDir) md5Path = (path) -> (if isDirectory(path) then md5Dir else md5File)(path) peek = (ary) -> ary[ary.length - 1] getIn = (obj, ks) -> ks.reduce(((xs, x) -> xs[x]), obj) split = (str, sep, count=Infinity) -> toks = str.split(sep) n = Math.min(toks.length, count) - 1 toks[0...n].concat(toks[n..].join(sep)) isString = (x) -> typeOf(x) is 'String' isArray = (x) -> typeOf(x) is 'Array' isObject = (x) -> typeOf(x) is 'Object' isBoolean = (x) -> typeOf(x) is 'Boolean' assertObject = (thing) -> assert.ok(typeOf(thing) in [ 'Object' 'Undefined' 'Null' ], "expected an Object, got #{JSON.stringify(thing)}") thing assertArray = (thing) -> assert.ok(isArray(thing), "expected an Array, got #{JSON.stringify(thing)}") thing parseKeyOpt = (opt) -> if (multi = opt.match(/^\[(.*)\]$/)) then multi[1].split(',') else opt parseKeyOpts = (opts) -> opts.reduce(((xs, x) -> [k, v] = x.split('=') v ?= k merge(xs, hashMap(k, parseKeyOpt(v))) ), {}) mergeStrings = (toks, sep = '') -> reducer = (xs, x) -> y = xs.pop() xs.concat(if isString(x) and isString(y) then [[y,x].join(sep)] else [y,x]) toks.reduce(reducer, []).filter((x) -> x? and x isnt '') indexOfClosingCurly = (form) -> depth = 0 for i in [0...form.length] switch form[i] when '{' then depth++ when '}' then return i if not depth-- return -1 interpolateSub = (form) -> ret = [] while true if form.startsWith('${!') ret.push(form[0...3]) form = form[3..] else if form.startsWith('${') i = indexOfClosingCurly(form[2..]) assert.notEqual(i, -1, "no closing curly: #{JSON.stringify(form)}") ret.push({Ref: form[2...i+2]}) form = form[i+3..] else if (i = form.indexOf('${')) is -1 ret.push(form) break else ret.push(form[0...i]) form = form[i..] ret #=============================================================================# # AWS CLOUDFORMATION YAML TRANSFORMER BASE CLASS # #=============================================================================# class CfnTransformer extends YamlTransformer constructor: ({@basedir, @tempdir, @cache, @s3bucket, @s3prefix, @verbose, @linter} = {}) -> super() @cache ?= {} @basedir ?= process.cwd() @tempdir = path.resolve(@tempdir ? fs.mkdtempSync("#{os.tmpdir()}/")) @template = null @resourceMacros = [] @bindstack = [] #=========================================================================# # Redefine and extend built-in CloudFormation macros. # #=========================================================================# @defmacro 'Base64', (form) => form = if isArray(form) then form[0] else form {'Fn::Base64': form} @defmacro 'GetAZs', (form) => form = if isArray(form) then form[0] else form {'Fn::GetAZs': form} @defmacro 'ImportValue', (form) => form = if isArray(form) then form[0] else form {'Fn::ImportValue': form} @defmacro 'GetAtt', (form) => form = if isArray(form) and form.length is 1 then form[0] else form {'Fn::GetAtt': if isString(form) then split(form, '.', 2) else form} @defmacro 'RefAll', (form) => form = if isArray(form) then form[0] else form {'Fn::RefAll': form} @defmacro 'Join', (form) => [sep, toks] = form switch (xs = mergeStrings(toks, sep)).length when 0 then '' when 1 then xs[0] else {'Fn::Join': [sep, xs]} @defmacro 'Condition', 'Condition', (form) => {Condition: if isArray(form) then form[0] else form} @defmacro 'Ref', 'Ref', (form) => form = if isArray(form) then form[0] else form if isString(form) [ref, ks...] = form.split('.') switch when form.startsWith('$') then {'Fn::Env': form[1..]} when form.startsWith('%') then {'Fn::Get': form[1..]} when form.startsWith('@') then {'Fn::Attr': form[1..]} when peek(@bindstack)[ref]? then getIn(peek(@bindstack)[ref], ks) else {Ref: form} else form @defmacro 'Sub', (form) => form = if isArray(form) and form.length is 1 then form[0] else form switch typeOf(form) when 'String' then {'Fn::Join': ['', interpolateSub(form)]} else {'Fn::Sub': form} #=========================================================================# # Define special forms. # #=========================================================================# @defspecial 'Let', (form) => form = if isArray(form) and form.length is 1 then form[0] else form if isArray(form) @withBindings(@walk(form[0]), => @walk(form[1])) else merge(peek(@bindstack), assertObject(@walk(form))) null @defspecial 'Do', (form) => assertArray(form).reduce(((xs, x) => @walk(x)), null) #=========================================================================# # Define custom macros. # #=========================================================================# @defmacro 'Require', (form) => form = [form] unless isArray(form) require(path.resolve(v))(@) for v in form null @defmacro 'Parameters', (form) => Parameters: form.reduce(((xs, param) => [name, opts...] = param.split(/ +/) opts = merge({Type: 'String'}, parseKeyOpts(opts)) merge(xs, hashMap(name, opts)) ), {}) @defmacro 'Return', (form) => Outputs: reduceKv form, (xs, k, v) => [name, opts...] = k.split(/ +/) xport = if notEmpty(opts = parseKeyOpts(opts)) opts.Name = @walk {'Fn::Sub': opts.Name} if opts.Name {Export: opts} merge(xs, hashMap(name, merge({Value: v}, xport))) @defmacro 'Resources', (form) => ret = {} for id, body of form [id, Type, opts...] = id.split(/ +/) id = @walk {'Fn::Sub': id} ret[id] = if not Type if (m = @resourceMacros[body.Type]) then m(body) else body else body = merge({Type}, parseKeyOpts(opts), {Properties: body}) if (m = @resourceMacros[Type]) then m(body) else body Resources: ret @defmacro 'Attr', (form) => form = if isArray(form) then form[0] else form {'Fn::GetAtt': split(form, '.', 2).map((x) => {'Fn::Sub': x})} @defmacro 'Get', (form) => form = if isArray(form) and form.length is 1 then form[0] else form form = form.split('.') if isString(form) {'Fn::FindInMap': form.map((x) => {'Fn::Sub': x})} @defmacro 'Env', (form) => form = if isArray(form) then form[0] else form ret = process.env[form] assert.ok(ret?, "required environment variable not set: #{form}") ret @defmacro 'Var', (form) => form = if isArray(form) then form[0] else form {'Fn::ImportValue': {'Fn::Sub': form}} @defmacro 'Shell', (form) => form = if isArray(form) then form[0] else form key = JSON.stringify {shell: [@template, form]} @cache[key] = (@execShell(form) or '').replace(/\n$/, '') unless @cache[key]? @cache[key] @defmacro 'Package', (form) => form = if isArray(form) then form[0] else form form = {Path: form} if isString(form) {Path, CacheKey, Parse} = form key = JSON.stringify {package: [@userPath(Path), CacheKey, Parse]} if not @cache[key]? @cache[key] = ( if isDirectory(Path) @writeDir(Path, CacheKey) else if Parse @writeTemplate(Path, CacheKey) else @writeFile(Path, CacheKey) ).code @cache[key] @defmacro 'PackageURL', (form) => form = if isArray(form) then form[0] else form @walk 'Fn::Let': [ {'Fn::Package': form} {'Fn::Sub': 'https://s3.amazonaws.com/${S3Bucket}/${S3Key}'} ] @defmacro 'PackageURI', (form) => form = if isArray(form) then form[0] else form @walk 'Fn::Let': [ {'Fn::Package': form} {'Fn::Sub': 's3://${S3Bucket}/${S3Key}'} ] @defmacro 'PackageTemplateURL', (form) => form = if isArray(form) then form[0] else form form = {Path: form} if isString(form) @walk {'Fn::PackageURL': Object.assign({Parse: true}, form)} @defmacro 'YamlParse', (form) => form = if isArray(form) then form[0] else form yaml.safeLoad(form) @defmacro 'YamlDump', (form) => form = if isArray(form) then form[0] else form yaml.safeDump(form) @defmacro 'JsonParse', (form) => form = if isArray(form) then form[0] else form JSON.parse(form) @defmacro 'JsonDump', (form) => form = if isArray(form) then form[0] else form JSON.stringify(form) @defmacro 'File', (form) => form = if isArray(form) then form[0] else form fs.readFileSync(form) @defmacro 'TemplateFile', (form) => form = if isArray(form) then form[0] else form yaml.safeLoad(@transformTemplateFile(form)) @defmacro 'Merge', (form) => merge.apply(null, form) @defmacro 'DeepMerge', (form) => deepMerge.apply(null, form) @defmacro 'Tags', (form) => {Key: k, Value: form[k]} for k in Object.keys(form) @defresource 'Stack', (form) => Type = 'AWS::CloudFormation::Stack' Parameters = {} Properties = {Parameters} stackProps = Object.keys(ResourceTypes[Type].Properties) for k, v of (form.Properties or {}) (if k in stackProps then Properties else Parameters)[k] = v merge(form, {Type, Properties}) abort: (msg...) -> ks = ['$'].concat(@keystack.map((x) -> "[#{x}]")) msg.unshift("at #{ks.join('')}:") msg.unshift("\n in #{@template}:") if @template throw new Error(msg.join(' ')) debug: (msg...) -> console.error.apply(console, msg) if @verbose msg.join(' ') execShell: (command, opts, throwOnNonZeroStatus=true) -> try res = spawnSync(command, merge({stdio: 'pipe', shell: '/bin/bash'}, opts)) throw res if res.status isnt 0 and throwOnNonZeroStatus @debug x if (x = res.stderr?.toString('utf-8')) res.stdout?.toString('utf-8') catch e msg = "shell exec failed: #{command}" err = e.stderr.toString('utf-8') assert.fail(if err? then "#{msg}\n#{err}" else msg) withBindings: (bindings, f) -> @bindstack.push(merge({}, peek(@bindstack), assertObject(bindings))) ret = f() @bindstack.pop() ret canonicalKeyPath: () -> [@template].concat(@keystack) canonicalHash: (fileOrDir, key) -> if key then md5(JSON.stringify([@canonicalKeyPath(),key])) else md5Path(fileOrDir) writePaths: (fileName, ext = '') -> fileName = "#{fileName}#{ext}" tmpPath: @tmpPath(fileName), code: { S3Bucket: @s3bucket, S3Key: "#{@s3prefix}#{fileName}" } writeText: (text, ext, key) -> ret = @writePaths(md5(key or text), ext) fs.writeFileSync(ret.tmpPath, text) ret transformTemplateFile: (file) -> xformer = new @.constructor({@basedir, @tempdir, @cache, @s3bucket, @s3prefix, @verbose, @linter}) xformer.transformFile(file) writeTemplate: (file, key) -> ret = @writeText(@transformTemplateFile(file), fileExt(file), key) if @linter try console.log("LINTING: #{@userPath(file)}...") lint = (@execShell("#{@linter} #{ret.tmpPath}", null, false) or '').trimRight() console.log(lint) if lint catch e console.error(e.message) ret writeFile: (file, key) -> ret = @writePaths(@canonicalHash(file, key), fileExt(file)) fs.copyFileSync(file, ret.tmpPath) ret writeDir: (dir, key) -> tmpZip = @tmpPath("#{encodeURIComponent(@userPath(dir))}.zip") @debug "packg: #{dir}" @execShell("zip -r #{tmpZip} .", {cwd: dir}) ret = @writePaths(@canonicalHash(dir, key), '.zip') fs.renameSync(tmpZip, ret.tmpPath) ret userPath: (file) -> path.relative(@basedir, file) tmpPath: (name) -> path.join(@tempdir, name) pushFile: (file, f) -> tpl = @template dir = process.cwd() @template = @userPath(file) @debug "xform: #{@template}" process.chdir(path.dirname(file)) ret = f(path.basename(file)) process.chdir(dir) @template = tpl ret pushFileCaching: (file, f) -> key = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI {pushFileCaching: @userPath(file)} @cache[key] = @pushFile(file, f) unless @cache[key] @cache[key] defresource: (type, emit) -> @resourceMacros[type] = emit @ transform: (text) -> @bindstack = [{}] super(text) transformFile: (templateFile, doc) -> @pushFileCaching templateFile, (file) => @transform(doc or fs.readFileSync(file).toString('utf-8')) module.exports = CfnTransformer
[ { "context": "g = P \"00000000000000000000000000000000\"\nkey = P \"00000000000000000000000000000000\"\n\ntf = CryptoJS.algo.TwoFish.create 0, key, {}\nco", "end": 198, "score": 0.9991270899772644, "start": 166, "tag": "KEY", "value": "00000000000000000000000000000000" } ]
dev/twofish.iced
CyberFlameGO/triplesec
274
{CryptoJS} = require 'cryptojs-2fish' {TwoFish} = require '../lib/twofish' P = (x) -> CryptoJS.enc.Hex.parse x msg = P "00000000000000000000000000000000" key = P "00000000000000000000000000000000" tf = CryptoJS.algo.TwoFish.create 0, key, {} console.log msg tf.encryptBlock msg.words, 0 console.log msg console.log msg.toString() tf.decryptBlock msg.words, 0 console.log msg tf2 = new TwoFish key tf2.encryptBlock msg.words, 0 console.log msg console.log msg.toString() tf.decryptBlock msg.words, 0 console.log msg
74640
{CryptoJS} = require 'cryptojs-2fish' {TwoFish} = require '../lib/twofish' P = (x) -> CryptoJS.enc.Hex.parse x msg = P "00000000000000000000000000000000" key = P "<KEY>" tf = CryptoJS.algo.TwoFish.create 0, key, {} console.log msg tf.encryptBlock msg.words, 0 console.log msg console.log msg.toString() tf.decryptBlock msg.words, 0 console.log msg tf2 = new TwoFish key tf2.encryptBlock msg.words, 0 console.log msg console.log msg.toString() tf.decryptBlock msg.words, 0 console.log msg
true
{CryptoJS} = require 'cryptojs-2fish' {TwoFish} = require '../lib/twofish' P = (x) -> CryptoJS.enc.Hex.parse x msg = P "00000000000000000000000000000000" key = P "PI:KEY:<KEY>END_PI" tf = CryptoJS.algo.TwoFish.create 0, key, {} console.log msg tf.encryptBlock msg.words, 0 console.log msg console.log msg.toString() tf.decryptBlock msg.words, 0 console.log msg tf2 = new TwoFish key tf2.encryptBlock msg.words, 0 console.log msg console.log msg.toString() tf.decryptBlock msg.words, 0 console.log msg
[ { "context": "Tinysou = require 'tinysou'\n\nTOKEN = 'YOUR_TOKEN'\n\nengine = {\n name: 'YOUR-blog',\n display_name:", "end": 48, "score": 0.8931726813316345, "start": 38, "tag": "KEY", "value": "YOUR_TOKEN" }, { "context": "le: 'My First Post',\n tags: ['news'],\n author: 'Author',\n date: new Date().getTime(),\n body: 'Tinysou ", "end": 335, "score": 0.6576575636863708, "start": 329, "tag": "USERNAME", "value": "Author" } ]
examples/demo.coffee
tinysou/tinysou-node
3
Tinysou = require 'tinysou' TOKEN = 'YOUR_TOKEN' engine = { name: 'YOUR-blog', display_name: 'Blog' } collection = { name: 'posts', field_types: { title: 'string', tags: 'string', author: 'enum', date: 'date', body: 'text' } } document = { title: 'My First Post', tags: ['news'], author: 'Author', date: new Date().getTime(), body: 'Tinysou start online today!' } tinysou = new Tinysou TOKEN searchInfo = { q: 'tinysou' c: 'posts' page: 0, per_parge: 10, sort:{ field: "date", order: "asc", mode: "avg" } } autocompleteInfo = { q: 'fir', c: 'posts' sort:{ field: "date", order: "asc", mode: "avg" } } display = (msg, err, res) -> console.log(msg) if err console.log(err) else console.log(res) tasks = { listEngines: -> tinysou.engines.list (err, res) -> display('List engines', err, res) createEngine: -> tinysou.engines.create engine, (err, res) -> display('Create an engine', err, res) getEngine: -> tinysou.engines.get engine.name, (err, res) -> display('Get an engine', err, res) updateEngine: -> tinysou.engines.update engine.name, engine, (err, res) -> display('Update an engine', err, res) deleteEngine: -> tinysou.engines.delete engine.name, (err, res) -> display('Delete an engine', err, res) listCollections: -> tinysou.collections.list engine.name, (err, res) -> display("List collections in #{engine.name}", err, res) createCollection: -> tinysou.collections.create engine.name, collection, (err, res) -> display('Create a collection', err, res) getCollection: -> tinysou.collections.get engine.name, collection.name, (err, res) -> display('Get a collection', err, res) deleteCollection: -> tinysou.collections.delete engine.name, collection.name, (err, res) -> display('Delete a collection', err, res) listDocuments: -> tinysou.documents.list engine.name, collection.name, (err, res) -> display("List documents in #{collection.name}", err, res) createDocument: -> tinysou.documents.create engine.name, collection.name, document, (err, res) -> display('Create a document', err, res) getDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.get engine.name, collection.name, document_id, (err, res) -> display('Get a document', err, res) else console.log('Please create a document first') updateDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.update engine.name, collection.name, document_id, document, (err, res) -> display('Update a document', err, res) else console.log('Please create a document first') deleteDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.delete engine.name, collection.name, document_id, (err, res) -> display('Delete a document', err, res) else console.log('Please create a document first') search: -> tinysou.search engine.name, searchInfo, (err, res) -> display('Search in many collections', err, res) autocomplete: -> tinysou.autocomplete engine.name, autocompleteInfo, (err, res) -> display("autocomplete in many collections", err, res) } args = process.argv if args.length == 3 and args[2] of tasks tasks[args[2]]() else console.log('Available arguments are:') console.log(k) for k of tasks
163422
Tinysou = require 'tinysou' TOKEN = '<KEY>' engine = { name: 'YOUR-blog', display_name: 'Blog' } collection = { name: 'posts', field_types: { title: 'string', tags: 'string', author: 'enum', date: 'date', body: 'text' } } document = { title: 'My First Post', tags: ['news'], author: 'Author', date: new Date().getTime(), body: 'Tinysou start online today!' } tinysou = new Tinysou TOKEN searchInfo = { q: 'tinysou' c: 'posts' page: 0, per_parge: 10, sort:{ field: "date", order: "asc", mode: "avg" } } autocompleteInfo = { q: 'fir', c: 'posts' sort:{ field: "date", order: "asc", mode: "avg" } } display = (msg, err, res) -> console.log(msg) if err console.log(err) else console.log(res) tasks = { listEngines: -> tinysou.engines.list (err, res) -> display('List engines', err, res) createEngine: -> tinysou.engines.create engine, (err, res) -> display('Create an engine', err, res) getEngine: -> tinysou.engines.get engine.name, (err, res) -> display('Get an engine', err, res) updateEngine: -> tinysou.engines.update engine.name, engine, (err, res) -> display('Update an engine', err, res) deleteEngine: -> tinysou.engines.delete engine.name, (err, res) -> display('Delete an engine', err, res) listCollections: -> tinysou.collections.list engine.name, (err, res) -> display("List collections in #{engine.name}", err, res) createCollection: -> tinysou.collections.create engine.name, collection, (err, res) -> display('Create a collection', err, res) getCollection: -> tinysou.collections.get engine.name, collection.name, (err, res) -> display('Get a collection', err, res) deleteCollection: -> tinysou.collections.delete engine.name, collection.name, (err, res) -> display('Delete a collection', err, res) listDocuments: -> tinysou.documents.list engine.name, collection.name, (err, res) -> display("List documents in #{collection.name}", err, res) createDocument: -> tinysou.documents.create engine.name, collection.name, document, (err, res) -> display('Create a document', err, res) getDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.get engine.name, collection.name, document_id, (err, res) -> display('Get a document', err, res) else console.log('Please create a document first') updateDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.update engine.name, collection.name, document_id, document, (err, res) -> display('Update a document', err, res) else console.log('Please create a document first') deleteDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.delete engine.name, collection.name, document_id, (err, res) -> display('Delete a document', err, res) else console.log('Please create a document first') search: -> tinysou.search engine.name, searchInfo, (err, res) -> display('Search in many collections', err, res) autocomplete: -> tinysou.autocomplete engine.name, autocompleteInfo, (err, res) -> display("autocomplete in many collections", err, res) } args = process.argv if args.length == 3 and args[2] of tasks tasks[args[2]]() else console.log('Available arguments are:') console.log(k) for k of tasks
true
Tinysou = require 'tinysou' TOKEN = 'PI:KEY:<KEY>END_PI' engine = { name: 'YOUR-blog', display_name: 'Blog' } collection = { name: 'posts', field_types: { title: 'string', tags: 'string', author: 'enum', date: 'date', body: 'text' } } document = { title: 'My First Post', tags: ['news'], author: 'Author', date: new Date().getTime(), body: 'Tinysou start online today!' } tinysou = new Tinysou TOKEN searchInfo = { q: 'tinysou' c: 'posts' page: 0, per_parge: 10, sort:{ field: "date", order: "asc", mode: "avg" } } autocompleteInfo = { q: 'fir', c: 'posts' sort:{ field: "date", order: "asc", mode: "avg" } } display = (msg, err, res) -> console.log(msg) if err console.log(err) else console.log(res) tasks = { listEngines: -> tinysou.engines.list (err, res) -> display('List engines', err, res) createEngine: -> tinysou.engines.create engine, (err, res) -> display('Create an engine', err, res) getEngine: -> tinysou.engines.get engine.name, (err, res) -> display('Get an engine', err, res) updateEngine: -> tinysou.engines.update engine.name, engine, (err, res) -> display('Update an engine', err, res) deleteEngine: -> tinysou.engines.delete engine.name, (err, res) -> display('Delete an engine', err, res) listCollections: -> tinysou.collections.list engine.name, (err, res) -> display("List collections in #{engine.name}", err, res) createCollection: -> tinysou.collections.create engine.name, collection, (err, res) -> display('Create a collection', err, res) getCollection: -> tinysou.collections.get engine.name, collection.name, (err, res) -> display('Get a collection', err, res) deleteCollection: -> tinysou.collections.delete engine.name, collection.name, (err, res) -> display('Delete a collection', err, res) listDocuments: -> tinysou.documents.list engine.name, collection.name, (err, res) -> display("List documents in #{collection.name}", err, res) createDocument: -> tinysou.documents.create engine.name, collection.name, document, (err, res) -> display('Create a document', err, res) getDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.get engine.name, collection.name, document_id, (err, res) -> display('Get a document', err, res) else console.log('Please create a document first') updateDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.update engine.name, collection.name, document_id, document, (err, res) -> display('Update a document', err, res) else console.log('Please create a document first') deleteDocument: -> tinysou.documents.list engine.name, collection.name, (err, res) -> if err console.log(err) else if res.length > 0 document_id = res[0].id tinysou.documents.delete engine.name, collection.name, document_id, (err, res) -> display('Delete a document', err, res) else console.log('Please create a document first') search: -> tinysou.search engine.name, searchInfo, (err, res) -> display('Search in many collections', err, res) autocomplete: -> tinysou.autocomplete engine.name, autocompleteInfo, (err, res) -> display("autocomplete in many collections", err, res) } args = process.argv if args.length == 3 and args[2] of tasks tasks[args[2]]() else console.log('Available arguments are:') console.log(k) for k of tasks
[ { "context": " username: ssh.config.username\n password: ssh.config.password\n private_key: ssh.config.privateKey\n .cal", "end": 421, "score": 0.9992461204528809, "start": 402, "tag": "PASSWORD", "value": "ssh.config.password" }, { "context": " username: ssh.config.username\n password: ssh.config.password\n private_key: ssh.config.privateKey\n .cal", "end": 776, "score": 0.9992386698722839, "start": 757, "tag": "PASSWORD", "value": "ssh.config.password" }, { "context": " username: ssh.config.username\n password: ssh.config.password\n private_key: ssh.config.privateKey\n .s", "end": 1158, "score": 0.9992785453796387, "start": 1139, "tag": "PASSWORD", "value": "ssh.config.password" } ]
packages/core/test/ssh/index.coffee
chibanemourad/node-nikita
0
nikita = require '../../src' misc = require '../../src/misc' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'ssh.index', -> they 'argument is true', ({ssh}) -> return @skip() unless ssh nikita .ssh.open host: ssh.config.host port: ssh.config.port username: ssh.config.username password: ssh.config.password private_key: ssh.config.privateKey .call -> misc.ssh.is(@ssh true).should.be.true() .ssh.close() .promise() they 'argument is false', ({ssh}) -> return @skip() unless ssh nikita .ssh.open host: ssh.config.host port: ssh.config.port username: ssh.config.username password: ssh.config.password private_key: ssh.config.privateKey .call -> (@ssh(false) is null).should.be.true() .ssh.close() .promise() they 'argument does not conflict with session', ({ssh}) -> return @skip() unless ssh nikita ssh: host: ssh.config.host port: ssh.config.port username: ssh.config.username password: ssh.config.password private_key: ssh.config.privateKey .ssh.open() .call -> misc.ssh.is(@ssh true).should.be.true() .call -> (@ssh(false) is null).should.be.true() .ssh.close() .promise()
218648
nikita = require '../../src' misc = require '../../src/misc' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'ssh.index', -> they 'argument is true', ({ssh}) -> return @skip() unless ssh nikita .ssh.open host: ssh.config.host port: ssh.config.port username: ssh.config.username password: <PASSWORD> private_key: ssh.config.privateKey .call -> misc.ssh.is(@ssh true).should.be.true() .ssh.close() .promise() they 'argument is false', ({ssh}) -> return @skip() unless ssh nikita .ssh.open host: ssh.config.host port: ssh.config.port username: ssh.config.username password: <PASSWORD> private_key: ssh.config.privateKey .call -> (@ssh(false) is null).should.be.true() .ssh.close() .promise() they 'argument does not conflict with session', ({ssh}) -> return @skip() unless ssh nikita ssh: host: ssh.config.host port: ssh.config.port username: ssh.config.username password: <PASSWORD> private_key: ssh.config.privateKey .ssh.open() .call -> misc.ssh.is(@ssh true).should.be.true() .call -> (@ssh(false) is null).should.be.true() .ssh.close() .promise()
true
nikita = require '../../src' misc = require '../../src/misc' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'ssh.index', -> they 'argument is true', ({ssh}) -> return @skip() unless ssh nikita .ssh.open host: ssh.config.host port: ssh.config.port username: ssh.config.username password: PI:PASSWORD:<PASSWORD>END_PI private_key: ssh.config.privateKey .call -> misc.ssh.is(@ssh true).should.be.true() .ssh.close() .promise() they 'argument is false', ({ssh}) -> return @skip() unless ssh nikita .ssh.open host: ssh.config.host port: ssh.config.port username: ssh.config.username password: PI:PASSWORD:<PASSWORD>END_PI private_key: ssh.config.privateKey .call -> (@ssh(false) is null).should.be.true() .ssh.close() .promise() they 'argument does not conflict with session', ({ssh}) -> return @skip() unless ssh nikita ssh: host: ssh.config.host port: ssh.config.port username: ssh.config.username password: PI:PASSWORD:<PASSWORD>END_PI private_key: ssh.config.privateKey .ssh.open() .call -> misc.ssh.is(@ssh true).should.be.true() .call -> (@ssh(false) is null).should.be.true() .ssh.close() .promise()
[ { "context": " newUser = objtrans\n token: token\n profile: profile\n , ndx.", "end": 2120, "score": 0.7018923163414001, "start": 2115, "tag": "PASSWORD", "value": "token" }, { "context": "lse\n updateUser = objtrans\n token: token\n profile: profile\n , ndx.transfor", "end": 2592, "score": 0.482374370098114, "start": 2587, "tag": "PASSWORD", "value": "token" } ]
src/index.coffee
ndxbxrme/ndx-passport-facebook
0
'use strict' FacebookStrategy = require('passport-facebook').Strategy objtrans = require 'objtrans' module.exports = (ndx) -> ndx.settings.FACEBOOK_KEY = process.env.FACEBOOK_KEY or ndx.settings.FACEBOOK_KEY ndx.settings.FACEBOOK_SECRET = process.env.FACEBOOK_SECRET or ndx.settings.FACEBOOK_SECRET ndx.settings.FACEBOOK_CALLBACK = process.env.FACEBOOK_CALLBACK or ndx.settings.FACEBOOK_CALLBACK ndx.settings.FACEBOOK_SCOPE = process.env.FACEBOOK_SCOPE or ndx.settings.FACEBOOK_SCOPE or 'email' if ndx.settings.FACEBOOK_KEY if not ndx.transforms.facebook ndx.transforms.facebook = email: 'profile.emails[0].value' facebook: id: 'profile.id' token: 'token' name: (input) -> if input input.profile.name.givenName + ' ' + input.profile.name.familyName email: 'profile.emails[0].value' scopes = ndx.passport.splitScopes ndx.settings.FACEBOOK_SCOPE ndx.passport.use new FacebookStrategy clientID: ndx.settings.FACEBOOK_KEY clientSecret: ndx.settings.FACEBOOK_SECRET callbackURL: ndx.settings.FACEBOOK_CALLBACK passReqToCallback: true , (req, token, refreshToken, profile, done) -> if not ndx.user ndx.database.select ndx.settings.USER_TABLE, where: facebook: id: profile.id , (users) -> if users and users.length if not users[0].facebook.token updateUser = objtrans token: token profile: profile , ndx.transforms.facebook where = {} where[ndx.settings.AUTO_ID] = users[0][ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, updateUser, where, null, true ndx.user = users[0] return done null, users[0] ndx.user = users[0] if ndx.auth ndx.auth.extendUser() ndx.passport.syncCallback 'login', ndx.user return done null, users[0] else newUser = objtrans token: token profile: profile , ndx.transforms.facebook newUser[ndx.settings.AUTO_ID] = ndx.generateID() ndx.database.insert ndx.settings.USER_TABLE, newUser, null, true ndx.user = newUser if ndx.auth ndx.auth.extendUser() ndx.passport.syncCallback 'signup', ndx.user return done null, newUser , true else updateUser = objtrans token: token profile: profile , ndx.transforms.facebook where = {} where[ndx.settings.AUTO_ID] = ndx.user[ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, updateUser, where, null, true return done null, ndx.user ndx.app.get '/api/facebook', ndx.passport.authenticate('facebook', scope: scopes) , ndx.postAuthenticate ndx.app.get '/api/facebook/callback', ndx.passport.authenticate('facebook') , ndx.postAuthenticate ndx.app.get '/api/connect/facebook', ndx.passport.authorize('facebook', scope: scopes) ndx.app.get '/api/unlink/facebook', (req, res) -> user = ndx.user user.facebook.token = undefined user.save (err) -> res.redirect '/profile' return return
200852
'use strict' FacebookStrategy = require('passport-facebook').Strategy objtrans = require 'objtrans' module.exports = (ndx) -> ndx.settings.FACEBOOK_KEY = process.env.FACEBOOK_KEY or ndx.settings.FACEBOOK_KEY ndx.settings.FACEBOOK_SECRET = process.env.FACEBOOK_SECRET or ndx.settings.FACEBOOK_SECRET ndx.settings.FACEBOOK_CALLBACK = process.env.FACEBOOK_CALLBACK or ndx.settings.FACEBOOK_CALLBACK ndx.settings.FACEBOOK_SCOPE = process.env.FACEBOOK_SCOPE or ndx.settings.FACEBOOK_SCOPE or 'email' if ndx.settings.FACEBOOK_KEY if not ndx.transforms.facebook ndx.transforms.facebook = email: 'profile.emails[0].value' facebook: id: 'profile.id' token: 'token' name: (input) -> if input input.profile.name.givenName + ' ' + input.profile.name.familyName email: 'profile.emails[0].value' scopes = ndx.passport.splitScopes ndx.settings.FACEBOOK_SCOPE ndx.passport.use new FacebookStrategy clientID: ndx.settings.FACEBOOK_KEY clientSecret: ndx.settings.FACEBOOK_SECRET callbackURL: ndx.settings.FACEBOOK_CALLBACK passReqToCallback: true , (req, token, refreshToken, profile, done) -> if not ndx.user ndx.database.select ndx.settings.USER_TABLE, where: facebook: id: profile.id , (users) -> if users and users.length if not users[0].facebook.token updateUser = objtrans token: token profile: profile , ndx.transforms.facebook where = {} where[ndx.settings.AUTO_ID] = users[0][ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, updateUser, where, null, true ndx.user = users[0] return done null, users[0] ndx.user = users[0] if ndx.auth ndx.auth.extendUser() ndx.passport.syncCallback 'login', ndx.user return done null, users[0] else newUser = objtrans token: <PASSWORD> profile: profile , ndx.transforms.facebook newUser[ndx.settings.AUTO_ID] = ndx.generateID() ndx.database.insert ndx.settings.USER_TABLE, newUser, null, true ndx.user = newUser if ndx.auth ndx.auth.extendUser() ndx.passport.syncCallback 'signup', ndx.user return done null, newUser , true else updateUser = objtrans token: <PASSWORD> profile: profile , ndx.transforms.facebook where = {} where[ndx.settings.AUTO_ID] = ndx.user[ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, updateUser, where, null, true return done null, ndx.user ndx.app.get '/api/facebook', ndx.passport.authenticate('facebook', scope: scopes) , ndx.postAuthenticate ndx.app.get '/api/facebook/callback', ndx.passport.authenticate('facebook') , ndx.postAuthenticate ndx.app.get '/api/connect/facebook', ndx.passport.authorize('facebook', scope: scopes) ndx.app.get '/api/unlink/facebook', (req, res) -> user = ndx.user user.facebook.token = undefined user.save (err) -> res.redirect '/profile' return return
true
'use strict' FacebookStrategy = require('passport-facebook').Strategy objtrans = require 'objtrans' module.exports = (ndx) -> ndx.settings.FACEBOOK_KEY = process.env.FACEBOOK_KEY or ndx.settings.FACEBOOK_KEY ndx.settings.FACEBOOK_SECRET = process.env.FACEBOOK_SECRET or ndx.settings.FACEBOOK_SECRET ndx.settings.FACEBOOK_CALLBACK = process.env.FACEBOOK_CALLBACK or ndx.settings.FACEBOOK_CALLBACK ndx.settings.FACEBOOK_SCOPE = process.env.FACEBOOK_SCOPE or ndx.settings.FACEBOOK_SCOPE or 'email' if ndx.settings.FACEBOOK_KEY if not ndx.transforms.facebook ndx.transforms.facebook = email: 'profile.emails[0].value' facebook: id: 'profile.id' token: 'token' name: (input) -> if input input.profile.name.givenName + ' ' + input.profile.name.familyName email: 'profile.emails[0].value' scopes = ndx.passport.splitScopes ndx.settings.FACEBOOK_SCOPE ndx.passport.use new FacebookStrategy clientID: ndx.settings.FACEBOOK_KEY clientSecret: ndx.settings.FACEBOOK_SECRET callbackURL: ndx.settings.FACEBOOK_CALLBACK passReqToCallback: true , (req, token, refreshToken, profile, done) -> if not ndx.user ndx.database.select ndx.settings.USER_TABLE, where: facebook: id: profile.id , (users) -> if users and users.length if not users[0].facebook.token updateUser = objtrans token: token profile: profile , ndx.transforms.facebook where = {} where[ndx.settings.AUTO_ID] = users[0][ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, updateUser, where, null, true ndx.user = users[0] return done null, users[0] ndx.user = users[0] if ndx.auth ndx.auth.extendUser() ndx.passport.syncCallback 'login', ndx.user return done null, users[0] else newUser = objtrans token: PI:PASSWORD:<PASSWORD>END_PI profile: profile , ndx.transforms.facebook newUser[ndx.settings.AUTO_ID] = ndx.generateID() ndx.database.insert ndx.settings.USER_TABLE, newUser, null, true ndx.user = newUser if ndx.auth ndx.auth.extendUser() ndx.passport.syncCallback 'signup', ndx.user return done null, newUser , true else updateUser = objtrans token: PI:PASSWORD:<PASSWORD>END_PI profile: profile , ndx.transforms.facebook where = {} where[ndx.settings.AUTO_ID] = ndx.user[ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, updateUser, where, null, true return done null, ndx.user ndx.app.get '/api/facebook', ndx.passport.authenticate('facebook', scope: scopes) , ndx.postAuthenticate ndx.app.get '/api/facebook/callback', ndx.passport.authenticate('facebook') , ndx.postAuthenticate ndx.app.get '/api/connect/facebook', ndx.passport.authorize('facebook', scope: scopes) ndx.app.get '/api/unlink/facebook', (req, res) -> user = ndx.user user.facebook.token = undefined user.save (err) -> res.redirect '/profile' return return
[ { "context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig", "end": 74, "score": 0.9998774528503418, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa", "end": 96, "score": 0.9999335408210754, "start": 76, "tag": "EMAIL", "value": "jessym@konsserto.com" }, { "context": "ic/Tools');\n\n#\n# GenerateBundleCommand\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\n\nInputOption = use('@Kon", "end": 691, "score": 0.9998845458030701, "start": 678, "tag": "NAME", "value": "Jessym Reziga" }, { "context": " GenerateBundleCommand\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\n\nInputOption = use('@Konsserto/Component/Conso", "end": 713, "score": 0.9999324083328247, "start": 693, "tag": "EMAIL", "value": "jessym@konsserto.com" } ]
node_modules/konsserto/lib/src/Konsserto/Bundle/FrameworkBundle/Command/GenerateBundleCommand.coffee
konsserto/konsserto
2
### * This file is part of the Konsserto package. * * (c) Jessym Reziga <jessym@konsserto.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') file_helper = use('fs') path_helper = use('path') Table = use('cli-table'); Command = use('@Konsserto/Component/Console/Command') Filesystem = use('@Konsserto/Component/Filesystem/Filesystem') InputArgument = use('@Konsserto/Component/Console/Input/InputArgument') InputOption = use('@Konsserto/Component/Console/Input/InputOption') Tools = use('@Konsserto/Component/Static/Tools'); # # GenerateBundleCommand # # @author Jessym Reziga <jessym@konsserto.com> # InputOption = use('@Konsserto/Component/Console/Input/InputOption') class GenerateBundleCommand extends Command create: () -> @setName('generate:bundle') @setDescription('Generate a bundle') @setDefinition([new InputOption('--empty','e',InputOption.VALUE_NONE,'Doesn\'t generate example')]) @setHelp(' The command %command.name% generate the whole bundle directory tree. Example:\n %command.full_name% JohnSmithBundle') execute: (input) -> @nl() return 0 interact: (input)-> empty = input.getOption('empty') table = new Table({chars:@getArrayChars()}); table.push(['Konsserto Bundle Generator']) @write('\n\n'+table.toString()+'\n') @write("""Bundle or not to Bundle, that is the question. Luckily in Konsserto, all is about bundles. Each bundle is hosted under a namespace (like Foo/Bundle/(...)/BlogBundle). The namespace should begin with a vendor name like your company name, your project name, or your client name, followed by one or more optional category sub-namespaces, and it should end with the bundle name itself (which must have 'Bundle' as a suffix). """) bundle = '' name = '' _loop = true while _loop bundle = @ask('\nBundle namespace : ') match = bundle.match('^([a-zA-Z0-9/]+)$') if bundle == 'exit' || bundle == 'quit' || bundle == '!q' process.exit(0) if match == undefined || match == null || match.length <= 0 @write(' The namespace contains invalid characters.') continue if !Tools.endsWith(bundle,'Bundle') @write(' The namespace must end with \'Bundle\'.') continue if bundle.indexOf('/') <= 0 @write(' You must specify a vendor name (Example: VendorName/'+bundle+').') continue _loop = false _loop = true while _loop name = @ask('\nBundle name ['+bundle.replace(/\//g,'')+']: ') match = name.match('^([a-zA-Z0-9/]+)$') if name == 'exit' || name == 'quit' || name == '!q' process.exit(0) if name == '' name = bundle.replace(/\//g,'') break if match == undefined || match == null || match.length <= 0 @write(' The namespace contains invalid characters.') continue if !Tools.endsWith(name,'Bundle') @write(' The namespace must end with \'Bundle\'.') continue _loop = false root = Filesystem.mktree(process.cwd()+'/'+sourceDir+'/',bundle.split('/')) bundleDirs = { ':files':{} 'Command': null, 'Controller': { ':files': { 'HelloController.coffee':@getControllerClassContent(name) } }, 'Entity': null, 'Repository': null, 'Resources': { 'config':{ ':files':{ 'routing.js':@getRoutingContent(name,bundle,empty), 'services.js':@getServiceContent(name,bundle,empty), 'socket.js':@getSocketContent() } }, 'views':{ 'Hello':{ ':files':{ 'index.html.twig':'Hello {{ name }}!' } } } }, 'Services': null } if empty bundleDirs['Controller'] = null bundleDirs['Resources']['views'] = null bundleDirs[':files'][name+'.coffee'] = @getBundleClassContent(name) Filesystem.mktree(root,bundleDirs) @registerBundle(name,bundle) @registerRoutes(name,bundle) @registerSockets(name,bundle) return 0 registerBundle:(name,bundle) -> file = process.cwd() + '/app/config/bundles.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newBundle = 'use(\'@'+bundle+'/'+name+'\')' oldBundleWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newBundle) >= 0 oldBundleWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _i if moduleExportAtLine != -1 & !oldBundleWithSameLine arrayFile[moduleExportAtLine] = 'bundles.push('+newBundle+');\nmodule.exports = bundles;' file_helper.writeFileSync(file,arrayFile.join('\n')) registerRoutes:(name,bundle,shortname = '') -> file = process.cwd() + '/app/config/routing.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newRoutes = "resource: '@"+bundle+"/Resources/config/routing.js'" bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') shortname += part+'_' for part in path newRoutesExtended = "{\n \tname: '"+shortname.toLowerCase()+"import',\n \t"+newRoutes+"\n }" oldRoutesWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newRoutes) >= 0 oldRoutesWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _j if moduleExportAtLine != -1 & !oldRoutesWithSameLine arrayFile[moduleExportAtLine] = 'routing.push('+newRoutesExtended+');\nmodule.exports = routing;' file_helper.writeFileSync(file,arrayFile.join('\n')) registerSockets:(name,bundle,shortname = '') -> file = process.cwd() + '/app/config/socket.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newSockets = "resource: '@"+bundle+"/Resources/config/socket.js'" bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') shortname += part+'_' for part in path newSocketsExtended = "{\n \tname: '"+shortname.toLowerCase()+"import',\n \t"+newSockets+"\n }" oldSocketsWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newSockets) >= 0 oldSocketsWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _j if moduleExportAtLine != -1 & !oldSocketsWithSameLine arrayFile[moduleExportAtLine] = 'socket.push('+newSocketsExtended+');\nmodule.exports = socket;' file_helper.writeFileSync(file,arrayFile.join('\n')) getBundleClassContent:(name) -> return """ Bundle = use('@Konsserto/Component/Bundle/Bundle')\n class #{name} extends Bundle\n\n\n\n module.exports = new #{name} """ getControllerClassContent:(name) -> return """ Controller = use('@Konsserto/Bundle/FrameworkBundle/Controller/Controller')\n class HelloController extends Controller\n\n \tindexAction:(name) =>\n \t\t@render('#{name}:Hello:index.html.twig',{name:name})\n\n module.exports = HelloController """ getRoutingContent:(name,bundle,empty = false,route = '') -> bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') route += part+'_' for part in path if empty return """ var routing = [ \n ];\n\n module.exports = routing; """ return """ var routing = [ \t{name: '#{route.toLowerCase()}homepage', pattern: '/hello/{name}', controller: '#{name}:Hello:index', method: 'get'}\n ];\n\n module.exports = routing; """ getServiceContent:(name,bundle,empty = false,service = '') -> include = (bundle) bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') service += part+'_' for part in path if empty return """ var services = [ \n ];\n\n module.exports = services; """ return """ var services = [ \t//{name: '#{service.toLowerCase()}service', _class: '@#{include}/Services/#{name}Service'}\n ];\n\n module.exports = services; """ getSocketContent:() -> return """ var socket = [ \n ];\n\n module.exports = socket; """ module.exports = GenerateBundleCommand;
84114
### * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') file_helper = use('fs') path_helper = use('path') Table = use('cli-table'); Command = use('@Konsserto/Component/Console/Command') Filesystem = use('@Konsserto/Component/Filesystem/Filesystem') InputArgument = use('@Konsserto/Component/Console/Input/InputArgument') InputOption = use('@Konsserto/Component/Console/Input/InputOption') Tools = use('@Konsserto/Component/Static/Tools'); # # GenerateBundleCommand # # @author <NAME> <<EMAIL>> # InputOption = use('@Konsserto/Component/Console/Input/InputOption') class GenerateBundleCommand extends Command create: () -> @setName('generate:bundle') @setDescription('Generate a bundle') @setDefinition([new InputOption('--empty','e',InputOption.VALUE_NONE,'Doesn\'t generate example')]) @setHelp(' The command %command.name% generate the whole bundle directory tree. Example:\n %command.full_name% JohnSmithBundle') execute: (input) -> @nl() return 0 interact: (input)-> empty = input.getOption('empty') table = new Table({chars:@getArrayChars()}); table.push(['Konsserto Bundle Generator']) @write('\n\n'+table.toString()+'\n') @write("""Bundle or not to Bundle, that is the question. Luckily in Konsserto, all is about bundles. Each bundle is hosted under a namespace (like Foo/Bundle/(...)/BlogBundle). The namespace should begin with a vendor name like your company name, your project name, or your client name, followed by one or more optional category sub-namespaces, and it should end with the bundle name itself (which must have 'Bundle' as a suffix). """) bundle = '' name = '' _loop = true while _loop bundle = @ask('\nBundle namespace : ') match = bundle.match('^([a-zA-Z0-9/]+)$') if bundle == 'exit' || bundle == 'quit' || bundle == '!q' process.exit(0) if match == undefined || match == null || match.length <= 0 @write(' The namespace contains invalid characters.') continue if !Tools.endsWith(bundle,'Bundle') @write(' The namespace must end with \'Bundle\'.') continue if bundle.indexOf('/') <= 0 @write(' You must specify a vendor name (Example: VendorName/'+bundle+').') continue _loop = false _loop = true while _loop name = @ask('\nBundle name ['+bundle.replace(/\//g,'')+']: ') match = name.match('^([a-zA-Z0-9/]+)$') if name == 'exit' || name == 'quit' || name == '!q' process.exit(0) if name == '' name = bundle.replace(/\//g,'') break if match == undefined || match == null || match.length <= 0 @write(' The namespace contains invalid characters.') continue if !Tools.endsWith(name,'Bundle') @write(' The namespace must end with \'Bundle\'.') continue _loop = false root = Filesystem.mktree(process.cwd()+'/'+sourceDir+'/',bundle.split('/')) bundleDirs = { ':files':{} 'Command': null, 'Controller': { ':files': { 'HelloController.coffee':@getControllerClassContent(name) } }, 'Entity': null, 'Repository': null, 'Resources': { 'config':{ ':files':{ 'routing.js':@getRoutingContent(name,bundle,empty), 'services.js':@getServiceContent(name,bundle,empty), 'socket.js':@getSocketContent() } }, 'views':{ 'Hello':{ ':files':{ 'index.html.twig':'Hello {{ name }}!' } } } }, 'Services': null } if empty bundleDirs['Controller'] = null bundleDirs['Resources']['views'] = null bundleDirs[':files'][name+'.coffee'] = @getBundleClassContent(name) Filesystem.mktree(root,bundleDirs) @registerBundle(name,bundle) @registerRoutes(name,bundle) @registerSockets(name,bundle) return 0 registerBundle:(name,bundle) -> file = process.cwd() + '/app/config/bundles.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newBundle = 'use(\'@'+bundle+'/'+name+'\')' oldBundleWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newBundle) >= 0 oldBundleWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _i if moduleExportAtLine != -1 & !oldBundleWithSameLine arrayFile[moduleExportAtLine] = 'bundles.push('+newBundle+');\nmodule.exports = bundles;' file_helper.writeFileSync(file,arrayFile.join('\n')) registerRoutes:(name,bundle,shortname = '') -> file = process.cwd() + '/app/config/routing.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newRoutes = "resource: '@"+bundle+"/Resources/config/routing.js'" bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') shortname += part+'_' for part in path newRoutesExtended = "{\n \tname: '"+shortname.toLowerCase()+"import',\n \t"+newRoutes+"\n }" oldRoutesWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newRoutes) >= 0 oldRoutesWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _j if moduleExportAtLine != -1 & !oldRoutesWithSameLine arrayFile[moduleExportAtLine] = 'routing.push('+newRoutesExtended+');\nmodule.exports = routing;' file_helper.writeFileSync(file,arrayFile.join('\n')) registerSockets:(name,bundle,shortname = '') -> file = process.cwd() + '/app/config/socket.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newSockets = "resource: '@"+bundle+"/Resources/config/socket.js'" bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') shortname += part+'_' for part in path newSocketsExtended = "{\n \tname: '"+shortname.toLowerCase()+"import',\n \t"+newSockets+"\n }" oldSocketsWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newSockets) >= 0 oldSocketsWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _j if moduleExportAtLine != -1 & !oldSocketsWithSameLine arrayFile[moduleExportAtLine] = 'socket.push('+newSocketsExtended+');\nmodule.exports = socket;' file_helper.writeFileSync(file,arrayFile.join('\n')) getBundleClassContent:(name) -> return """ Bundle = use('@Konsserto/Component/Bundle/Bundle')\n class #{name} extends Bundle\n\n\n\n module.exports = new #{name} """ getControllerClassContent:(name) -> return """ Controller = use('@Konsserto/Bundle/FrameworkBundle/Controller/Controller')\n class HelloController extends Controller\n\n \tindexAction:(name) =>\n \t\t@render('#{name}:Hello:index.html.twig',{name:name})\n\n module.exports = HelloController """ getRoutingContent:(name,bundle,empty = false,route = '') -> bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') route += part+'_' for part in path if empty return """ var routing = [ \n ];\n\n module.exports = routing; """ return """ var routing = [ \t{name: '#{route.toLowerCase()}homepage', pattern: '/hello/{name}', controller: '#{name}:Hello:index', method: 'get'}\n ];\n\n module.exports = routing; """ getServiceContent:(name,bundle,empty = false,service = '') -> include = (bundle) bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') service += part+'_' for part in path if empty return """ var services = [ \n ];\n\n module.exports = services; """ return """ var services = [ \t//{name: '#{service.toLowerCase()}service', _class: '@#{include}/Services/#{name}Service'}\n ];\n\n module.exports = services; """ getSocketContent:() -> return """ var socket = [ \n ];\n\n module.exports = socket; """ module.exports = GenerateBundleCommand;
true
### * This file is part of the Konsserto package. * * (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') file_helper = use('fs') path_helper = use('path') Table = use('cli-table'); Command = use('@Konsserto/Component/Console/Command') Filesystem = use('@Konsserto/Component/Filesystem/Filesystem') InputArgument = use('@Konsserto/Component/Console/Input/InputArgument') InputOption = use('@Konsserto/Component/Console/Input/InputOption') Tools = use('@Konsserto/Component/Static/Tools'); # # GenerateBundleCommand # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # InputOption = use('@Konsserto/Component/Console/Input/InputOption') class GenerateBundleCommand extends Command create: () -> @setName('generate:bundle') @setDescription('Generate a bundle') @setDefinition([new InputOption('--empty','e',InputOption.VALUE_NONE,'Doesn\'t generate example')]) @setHelp(' The command %command.name% generate the whole bundle directory tree. Example:\n %command.full_name% JohnSmithBundle') execute: (input) -> @nl() return 0 interact: (input)-> empty = input.getOption('empty') table = new Table({chars:@getArrayChars()}); table.push(['Konsserto Bundle Generator']) @write('\n\n'+table.toString()+'\n') @write("""Bundle or not to Bundle, that is the question. Luckily in Konsserto, all is about bundles. Each bundle is hosted under a namespace (like Foo/Bundle/(...)/BlogBundle). The namespace should begin with a vendor name like your company name, your project name, or your client name, followed by one or more optional category sub-namespaces, and it should end with the bundle name itself (which must have 'Bundle' as a suffix). """) bundle = '' name = '' _loop = true while _loop bundle = @ask('\nBundle namespace : ') match = bundle.match('^([a-zA-Z0-9/]+)$') if bundle == 'exit' || bundle == 'quit' || bundle == '!q' process.exit(0) if match == undefined || match == null || match.length <= 0 @write(' The namespace contains invalid characters.') continue if !Tools.endsWith(bundle,'Bundle') @write(' The namespace must end with \'Bundle\'.') continue if bundle.indexOf('/') <= 0 @write(' You must specify a vendor name (Example: VendorName/'+bundle+').') continue _loop = false _loop = true while _loop name = @ask('\nBundle name ['+bundle.replace(/\//g,'')+']: ') match = name.match('^([a-zA-Z0-9/]+)$') if name == 'exit' || name == 'quit' || name == '!q' process.exit(0) if name == '' name = bundle.replace(/\//g,'') break if match == undefined || match == null || match.length <= 0 @write(' The namespace contains invalid characters.') continue if !Tools.endsWith(name,'Bundle') @write(' The namespace must end with \'Bundle\'.') continue _loop = false root = Filesystem.mktree(process.cwd()+'/'+sourceDir+'/',bundle.split('/')) bundleDirs = { ':files':{} 'Command': null, 'Controller': { ':files': { 'HelloController.coffee':@getControllerClassContent(name) } }, 'Entity': null, 'Repository': null, 'Resources': { 'config':{ ':files':{ 'routing.js':@getRoutingContent(name,bundle,empty), 'services.js':@getServiceContent(name,bundle,empty), 'socket.js':@getSocketContent() } }, 'views':{ 'Hello':{ ':files':{ 'index.html.twig':'Hello {{ name }}!' } } } }, 'Services': null } if empty bundleDirs['Controller'] = null bundleDirs['Resources']['views'] = null bundleDirs[':files'][name+'.coffee'] = @getBundleClassContent(name) Filesystem.mktree(root,bundleDirs) @registerBundle(name,bundle) @registerRoutes(name,bundle) @registerSockets(name,bundle) return 0 registerBundle:(name,bundle) -> file = process.cwd() + '/app/config/bundles.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newBundle = 'use(\'@'+bundle+'/'+name+'\')' oldBundleWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newBundle) >= 0 oldBundleWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _i if moduleExportAtLine != -1 & !oldBundleWithSameLine arrayFile[moduleExportAtLine] = 'bundles.push('+newBundle+');\nmodule.exports = bundles;' file_helper.writeFileSync(file,arrayFile.join('\n')) registerRoutes:(name,bundle,shortname = '') -> file = process.cwd() + '/app/config/routing.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newRoutes = "resource: '@"+bundle+"/Resources/config/routing.js'" bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') shortname += part+'_' for part in path newRoutesExtended = "{\n \tname: '"+shortname.toLowerCase()+"import',\n \t"+newRoutes+"\n }" oldRoutesWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newRoutes) >= 0 oldRoutesWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _j if moduleExportAtLine != -1 & !oldRoutesWithSameLine arrayFile[moduleExportAtLine] = 'routing.push('+newRoutesExtended+');\nmodule.exports = routing;' file_helper.writeFileSync(file,arrayFile.join('\n')) registerSockets:(name,bundle,shortname = '') -> file = process.cwd() + '/app/config/socket.js' arrayFile = file_helper.readFileSync(file).toString().split('\n') newSockets = "resource: '@"+bundle+"/Resources/config/socket.js'" bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') shortname += part+'_' for part in path newSocketsExtended = "{\n \tname: '"+shortname.toLowerCase()+"import',\n \t"+newSockets+"\n }" oldSocketsWithSameLine = false moduleExportAtLine = -1 for line in arrayFile if line.trim().indexOf(newSockets) >= 0 oldSocketsWithSameLine = true if line.trim().indexOf('module.exports') == 0 moduleExportAtLine = _j if moduleExportAtLine != -1 & !oldSocketsWithSameLine arrayFile[moduleExportAtLine] = 'socket.push('+newSocketsExtended+');\nmodule.exports = socket;' file_helper.writeFileSync(file,arrayFile.join('\n')) getBundleClassContent:(name) -> return """ Bundle = use('@Konsserto/Component/Bundle/Bundle')\n class #{name} extends Bundle\n\n\n\n module.exports = new #{name} """ getControllerClassContent:(name) -> return """ Controller = use('@Konsserto/Bundle/FrameworkBundle/Controller/Controller')\n class HelloController extends Controller\n\n \tindexAction:(name) =>\n \t\t@render('#{name}:Hello:index.html.twig',{name:name})\n\n module.exports = HelloController """ getRoutingContent:(name,bundle,empty = false,route = '') -> bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') route += part+'_' for part in path if empty return """ var routing = [ \n ];\n\n module.exports = routing; """ return """ var routing = [ \t{name: '#{route.toLowerCase()}homepage', pattern: '/hello/{name}', controller: '#{name}:Hello:index', method: 'get'}\n ];\n\n module.exports = routing; """ getServiceContent:(name,bundle,empty = false,service = '') -> include = (bundle) bundle = bundle.replace(/Bundle/g,'') path = bundle.split('/') service += part+'_' for part in path if empty return """ var services = [ \n ];\n\n module.exports = services; """ return """ var services = [ \t//{name: '#{service.toLowerCase()}service', _class: '@#{include}/Services/#{name}Service'}\n ];\n\n module.exports = services; """ getSocketContent:() -> return """ var socket = [ \n ];\n\n module.exports = socket; """ module.exports = GenerateBundleCommand;
[ { "context": ".load [\n {\n id: 1,\n committer_name: 'Jimmy',\n committer_email: 'jimmy@example.com',\n ", "end": 217, "score": 0.9996939897537231, "start": 212, "tag": "NAME", "value": "Jimmy" }, { "context": " committer_name: 'Jimmy',\n committer_email: 'jimmy@example.com',\n author_name: 'Jimmy',\n author_email:", "end": 261, "score": 0.9999254941940308, "start": 244, "tag": "EMAIL", "value": "jimmy@example.com" }, { "context": "r_email: 'jimmy@example.com',\n author_name: 'Jimmy',\n author_email: 'jimmy@example.com'\n }\n ", "end": 289, "score": 0.9997737407684326, "start": 284, "tag": "NAME", "value": "Jimmy" }, { "context": "\n author_name: 'Jimmy',\n author_email: 'jimmy@example.com'\n }\n ]\n\n Ember.run ->\n record = Travis.Co", "end": 330, "score": 0.999925434589386, "start": 313, "tag": "EMAIL", "value": "jimmy@example.com" }, { "context": ".load [\n {\n id: 1,\n committer_name: 'Jimmy',\n committer_email: 'jimmy@example.com',\n ", "end": 609, "score": 0.9997785091400146, "start": 604, "tag": "NAME", "value": "Jimmy" }, { "context": " committer_name: 'Jimmy',\n committer_email: 'jimmy@example.com',\n author_name: 'John',\n author_email: ", "end": 653, "score": 0.9999257326126099, "start": 636, "tag": "EMAIL", "value": "jimmy@example.com" }, { "context": "r_email: 'jimmy@example.com',\n author_name: 'John',\n author_email: 'john@example.com'\n }\n ", "end": 680, "score": 0.9997735619544983, "start": 676, "tag": "NAME", "value": "John" }, { "context": ",\n author_name: 'John',\n author_email: 'john@example.com'\n }\n ]\n\n Ember.run ->\n record = Travis.Co", "end": 720, "score": 0.9999285936355591, "start": 704, "tag": "EMAIL", "value": "john@example.com" } ]
assets/scripts/spec/unit/commit_spec.coffee
Acidburn0zzz/travis-web
0
record = null module "Travis.Commit", setup: -> teardown: -> Travis.Commit.resetData() test 'it recognizes when author is committer', -> Travis.Commit.load [ { id: 1, committer_name: 'Jimmy', committer_email: 'jimmy@example.com', author_name: 'Jimmy', author_email: 'jimmy@example.com' } ] Ember.run -> record = Travis.Commit.find 1 console.log(record.get('authorName')) equal(true, record.get('authorIsCommitter')) test 'it recognizes when author is not committer', -> Travis.Commit.load [ { id: 1, committer_name: 'Jimmy', committer_email: 'jimmy@example.com', author_name: 'John', author_email: 'john@example.com' } ] Ember.run -> record = Travis.Commit.find 1 console.log(record.get('authorName')) equal(false, record.get('authorIsCommitter'))
193655
record = null module "Travis.Commit", setup: -> teardown: -> Travis.Commit.resetData() test 'it recognizes when author is committer', -> Travis.Commit.load [ { id: 1, committer_name: '<NAME>', committer_email: '<EMAIL>', author_name: '<NAME>', author_email: '<EMAIL>' } ] Ember.run -> record = Travis.Commit.find 1 console.log(record.get('authorName')) equal(true, record.get('authorIsCommitter')) test 'it recognizes when author is not committer', -> Travis.Commit.load [ { id: 1, committer_name: '<NAME>', committer_email: '<EMAIL>', author_name: '<NAME>', author_email: '<EMAIL>' } ] Ember.run -> record = Travis.Commit.find 1 console.log(record.get('authorName')) equal(false, record.get('authorIsCommitter'))
true
record = null module "Travis.Commit", setup: -> teardown: -> Travis.Commit.resetData() test 'it recognizes when author is committer', -> Travis.Commit.load [ { id: 1, committer_name: 'PI:NAME:<NAME>END_PI', committer_email: 'PI:EMAIL:<EMAIL>END_PI', author_name: 'PI:NAME:<NAME>END_PI', author_email: 'PI:EMAIL:<EMAIL>END_PI' } ] Ember.run -> record = Travis.Commit.find 1 console.log(record.get('authorName')) equal(true, record.get('authorIsCommitter')) test 'it recognizes when author is not committer', -> Travis.Commit.load [ { id: 1, committer_name: 'PI:NAME:<NAME>END_PI', committer_email: 'PI:EMAIL:<EMAIL>END_PI', author_name: 'PI:NAME:<NAME>END_PI', author_email: 'PI:EMAIL:<EMAIL>END_PI' } ] Ember.run -> record = Travis.Commit.find 1 console.log(record.get('authorName')) equal(false, record.get('authorIsCommitter'))
[ { "context": "cess.nextTick ->\n if (!rec.partition)\n key = [rec.id]\n value = []\n \n for i in [0...rec.schema", "end": 474, "score": 0.9920859336853027, "start": 468, "tag": "KEY", "value": "rec.id" } ]
src/provider/foundationdb/activerecord/functions/save.coffee
frisb/formalize
2
fdb = require('fdb').apiVersion(200) deepak = require('deepak')(fdb) savePartioned = (tr, rec) -> # tr.set(rec.provider.dir.records.pack([rec.id]), deepak.pack('')) for d in rec.schema.destKeys if (d isnt 'id') val = rec.data(d) if (typeof(val) isnt 'undefined') tr.set(rec.provider.dir.records.pack([rec.id, d]), deepak.packValue(val)) save = (tr, rec, callback) -> #process.nextTick -> if (!rec.partition) key = [rec.id] value = [] for i in [0...rec.schema.destKeys.length - 1] v = rec.__d[i + 1] if typeof v isnt 'undefined' key.push(rec.schema.destKeys[i + 1]) value.push(deepak.packValue(v)) packedKey = rec.provider.dir.records.pack(key) packedValue = fdb.tuple.pack(value) rec.keySize = packedKey.length rec.valueSize = packedValue.length rec.partition ?= rec.keySize > 100 || rec.valueSize > 1024 if (!rec.partition) tr.set(packedKey, packedValue) else savePartioned(tr, rec) else savePartioned(tr, rec) rec.reset(true) rec.index(tr) rec.add(tr) callback(null) transactionalSave = fdb.transactional(save) module.exports = (tr, callback) -> if (typeof(tr) is 'function') callback = tr tr = null complete = (err) => callback(err, @) if callback #fdb.future.create (futureCb) => transactionalSave(tr || @provider.db, @, complete) #, callback
165916
fdb = require('fdb').apiVersion(200) deepak = require('deepak')(fdb) savePartioned = (tr, rec) -> # tr.set(rec.provider.dir.records.pack([rec.id]), deepak.pack('')) for d in rec.schema.destKeys if (d isnt 'id') val = rec.data(d) if (typeof(val) isnt 'undefined') tr.set(rec.provider.dir.records.pack([rec.id, d]), deepak.packValue(val)) save = (tr, rec, callback) -> #process.nextTick -> if (!rec.partition) key = [<KEY>] value = [] for i in [0...rec.schema.destKeys.length - 1] v = rec.__d[i + 1] if typeof v isnt 'undefined' key.push(rec.schema.destKeys[i + 1]) value.push(deepak.packValue(v)) packedKey = rec.provider.dir.records.pack(key) packedValue = fdb.tuple.pack(value) rec.keySize = packedKey.length rec.valueSize = packedValue.length rec.partition ?= rec.keySize > 100 || rec.valueSize > 1024 if (!rec.partition) tr.set(packedKey, packedValue) else savePartioned(tr, rec) else savePartioned(tr, rec) rec.reset(true) rec.index(tr) rec.add(tr) callback(null) transactionalSave = fdb.transactional(save) module.exports = (tr, callback) -> if (typeof(tr) is 'function') callback = tr tr = null complete = (err) => callback(err, @) if callback #fdb.future.create (futureCb) => transactionalSave(tr || @provider.db, @, complete) #, callback
true
fdb = require('fdb').apiVersion(200) deepak = require('deepak')(fdb) savePartioned = (tr, rec) -> # tr.set(rec.provider.dir.records.pack([rec.id]), deepak.pack('')) for d in rec.schema.destKeys if (d isnt 'id') val = rec.data(d) if (typeof(val) isnt 'undefined') tr.set(rec.provider.dir.records.pack([rec.id, d]), deepak.packValue(val)) save = (tr, rec, callback) -> #process.nextTick -> if (!rec.partition) key = [PI:KEY:<KEY>END_PI] value = [] for i in [0...rec.schema.destKeys.length - 1] v = rec.__d[i + 1] if typeof v isnt 'undefined' key.push(rec.schema.destKeys[i + 1]) value.push(deepak.packValue(v)) packedKey = rec.provider.dir.records.pack(key) packedValue = fdb.tuple.pack(value) rec.keySize = packedKey.length rec.valueSize = packedValue.length rec.partition ?= rec.keySize > 100 || rec.valueSize > 1024 if (!rec.partition) tr.set(packedKey, packedValue) else savePartioned(tr, rec) else savePartioned(tr, rec) rec.reset(true) rec.index(tr) rec.add(tr) callback(null) transactionalSave = fdb.transactional(save) module.exports = (tr, callback) -> if (typeof(tr) is 'function') callback = tr tr = null complete = (err) => callback(err, @) if callback #fdb.future.create (futureCb) => transactionalSave(tr || @provider.db, @, complete) #, callback
[ { "context": " getChunk: (x, y, z, create = false) ->\n key = \"#{x}|#{y}|#{z}\"\n chunk = @chunks[key]\n if !chunk? && create", "end": 3785, "score": 0.9992904663085938, "start": 3769, "tag": "KEY", "value": "\"#{x}|#{y}|#{z}\"" }, { "context": " chunk\n\n setChunk: (x, y, z, chunk) ->\n key = \"#{x}|#{y}|#{z}\"\n @chunks[key] = forceChunkType chunk\n @dirt", "end": 3986, "score": 0.9992501735687256, "start": 3970, "tag": "KEY", "value": "\"#{x}|#{y}|#{z}\"" }, { "context": ".makeVBO()\n\n markVBODirty: (x, y, z) ->\n key = \"#{x}|#{y}|#{z}\"\n if @cachedVBOs[key]\n @dirtyVBOs[key] = t", "end": 5572, "score": 0.9985456466674805, "start": 5556, "tag": "KEY", "value": "\"#{x}|#{y}|#{z}\"" }, { "context": "key] = true\n\n getChunkVBO: (x, y, z) ->\n key = \"#{x}|#{y}|#{z}\"\n chunk = @chunks[key]\n if !chunk\n retu", "end": 5681, "score": 0.9989808201789856, "start": 5665, "tag": "KEY", "value": "\"#{x}|#{y}|#{z}\"" } ]
src/world.coffee
TamaMcGlinn/webgl-meincraft
0
# Rendering size of a single block cube CUBE_SIZE = 1.0 # must be a power of two for the octree based fast raycasting # to work properly. CHUNK_SIZE = 32 # View distances are in chunks GENERATE_DISTANCE_X = 2 GENERATE_DISTANCE_Y = 2 GENERATE_DISTANCE_Z = 2 VIEW_DISTANCE_X = 4 VIEW_DISTANCE_Y = 4 VIEW_DISTANCE_Z = 4 # Currently blocks are one byte in size which limits them to 255 # different block types. BLOCK_TYPES = air: 0 grass01: 1 grass02: 2 grass03: 3 grass04: 4 stone: 10 granite: 11 rock01: 20 rock02: 21 water: 30 sand: 31 ChunkArray = Uint8Array parseKey = (key) -> [x, y, z] = key.split('|') [+x, +y, +z] div = (x, y) -> Math.floor x / y mod = (x, y) -> (x % y + y) % y makeBlockAtlas = -> builder = new webglmc.AtlasBuilder 1024, 1024, gridAdd: true for key, blockID of BLOCK_TYPES if blockID == 0 continue img = webglmc.resmgr.resources["blocks/#{key}"] builder.add blockID, img builder.makeAtlas mipmaps: true makeNewChunk = (chunkSize) -> forceChunkType = (chunk) -> if !chunk instanceof ChunkArray chunk = new ChunkArray chunk chunk class WorldRaycastResult constructor: (ray, hit, x, y, z, blockID) -> @x = x @y = y @z = z @blockID = blockID @ray = ray @hit = hit # Neighboring block switch @hit.side when 'top' then y += 1 when 'bottom' then y -= 1 when 'right' then x += 1 when 'left' then x -= 1 when 'near' then z += 1 when 'far' then z -= 1 @nx = x @ny = y @nz = z class World constructor: (seed = null) -> if seed == null seed = parseInt Math.random() * 10000000 @seed = seed @generator = new webglmc.WorldGenerator this @chunkSize = CHUNK_SIZE @vboBuildThreshold = +webglmc.getRuntimeParameter 'vboBuildThreshold', 0 @chunks = {} @cachedVBOs = {} @dirtyVBOs = {} @generatingChunks = 0 @shader = webglmc.resmgr.resources['shaders/block'] @sunColor = webglmc.floatColorFromHex '#F2F3DC' @sunDirection = vec3.create [0.7, 0.8, 1.0] @fogColor = webglmc.floatColorFromHex '#EDF0F0' @fogDensity = 0.012 @displays = chunkStats: webglmc.debugPanel.addDisplay 'Chunk stats' @atlas = makeBlockAtlas() @selectionTexture = webglmc.resmgr.resources.selection getBlock: (x, y, z) -> {chunkSize} = this cx = div x, chunkSize cy = div y, chunkSize cz = div z, chunkSize chunk = this.getChunk cx, cy, cz if !chunk? return 0 inX = mod x, chunkSize inY = mod y, chunkSize inZ = mod z, chunkSize chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] setBlock: (x, y, z, type) -> {chunkSize} = this cx = div x, chunkSize cy = div y, chunkSize cz = div z, chunkSize chunk = this.getChunk cx, cy, cz, true inX = mod x, chunkSize inY = mod y, chunkSize inZ = mod z, chunkSize oldType = chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] = type this.markVBODirty cx, cy, cz # in case we replace air with non air at an edge block we need # to mark the vbos nearly as dirty if ((type == 0) != (oldType == 0)) if inX == @chunkSize - 1 then this.markVBODirty cx + 1, cy, cz else if inX == 0 then this.markVBODirty cx - 1, cy, cz if inY == @chunkSize - 1 then this.markVBODirty cx, cy + 1, cz else if inY == 0 then this.markVBODirty cx, cy - 1, cz if inZ == @chunkSize - 1 then this.markVBODirty cx, cy, cz + 1 else if inZ == 0 then this.markVBODirty cx, cy, cz - 1 getChunk: (x, y, z, create = false) -> key = "#{x}|#{y}|#{z}" chunk = @chunks[key] if !chunk? && create @chunks[key] = chunk = new ChunkArray @chunkSize * @chunkSize * @chunkSize chunk setChunk: (x, y, z, chunk) -> key = "#{x}|#{y}|#{z}" @chunks[key] = forceChunkType chunk @dirtyVBOs[key] = true this.markVBODirty x + 1, y, z this.markVBODirty x - 1, y, z this.markVBODirty x, y + 1, z this.markVBODirty x, y - 1, z this.markVBODirty x, y, z + 1 this.markVBODirty x, y, z - 1 updateVBO: (x, y, z) -> chunk = this.getChunk x, y, z maker = new webglmc.CubeMaker CUBE_SIZE {chunkSize} = this blockTextures = @atlas.slices offX = x * chunkSize offY = y * chunkSize offZ = z * chunkSize isAir = (cx, cy, cz) => if cx >= 0 && cy >= 0 && cz >= 0 && cx < chunkSize && cy < chunkSize && cz < chunkSize return chunk[cx + cy * chunkSize + cz * chunkSize * chunkSize] == 0 return this.getBlock(offX + cx, offY + cy, offZ + cz) == 0 addSide = (side) => maker.addSide side, (offX + cx) * CUBE_SIZE, (offY + cy) * CUBE_SIZE, (offZ + cz) * CUBE_SIZE, blockTextures[blockID] for cz in [0...chunkSize] by 1 for cy in [0...chunkSize] by 1 for cx in [0...chunkSize] by 1 blockID = chunk[cx + cy * chunkSize + cz * chunkSize * chunkSize] if blockID == 0 continue if isAir cx - 1, cy, cz then addSide 'left' if isAir cx + 1, cy, cz then addSide 'right' if isAir cx, cy - 1, cz then addSide 'bottom' if isAir cx, cy + 1, cz then addSide 'top' if isAir cx, cy, cz - 1 then addSide 'far' if isAir cx, cy, cz + 1 then addSide 'near' maker.makeVBO() markVBODirty: (x, y, z) -> key = "#{x}|#{y}|#{z}" if @cachedVBOs[key] @dirtyVBOs[key] = true getChunkVBO: (x, y, z) -> key = "#{x}|#{y}|#{z}" chunk = @chunks[key] if !chunk return null vbo = @cachedVBOs[key] if (!vbo || @dirtyVBOs[key]) && this.generatingChunks <= @vboBuildThreshold vbo.destroy() if vbo vbo = this.updateVBO x, y, z delete @dirtyVBOs[key] @cachedVBOs[key] = vbo vbo iterVisibleVBOs: (callback) -> cameraPos = webglmc.engine.getCameraPos() chunkCount = 0 rv = [] chunkSize = CUBE_SIZE * @chunkSize [ccx, ccy, ccz] = this.chunkAtCameraPosition() for x in [ccx - VIEW_DISTANCE_X..ccx + VIEW_DISTANCE_X] by 1 for y in [ccy - VIEW_DISTANCE_Y..ccy + VIEW_DISTANCE_Y] by 1 for z in [ccz - VIEW_DISTANCE_Z..ccz + VIEW_DISTANCE_Z] by 1 vbo = this.getChunkVBO x, y, z if !vbo continue distance = vec3.create [x - ccx, y - ccy, z - ccz] rv.push vbo: vbo, distance: vec3.norm2 distance rv.sort (a, b) -> a.distance - b.distance @displays.chunkStats.setText "visibleVBOs=#{rv.length } generatingChunks=#{@generatingChunks}" for info in rv callback info.vbo chunkAtCameraPosition: -> [x, y, z] = webglmc.engine.getCameraPos() [Math.floor(x / CUBE_SIZE / @chunkSize + 0.5), Math.floor(y / CUBE_SIZE / @chunkSize + 0.5), Math.floor(z / CUBE_SIZE / @chunkSize + 0.5)] requestMissingChunks: -> [x, y, z] = this.chunkAtCameraPosition() for cx in [x - GENERATE_DISTANCE_X..x + GENERATE_DISTANCE_X] by 1 for cy in [y - GENERATE_DISTANCE_Y..y + GENERATE_DISTANCE_Y] by 1 for cz in [z - GENERATE_DISTANCE_Z..z + GENERATE_DISTANCE_Z] by 1 chunk = this.getChunk cx, cy, cz if !chunk this.requestChunk cx, cy, cz requestChunk: (x, y, z) -> # ensure chunk exists so that we don't request chunks # multiple times in requestMissingChunks this.getChunk x, y, z, true @generatingChunks++ @generator.generateChunk x, y, z setRequestedChunk: (x, y, z, chunk) -> @generatingChunks-- this.setChunk x, y, z, chunk iterChunksAroundCamera: (range, callback) -> if range == null for key, chunk of @chunks callback(chunk, parseKey(key)...) return [cx, cy, cz] = this.chunkAtCameraPosition() for x in [cx - range..cx + range] for y in [cy - range..cy + range] for z in [cz - range..cz + range] chunk = @chunks["#{x}|#{y}|#{z}"] if chunk callback(chunk, x, y, z) fastChunkRaycast: (chunk, cx, cy, cz, ray, callback) -> aabb = new webglmc.AABB() offX = @chunkSize * cx offY = @chunkSize * cy offZ = @chunkSize * cz walk = (inX, inY, inZ, inSize) => realX = offX + inX realY = offY + inY realZ = offZ + inZ actualInSize = CUBE_SIZE * inSize aabb.vec1[0] = realX * CUBE_SIZE aabb.vec1[1] = realY * CUBE_SIZE aabb.vec1[2] = realZ * CUBE_SIZE aabb.vec2[0] = aabb.vec1[0] + actualInSize aabb.vec2[1] = aabb.vec1[1] + actualInSize aabb.vec2[2] = aabb.vec1[2] + actualInSize hit = ray.intersectsAABB aabb, inSize != 1 if !hit return if inSize == 1 blockID = chunk[inX + inY * @chunkSize + inZ * @chunkSize * @chunkSize] if blockID result = new WorldRaycastResult ray, hit, realX, realY, realZ, blockID if !this.getBlock result.nx, result.ny, result.nz callback result return newInSize = inSize / 2 walk inX, inY, inZ, newInSize walk inX + newInSize, inY, inZ, newInSize walk inX, inY + newInSize, inZ, newInSize walk inX, inY, inZ + newInSize, newInSize walk inX + newInSize, inY + newInSize, inZ, newInSize walk inX, inY + newInSize, inZ + newInSize, newInSize walk inX + newInSize, inY, inZ + newInSize, newInSize walk inX + newInSize, inY + newInSize, inZ + newInSize, newInSize walk 0, 0, 0, @chunkSize performRayCast: (ray, range = null) -> aabb = new webglmc.AABB() chunkSize = CUBE_SIZE * @chunkSize bestResult = null this.iterChunksAroundCamera range, (chunk, cx, cy, cz) => aabb.vec1[0] = chunkSize * cx aabb.vec1[1] = chunkSize * cy aabb.vec1[2] = chunkSize * cz aabb.vec2[0] = aabb.vec1[0] + chunkSize aabb.vec2[1] = aabb.vec1[1] + chunkSize aabb.vec2[2] = aabb.vec1[2] + chunkSize if !ray.intersectsAABB aabb return this.fastChunkRaycast chunk, cx, cy, cz, ray, (result) => if !bestResult || bestResult.hit.distance > result.hit.distance bestResult = result bestResult pickBlockAtScreenPosition: (x, y, range = null) -> ray = webglmc.Ray.fromScreenSpaceNearToFar x, y this.performRayCast ray, range pickBlockAtScreenCenter: (range = null) -> {width, height} = webglmc.engine this.pickBlockAtScreenPosition width / 2, height / 2, range pickCloseBlockAtScreenCenter: -> rv = this.pickBlockAtScreenCenter 1 if rv && rv.hit.distance < 10 then rv else null drawBlockHighlight: (x, y, z, side) -> {gl} = webglmc.engine maker = new webglmc.CubeMaker CUBE_SIZE rx = x * CUBE_SIZE ry = y * CUBE_SIZE rz = z * CUBE_SIZE maker.addSide side, rx, ry, rz, @selectionTexture vbo = maker.makeVBO() webglmc.withContext [webglmc.disabledDepthTest, @shader, @selectionTexture], => vbo.draw() vbo.destroy() update: (dt) -> draw: -> {gl} = webglmc.engine webglmc.clear @fogColor webglmc.withContext [@shader, @atlas.texture], => @shader.uniform4fv "uSunColor", @sunColor @shader.uniform3fv "uSunDirection", @sunDirection @shader.uniform4fv "uFogColor", @fogColor @shader.uniform1f "uFogDensity", @fogDensity this.iterVisibleVBOs (vbo) => vbo.draw() publicInterface = self.webglmc ?= {} publicInterface.World = World publicInterface.BLOCK_TYPES = BLOCK_TYPES
64495
# Rendering size of a single block cube CUBE_SIZE = 1.0 # must be a power of two for the octree based fast raycasting # to work properly. CHUNK_SIZE = 32 # View distances are in chunks GENERATE_DISTANCE_X = 2 GENERATE_DISTANCE_Y = 2 GENERATE_DISTANCE_Z = 2 VIEW_DISTANCE_X = 4 VIEW_DISTANCE_Y = 4 VIEW_DISTANCE_Z = 4 # Currently blocks are one byte in size which limits them to 255 # different block types. BLOCK_TYPES = air: 0 grass01: 1 grass02: 2 grass03: 3 grass04: 4 stone: 10 granite: 11 rock01: 20 rock02: 21 water: 30 sand: 31 ChunkArray = Uint8Array parseKey = (key) -> [x, y, z] = key.split('|') [+x, +y, +z] div = (x, y) -> Math.floor x / y mod = (x, y) -> (x % y + y) % y makeBlockAtlas = -> builder = new webglmc.AtlasBuilder 1024, 1024, gridAdd: true for key, blockID of BLOCK_TYPES if blockID == 0 continue img = webglmc.resmgr.resources["blocks/#{key}"] builder.add blockID, img builder.makeAtlas mipmaps: true makeNewChunk = (chunkSize) -> forceChunkType = (chunk) -> if !chunk instanceof ChunkArray chunk = new ChunkArray chunk chunk class WorldRaycastResult constructor: (ray, hit, x, y, z, blockID) -> @x = x @y = y @z = z @blockID = blockID @ray = ray @hit = hit # Neighboring block switch @hit.side when 'top' then y += 1 when 'bottom' then y -= 1 when 'right' then x += 1 when 'left' then x -= 1 when 'near' then z += 1 when 'far' then z -= 1 @nx = x @ny = y @nz = z class World constructor: (seed = null) -> if seed == null seed = parseInt Math.random() * 10000000 @seed = seed @generator = new webglmc.WorldGenerator this @chunkSize = CHUNK_SIZE @vboBuildThreshold = +webglmc.getRuntimeParameter 'vboBuildThreshold', 0 @chunks = {} @cachedVBOs = {} @dirtyVBOs = {} @generatingChunks = 0 @shader = webglmc.resmgr.resources['shaders/block'] @sunColor = webglmc.floatColorFromHex '#F2F3DC' @sunDirection = vec3.create [0.7, 0.8, 1.0] @fogColor = webglmc.floatColorFromHex '#EDF0F0' @fogDensity = 0.012 @displays = chunkStats: webglmc.debugPanel.addDisplay 'Chunk stats' @atlas = makeBlockAtlas() @selectionTexture = webglmc.resmgr.resources.selection getBlock: (x, y, z) -> {chunkSize} = this cx = div x, chunkSize cy = div y, chunkSize cz = div z, chunkSize chunk = this.getChunk cx, cy, cz if !chunk? return 0 inX = mod x, chunkSize inY = mod y, chunkSize inZ = mod z, chunkSize chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] setBlock: (x, y, z, type) -> {chunkSize} = this cx = div x, chunkSize cy = div y, chunkSize cz = div z, chunkSize chunk = this.getChunk cx, cy, cz, true inX = mod x, chunkSize inY = mod y, chunkSize inZ = mod z, chunkSize oldType = chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] = type this.markVBODirty cx, cy, cz # in case we replace air with non air at an edge block we need # to mark the vbos nearly as dirty if ((type == 0) != (oldType == 0)) if inX == @chunkSize - 1 then this.markVBODirty cx + 1, cy, cz else if inX == 0 then this.markVBODirty cx - 1, cy, cz if inY == @chunkSize - 1 then this.markVBODirty cx, cy + 1, cz else if inY == 0 then this.markVBODirty cx, cy - 1, cz if inZ == @chunkSize - 1 then this.markVBODirty cx, cy, cz + 1 else if inZ == 0 then this.markVBODirty cx, cy, cz - 1 getChunk: (x, y, z, create = false) -> key = <KEY> chunk = @chunks[key] if !chunk? && create @chunks[key] = chunk = new ChunkArray @chunkSize * @chunkSize * @chunkSize chunk setChunk: (x, y, z, chunk) -> key = <KEY> @chunks[key] = forceChunkType chunk @dirtyVBOs[key] = true this.markVBODirty x + 1, y, z this.markVBODirty x - 1, y, z this.markVBODirty x, y + 1, z this.markVBODirty x, y - 1, z this.markVBODirty x, y, z + 1 this.markVBODirty x, y, z - 1 updateVBO: (x, y, z) -> chunk = this.getChunk x, y, z maker = new webglmc.CubeMaker CUBE_SIZE {chunkSize} = this blockTextures = @atlas.slices offX = x * chunkSize offY = y * chunkSize offZ = z * chunkSize isAir = (cx, cy, cz) => if cx >= 0 && cy >= 0 && cz >= 0 && cx < chunkSize && cy < chunkSize && cz < chunkSize return chunk[cx + cy * chunkSize + cz * chunkSize * chunkSize] == 0 return this.getBlock(offX + cx, offY + cy, offZ + cz) == 0 addSide = (side) => maker.addSide side, (offX + cx) * CUBE_SIZE, (offY + cy) * CUBE_SIZE, (offZ + cz) * CUBE_SIZE, blockTextures[blockID] for cz in [0...chunkSize] by 1 for cy in [0...chunkSize] by 1 for cx in [0...chunkSize] by 1 blockID = chunk[cx + cy * chunkSize + cz * chunkSize * chunkSize] if blockID == 0 continue if isAir cx - 1, cy, cz then addSide 'left' if isAir cx + 1, cy, cz then addSide 'right' if isAir cx, cy - 1, cz then addSide 'bottom' if isAir cx, cy + 1, cz then addSide 'top' if isAir cx, cy, cz - 1 then addSide 'far' if isAir cx, cy, cz + 1 then addSide 'near' maker.makeVBO() markVBODirty: (x, y, z) -> key = <KEY> if @cachedVBOs[key] @dirtyVBOs[key] = true getChunkVBO: (x, y, z) -> key = <KEY> chunk = @chunks[key] if !chunk return null vbo = @cachedVBOs[key] if (!vbo || @dirtyVBOs[key]) && this.generatingChunks <= @vboBuildThreshold vbo.destroy() if vbo vbo = this.updateVBO x, y, z delete @dirtyVBOs[key] @cachedVBOs[key] = vbo vbo iterVisibleVBOs: (callback) -> cameraPos = webglmc.engine.getCameraPos() chunkCount = 0 rv = [] chunkSize = CUBE_SIZE * @chunkSize [ccx, ccy, ccz] = this.chunkAtCameraPosition() for x in [ccx - VIEW_DISTANCE_X..ccx + VIEW_DISTANCE_X] by 1 for y in [ccy - VIEW_DISTANCE_Y..ccy + VIEW_DISTANCE_Y] by 1 for z in [ccz - VIEW_DISTANCE_Z..ccz + VIEW_DISTANCE_Z] by 1 vbo = this.getChunkVBO x, y, z if !vbo continue distance = vec3.create [x - ccx, y - ccy, z - ccz] rv.push vbo: vbo, distance: vec3.norm2 distance rv.sort (a, b) -> a.distance - b.distance @displays.chunkStats.setText "visibleVBOs=#{rv.length } generatingChunks=#{@generatingChunks}" for info in rv callback info.vbo chunkAtCameraPosition: -> [x, y, z] = webglmc.engine.getCameraPos() [Math.floor(x / CUBE_SIZE / @chunkSize + 0.5), Math.floor(y / CUBE_SIZE / @chunkSize + 0.5), Math.floor(z / CUBE_SIZE / @chunkSize + 0.5)] requestMissingChunks: -> [x, y, z] = this.chunkAtCameraPosition() for cx in [x - GENERATE_DISTANCE_X..x + GENERATE_DISTANCE_X] by 1 for cy in [y - GENERATE_DISTANCE_Y..y + GENERATE_DISTANCE_Y] by 1 for cz in [z - GENERATE_DISTANCE_Z..z + GENERATE_DISTANCE_Z] by 1 chunk = this.getChunk cx, cy, cz if !chunk this.requestChunk cx, cy, cz requestChunk: (x, y, z) -> # ensure chunk exists so that we don't request chunks # multiple times in requestMissingChunks this.getChunk x, y, z, true @generatingChunks++ @generator.generateChunk x, y, z setRequestedChunk: (x, y, z, chunk) -> @generatingChunks-- this.setChunk x, y, z, chunk iterChunksAroundCamera: (range, callback) -> if range == null for key, chunk of @chunks callback(chunk, parseKey(key)...) return [cx, cy, cz] = this.chunkAtCameraPosition() for x in [cx - range..cx + range] for y in [cy - range..cy + range] for z in [cz - range..cz + range] chunk = @chunks["#{x}|#{y}|#{z}"] if chunk callback(chunk, x, y, z) fastChunkRaycast: (chunk, cx, cy, cz, ray, callback) -> aabb = new webglmc.AABB() offX = @chunkSize * cx offY = @chunkSize * cy offZ = @chunkSize * cz walk = (inX, inY, inZ, inSize) => realX = offX + inX realY = offY + inY realZ = offZ + inZ actualInSize = CUBE_SIZE * inSize aabb.vec1[0] = realX * CUBE_SIZE aabb.vec1[1] = realY * CUBE_SIZE aabb.vec1[2] = realZ * CUBE_SIZE aabb.vec2[0] = aabb.vec1[0] + actualInSize aabb.vec2[1] = aabb.vec1[1] + actualInSize aabb.vec2[2] = aabb.vec1[2] + actualInSize hit = ray.intersectsAABB aabb, inSize != 1 if !hit return if inSize == 1 blockID = chunk[inX + inY * @chunkSize + inZ * @chunkSize * @chunkSize] if blockID result = new WorldRaycastResult ray, hit, realX, realY, realZ, blockID if !this.getBlock result.nx, result.ny, result.nz callback result return newInSize = inSize / 2 walk inX, inY, inZ, newInSize walk inX + newInSize, inY, inZ, newInSize walk inX, inY + newInSize, inZ, newInSize walk inX, inY, inZ + newInSize, newInSize walk inX + newInSize, inY + newInSize, inZ, newInSize walk inX, inY + newInSize, inZ + newInSize, newInSize walk inX + newInSize, inY, inZ + newInSize, newInSize walk inX + newInSize, inY + newInSize, inZ + newInSize, newInSize walk 0, 0, 0, @chunkSize performRayCast: (ray, range = null) -> aabb = new webglmc.AABB() chunkSize = CUBE_SIZE * @chunkSize bestResult = null this.iterChunksAroundCamera range, (chunk, cx, cy, cz) => aabb.vec1[0] = chunkSize * cx aabb.vec1[1] = chunkSize * cy aabb.vec1[2] = chunkSize * cz aabb.vec2[0] = aabb.vec1[0] + chunkSize aabb.vec2[1] = aabb.vec1[1] + chunkSize aabb.vec2[2] = aabb.vec1[2] + chunkSize if !ray.intersectsAABB aabb return this.fastChunkRaycast chunk, cx, cy, cz, ray, (result) => if !bestResult || bestResult.hit.distance > result.hit.distance bestResult = result bestResult pickBlockAtScreenPosition: (x, y, range = null) -> ray = webglmc.Ray.fromScreenSpaceNearToFar x, y this.performRayCast ray, range pickBlockAtScreenCenter: (range = null) -> {width, height} = webglmc.engine this.pickBlockAtScreenPosition width / 2, height / 2, range pickCloseBlockAtScreenCenter: -> rv = this.pickBlockAtScreenCenter 1 if rv && rv.hit.distance < 10 then rv else null drawBlockHighlight: (x, y, z, side) -> {gl} = webglmc.engine maker = new webglmc.CubeMaker CUBE_SIZE rx = x * CUBE_SIZE ry = y * CUBE_SIZE rz = z * CUBE_SIZE maker.addSide side, rx, ry, rz, @selectionTexture vbo = maker.makeVBO() webglmc.withContext [webglmc.disabledDepthTest, @shader, @selectionTexture], => vbo.draw() vbo.destroy() update: (dt) -> draw: -> {gl} = webglmc.engine webglmc.clear @fogColor webglmc.withContext [@shader, @atlas.texture], => @shader.uniform4fv "uSunColor", @sunColor @shader.uniform3fv "uSunDirection", @sunDirection @shader.uniform4fv "uFogColor", @fogColor @shader.uniform1f "uFogDensity", @fogDensity this.iterVisibleVBOs (vbo) => vbo.draw() publicInterface = self.webglmc ?= {} publicInterface.World = World publicInterface.BLOCK_TYPES = BLOCK_TYPES
true
# Rendering size of a single block cube CUBE_SIZE = 1.0 # must be a power of two for the octree based fast raycasting # to work properly. CHUNK_SIZE = 32 # View distances are in chunks GENERATE_DISTANCE_X = 2 GENERATE_DISTANCE_Y = 2 GENERATE_DISTANCE_Z = 2 VIEW_DISTANCE_X = 4 VIEW_DISTANCE_Y = 4 VIEW_DISTANCE_Z = 4 # Currently blocks are one byte in size which limits them to 255 # different block types. BLOCK_TYPES = air: 0 grass01: 1 grass02: 2 grass03: 3 grass04: 4 stone: 10 granite: 11 rock01: 20 rock02: 21 water: 30 sand: 31 ChunkArray = Uint8Array parseKey = (key) -> [x, y, z] = key.split('|') [+x, +y, +z] div = (x, y) -> Math.floor x / y mod = (x, y) -> (x % y + y) % y makeBlockAtlas = -> builder = new webglmc.AtlasBuilder 1024, 1024, gridAdd: true for key, blockID of BLOCK_TYPES if blockID == 0 continue img = webglmc.resmgr.resources["blocks/#{key}"] builder.add blockID, img builder.makeAtlas mipmaps: true makeNewChunk = (chunkSize) -> forceChunkType = (chunk) -> if !chunk instanceof ChunkArray chunk = new ChunkArray chunk chunk class WorldRaycastResult constructor: (ray, hit, x, y, z, blockID) -> @x = x @y = y @z = z @blockID = blockID @ray = ray @hit = hit # Neighboring block switch @hit.side when 'top' then y += 1 when 'bottom' then y -= 1 when 'right' then x += 1 when 'left' then x -= 1 when 'near' then z += 1 when 'far' then z -= 1 @nx = x @ny = y @nz = z class World constructor: (seed = null) -> if seed == null seed = parseInt Math.random() * 10000000 @seed = seed @generator = new webglmc.WorldGenerator this @chunkSize = CHUNK_SIZE @vboBuildThreshold = +webglmc.getRuntimeParameter 'vboBuildThreshold', 0 @chunks = {} @cachedVBOs = {} @dirtyVBOs = {} @generatingChunks = 0 @shader = webglmc.resmgr.resources['shaders/block'] @sunColor = webglmc.floatColorFromHex '#F2F3DC' @sunDirection = vec3.create [0.7, 0.8, 1.0] @fogColor = webglmc.floatColorFromHex '#EDF0F0' @fogDensity = 0.012 @displays = chunkStats: webglmc.debugPanel.addDisplay 'Chunk stats' @atlas = makeBlockAtlas() @selectionTexture = webglmc.resmgr.resources.selection getBlock: (x, y, z) -> {chunkSize} = this cx = div x, chunkSize cy = div y, chunkSize cz = div z, chunkSize chunk = this.getChunk cx, cy, cz if !chunk? return 0 inX = mod x, chunkSize inY = mod y, chunkSize inZ = mod z, chunkSize chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] setBlock: (x, y, z, type) -> {chunkSize} = this cx = div x, chunkSize cy = div y, chunkSize cz = div z, chunkSize chunk = this.getChunk cx, cy, cz, true inX = mod x, chunkSize inY = mod y, chunkSize inZ = mod z, chunkSize oldType = chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] chunk[inX + inY * chunkSize + inZ * chunkSize * chunkSize] = type this.markVBODirty cx, cy, cz # in case we replace air with non air at an edge block we need # to mark the vbos nearly as dirty if ((type == 0) != (oldType == 0)) if inX == @chunkSize - 1 then this.markVBODirty cx + 1, cy, cz else if inX == 0 then this.markVBODirty cx - 1, cy, cz if inY == @chunkSize - 1 then this.markVBODirty cx, cy + 1, cz else if inY == 0 then this.markVBODirty cx, cy - 1, cz if inZ == @chunkSize - 1 then this.markVBODirty cx, cy, cz + 1 else if inZ == 0 then this.markVBODirty cx, cy, cz - 1 getChunk: (x, y, z, create = false) -> key = PI:KEY:<KEY>END_PI chunk = @chunks[key] if !chunk? && create @chunks[key] = chunk = new ChunkArray @chunkSize * @chunkSize * @chunkSize chunk setChunk: (x, y, z, chunk) -> key = PI:KEY:<KEY>END_PI @chunks[key] = forceChunkType chunk @dirtyVBOs[key] = true this.markVBODirty x + 1, y, z this.markVBODirty x - 1, y, z this.markVBODirty x, y + 1, z this.markVBODirty x, y - 1, z this.markVBODirty x, y, z + 1 this.markVBODirty x, y, z - 1 updateVBO: (x, y, z) -> chunk = this.getChunk x, y, z maker = new webglmc.CubeMaker CUBE_SIZE {chunkSize} = this blockTextures = @atlas.slices offX = x * chunkSize offY = y * chunkSize offZ = z * chunkSize isAir = (cx, cy, cz) => if cx >= 0 && cy >= 0 && cz >= 0 && cx < chunkSize && cy < chunkSize && cz < chunkSize return chunk[cx + cy * chunkSize + cz * chunkSize * chunkSize] == 0 return this.getBlock(offX + cx, offY + cy, offZ + cz) == 0 addSide = (side) => maker.addSide side, (offX + cx) * CUBE_SIZE, (offY + cy) * CUBE_SIZE, (offZ + cz) * CUBE_SIZE, blockTextures[blockID] for cz in [0...chunkSize] by 1 for cy in [0...chunkSize] by 1 for cx in [0...chunkSize] by 1 blockID = chunk[cx + cy * chunkSize + cz * chunkSize * chunkSize] if blockID == 0 continue if isAir cx - 1, cy, cz then addSide 'left' if isAir cx + 1, cy, cz then addSide 'right' if isAir cx, cy - 1, cz then addSide 'bottom' if isAir cx, cy + 1, cz then addSide 'top' if isAir cx, cy, cz - 1 then addSide 'far' if isAir cx, cy, cz + 1 then addSide 'near' maker.makeVBO() markVBODirty: (x, y, z) -> key = PI:KEY:<KEY>END_PI if @cachedVBOs[key] @dirtyVBOs[key] = true getChunkVBO: (x, y, z) -> key = PI:KEY:<KEY>END_PI chunk = @chunks[key] if !chunk return null vbo = @cachedVBOs[key] if (!vbo || @dirtyVBOs[key]) && this.generatingChunks <= @vboBuildThreshold vbo.destroy() if vbo vbo = this.updateVBO x, y, z delete @dirtyVBOs[key] @cachedVBOs[key] = vbo vbo iterVisibleVBOs: (callback) -> cameraPos = webglmc.engine.getCameraPos() chunkCount = 0 rv = [] chunkSize = CUBE_SIZE * @chunkSize [ccx, ccy, ccz] = this.chunkAtCameraPosition() for x in [ccx - VIEW_DISTANCE_X..ccx + VIEW_DISTANCE_X] by 1 for y in [ccy - VIEW_DISTANCE_Y..ccy + VIEW_DISTANCE_Y] by 1 for z in [ccz - VIEW_DISTANCE_Z..ccz + VIEW_DISTANCE_Z] by 1 vbo = this.getChunkVBO x, y, z if !vbo continue distance = vec3.create [x - ccx, y - ccy, z - ccz] rv.push vbo: vbo, distance: vec3.norm2 distance rv.sort (a, b) -> a.distance - b.distance @displays.chunkStats.setText "visibleVBOs=#{rv.length } generatingChunks=#{@generatingChunks}" for info in rv callback info.vbo chunkAtCameraPosition: -> [x, y, z] = webglmc.engine.getCameraPos() [Math.floor(x / CUBE_SIZE / @chunkSize + 0.5), Math.floor(y / CUBE_SIZE / @chunkSize + 0.5), Math.floor(z / CUBE_SIZE / @chunkSize + 0.5)] requestMissingChunks: -> [x, y, z] = this.chunkAtCameraPosition() for cx in [x - GENERATE_DISTANCE_X..x + GENERATE_DISTANCE_X] by 1 for cy in [y - GENERATE_DISTANCE_Y..y + GENERATE_DISTANCE_Y] by 1 for cz in [z - GENERATE_DISTANCE_Z..z + GENERATE_DISTANCE_Z] by 1 chunk = this.getChunk cx, cy, cz if !chunk this.requestChunk cx, cy, cz requestChunk: (x, y, z) -> # ensure chunk exists so that we don't request chunks # multiple times in requestMissingChunks this.getChunk x, y, z, true @generatingChunks++ @generator.generateChunk x, y, z setRequestedChunk: (x, y, z, chunk) -> @generatingChunks-- this.setChunk x, y, z, chunk iterChunksAroundCamera: (range, callback) -> if range == null for key, chunk of @chunks callback(chunk, parseKey(key)...) return [cx, cy, cz] = this.chunkAtCameraPosition() for x in [cx - range..cx + range] for y in [cy - range..cy + range] for z in [cz - range..cz + range] chunk = @chunks["#{x}|#{y}|#{z}"] if chunk callback(chunk, x, y, z) fastChunkRaycast: (chunk, cx, cy, cz, ray, callback) -> aabb = new webglmc.AABB() offX = @chunkSize * cx offY = @chunkSize * cy offZ = @chunkSize * cz walk = (inX, inY, inZ, inSize) => realX = offX + inX realY = offY + inY realZ = offZ + inZ actualInSize = CUBE_SIZE * inSize aabb.vec1[0] = realX * CUBE_SIZE aabb.vec1[1] = realY * CUBE_SIZE aabb.vec1[2] = realZ * CUBE_SIZE aabb.vec2[0] = aabb.vec1[0] + actualInSize aabb.vec2[1] = aabb.vec1[1] + actualInSize aabb.vec2[2] = aabb.vec1[2] + actualInSize hit = ray.intersectsAABB aabb, inSize != 1 if !hit return if inSize == 1 blockID = chunk[inX + inY * @chunkSize + inZ * @chunkSize * @chunkSize] if blockID result = new WorldRaycastResult ray, hit, realX, realY, realZ, blockID if !this.getBlock result.nx, result.ny, result.nz callback result return newInSize = inSize / 2 walk inX, inY, inZ, newInSize walk inX + newInSize, inY, inZ, newInSize walk inX, inY + newInSize, inZ, newInSize walk inX, inY, inZ + newInSize, newInSize walk inX + newInSize, inY + newInSize, inZ, newInSize walk inX, inY + newInSize, inZ + newInSize, newInSize walk inX + newInSize, inY, inZ + newInSize, newInSize walk inX + newInSize, inY + newInSize, inZ + newInSize, newInSize walk 0, 0, 0, @chunkSize performRayCast: (ray, range = null) -> aabb = new webglmc.AABB() chunkSize = CUBE_SIZE * @chunkSize bestResult = null this.iterChunksAroundCamera range, (chunk, cx, cy, cz) => aabb.vec1[0] = chunkSize * cx aabb.vec1[1] = chunkSize * cy aabb.vec1[2] = chunkSize * cz aabb.vec2[0] = aabb.vec1[0] + chunkSize aabb.vec2[1] = aabb.vec1[1] + chunkSize aabb.vec2[2] = aabb.vec1[2] + chunkSize if !ray.intersectsAABB aabb return this.fastChunkRaycast chunk, cx, cy, cz, ray, (result) => if !bestResult || bestResult.hit.distance > result.hit.distance bestResult = result bestResult pickBlockAtScreenPosition: (x, y, range = null) -> ray = webglmc.Ray.fromScreenSpaceNearToFar x, y this.performRayCast ray, range pickBlockAtScreenCenter: (range = null) -> {width, height} = webglmc.engine this.pickBlockAtScreenPosition width / 2, height / 2, range pickCloseBlockAtScreenCenter: -> rv = this.pickBlockAtScreenCenter 1 if rv && rv.hit.distance < 10 then rv else null drawBlockHighlight: (x, y, z, side) -> {gl} = webglmc.engine maker = new webglmc.CubeMaker CUBE_SIZE rx = x * CUBE_SIZE ry = y * CUBE_SIZE rz = z * CUBE_SIZE maker.addSide side, rx, ry, rz, @selectionTexture vbo = maker.makeVBO() webglmc.withContext [webglmc.disabledDepthTest, @shader, @selectionTexture], => vbo.draw() vbo.destroy() update: (dt) -> draw: -> {gl} = webglmc.engine webglmc.clear @fogColor webglmc.withContext [@shader, @atlas.texture], => @shader.uniform4fv "uSunColor", @sunColor @shader.uniform3fv "uSunDirection", @sunDirection @shader.uniform4fv "uFogColor", @fogColor @shader.uniform1f "uFogDensity", @fogDensity this.iterVisibleVBOs (vbo) => vbo.draw() publicInterface = self.webglmc ?= {} publicInterface.World = World publicInterface.BLOCK_TYPES = BLOCK_TYPES
[ { "context": "## MCSHOPDEX by LAKEN HAFNER\n## (c) 2017\n## AVAILABLE UNDER THE MIT LICENSE\n##", "end": 28, "score": 0.9998864531517029, "start": 16, "tag": "NAME", "value": "LAKEN HAFNER" }, { "context": "T LICENSE\n## PROJECT HOMEPAGE: HTTPS://GITLAB.COM/LAKEN/MCSHOPDEX/\n\n# creating a few variables, setting t", "end": 121, "score": 0.9997022151947021, "start": 116, "tag": "USERNAME", "value": "LAKEN" } ]
js/shopdex.coffee
FrozenBeard/MCShop
2
## MCSHOPDEX by LAKEN HAFNER ## (c) 2017 ## AVAILABLE UNDER THE MIT LICENSE ## PROJECT HOMEPAGE: HTTPS://GITLAB.COM/LAKEN/MCSHOPDEX/ # creating a few variables, setting them to null for now symbol = null dynmapURL = null # on page load, starts all other functions $ -> # loading our config $.getJSON 'config.json', (configData) -> console.log "Recieved Config..." # assigning each key's value in the config to a variable name = configData.shopdexName ip = configData.serverIP json = configData.shopData dynmapURL = configData.dynmapURL itemApi = configData.itemAPI symbol = configData.currencySymbol # filling blanks spots with the variables we set $('#shopdexName').text name $('#shopdexIp').text ip # now we're going to grab data about the server... getServerData ip # going to load item api now... idItems itemApi, (itemNames) -> # while we are still dealing with the config, we need to load the shopdata loadShopData json, itemNames getServerData = (ip) -> # using https://mcapi.ca/ # first going to check if the server specified is online or not... $.getJSON 'https://mcapi.ca/query/' + ip + '/info', (serverData) -> status = serverData.status version = serverData.version if status is true # because it defaults to red text saying `Offline` we are removing the red text class, adding the green one, and replacing text contents $('#shopdexStatusColor').removeClass 'red-text' $('#shopdexStatusColor').addClass 'green-text' $('#shopdexStatus').text 'Online' $('#shopdexVersion').text version # changing displayed picture to the official server one... $('#shopdexImage').attr 'src', 'https://mcapi.ca/query/' + ip + '/icon' console.log "Loaded Config!" idItems = (itemApi, callback) -> $.getJSON itemApi, (items) -> console.log "Recieved Item JSON..." itemIds = {} for itemData, itemDataVal of items # here we're turning the array of objects into an easier format.. plain 'ol array itemId = itemDataVal.type + ":" + itemDataVal.meta itemIds[itemId] = itemDataVal.name.toLowerCase() console.log "Converted Item JSON!" console.log itemIds callback itemIds shops = [] loadShopData = (json, itemNames) -> $.getJSON json, (jsonData) -> console.log "Recieved Shop JSON..." # because of the way the json is structured, we have to nest all of these loops # i know it's horrible validSigns = ["buy", "sell", "ibuy", "isell"] for root, rootVal of jsonData if rootVal.invItems.length < 2 # now we're checking for if there are multiple items sold in a shop # less than 2 objects in InvItems means that it isn't a multi-item shop multiShop = false else multiShop = true shopGroup = [] for invItems, invItemsVal of rootVal.invItems if rootVal.signType in validSigns # looping through the invitems to grab the name and amount of each item sold @ the same shop # atm we only grab those 2, so any meta values (such as enchantments) are not recorded there.. might fix in the future shopGroupItemId = invItemsVal.type + ":" + invItemsVal.durability shopGroup.push invItemsVal.amount + " " + itemNames[shopGroupItemId] multiShopItems = shopGroup.join(', ') for invItems, invItemsVal of rootVal.invItems if rootVal.signType in validSigns # this makes it much easier to work with the data, can go through all this only once instead of during every damn search shop = {} shop.itemId = invItemsVal.type + ":" + invItemsVal.durability shop.name = itemNames[shop.itemId] shop.type = rootVal.signType shop.price = rootVal.signPrice shop.amount = invItemsVal.amount shop.owner = rootVal.ownerName shop.owner = "Server" if shop.type is "ibuy" or shop.type is "isell" shop.stock = rootVal.invInStock shop.stock = "infinite" if shop.type is "ibuy" or shop.type is "isell" shop.world = rootVal.locWorld shop.x = rootVal.locX shop.y = rootVal.locY shop.z = rootVal.locZ shop.enchants = null; if invItemsVal.meta if invItemsVal.meta.enchantments enchantList = [] for enchant, level of invItemsVal.meta.enchantments # turning the enchants into a more familiar format... enchantList.push ENCHANTS[enchant] + " " + NUMERALS[level] # if multiple enchantments, we are joining them together with a comma and a space ;) shop.enchants = enchantList.join(', ') shop.multi = multiShopItems if multiShop isnt false if shop.multi or shop.enchants shop.hasMeta = true shops.push shop shops = shops.sort (a, b) -> # defaulting to sorting by price, in the future this may be a search option.. pricePerA = a.price / a.amount pricePerB = b.price / b.amount pricePerA - pricePerB console.log shops console.log "Loaded Shops!" $('#loadingSpinner').hide() $('#itemSearchBox').removeAttr 'disabled' $('#playerSearchBox').removeAttr 'disabled' $('#itemSearchBox').on 'input', () -> # this function searches the data based on itemname provided on each value change in the input $('#results').html "" $('#playerSearchBox').val "" search = $('#itemSearchBox').val().toLowerCase() $('#resultsLabel').show() $('#query').text search for searchShop, shop of shops if shop.enchants enchantSearch = shop.enchants.toLowerCase() if shop.name and shop.name.includes(search) or enchantSearch.includes(search) generateResults shop else if shop.name and shop.name.includes(search) generateResults shop $('#playerSearchBox').on 'input', () -> # this function searches the data based on playername provided on each value change in the input $('#results').html "" $('#itemSearchBox').val "" search = $('#playerSearchBox').val().toLowerCase() $('#resultsLabel').show() $('#query').text search for searchShop, shop of shops shopOwner = shop.owner.toLowerCase() if shopOwner and shopOwner.includes(search) generateResults shop generateResults = (shop) -> # this function generates results from the shop given to it if shop.stock is true color = 'green-text' inStock = 'In Stock' else if shop.stock is "infinite" color = 'green-text' inStock = '&infin; Stock' else color = 'red-text' inStock = 'No Stock' shopImage = shop.itemId.replace ':', '-' playerHead = "https://mcapi.ca/avatar/" + shop.owner if shop.owner is "Server" playerHead = "https://mcapi.ca/query/" + $('#shopdexIp').text() + "/icon/" if shop.enchants enchantDisplay = "<p>Enchanted with<em> " + shop.enchants + "</em></p>" else enchantDisplay = "" if shop.multi multiDisplay = "<p>Includes<em> " + shop.multi + "</em></p>" else multiDisplay = "" if shop.hasMeta is true $('#results').append """ <div class="result"> <img class="result-image" src="img/#{ shopImage }.png" alt="#{ shop.name }"> <div class="result-info"> <p><strong>#{ shop.type }</strong> #{ shop.amount } #{ shop.name } for #{ symbol }#{ shop.price }</p> <p><span class="#{ color }">#{ inStock }</span> @ <a href="#{ dynmapURL + "?worldname=" + shop.world + "&mapname=surface&zoom=20&x=" + shop.x + "&y=" + shop.y + "&z=" + shop.z }" target="_blank">x#{ shop.x }, y#{ shop.y }, z#{ shop.z }</a> <p><i class="icon-globe"></i> #{ shop.world } &nbsp; <button class="show-on-mobile show-more-info">More Details</button><small class="show-on-desktop">Hover to See More Details</small></p> <div class="result-player"><img src="#{ playerHead }" width="30px" height="30px"><p> #{ shop.owner }</p></div> <div class="result-more-info"> #{ enchantDisplay } #{ multiDisplay } </div> </div> </div> """ else $('#results').append """ <div class="result"> <img class="result-image" src="img/#{ shopImage }.png" alt="#{ shop.name }"> <div class="result-info"> <p><strong>#{ shop.type }</strong> #{ shop.amount } #{ shop.name } for #{ symbol }#{ shop.price }</p> <p><span class="#{ color }">#{ inStock }</span> @ <a href="#{ dynmapURL + "?worldname=" + shop.world + "&mapname=surface&zoom=20&x=" + shop.x + "&y=" + shop.y + "&z=" + shop.z }" target="_blank">x#{ shop.x }, y#{ shop.y }, z#{ shop.z }</a> <p><i class="icon-globe"></i> #{ shop.world }</p> <div class="result-player"><img src="#{ playerHead }" width="30px" height="30px"><p> #{ shop.owner }</p></div> </div> </div> """ # enchant and numerals clean names below ENCHANTS = 'ARROW_DAMAGE': 'Power' 'ARROW_FIRE': 'Flame' 'ARROW_INFINITE': 'Infinity' 'ARROW_KNOCKBACK': 'Punch' 'BINDING_CURSE': 'Curse of Binding' 'DAMAGE_ALL': 'Sharpness' 'DAMAGE_ARTHROPODS': 'Bane of Arthropods' 'DAMAGE_UNDEAD': 'Smite' 'DEPTH_STRIDER': 'Depth Strider' 'DIG_SPEED': 'Efficiency' 'DURABILITY': 'Unbreaking' 'FIRE_ASPECT': 'Fire Aspect' 'FROST_WALKER': 'Frost Walker' 'KNOCKBACK': 'Knockback' 'LOOT_BONUS_BLOCKS': 'Fortune' 'LOOT_BONUS_MOBS': 'Looting' 'LUCK': 'Luck of the Sea' 'LURE': 'Lure' 'MENDING': 'Mending' 'OXYGEN': 'Respiration' 'PROTECTION_ENVIRONMENTAL': 'Protection' 'PROTECTION_EXPLOSIONS': 'Blast Protection' 'PROTECTION_FALL': 'Feather Falling' 'PROTECTION_FIRE': 'Fire Protection' 'PROTECTION_PROJECTILE': 'Projectile Protection' 'SILK_TOUCH': 'Silk Touch' 'SWEEPING': 'Sweeping Edge' 'THORNS': 'Thorns' 'VANISHING_CURSE': 'Curse of Vanishing' 'WATER_WORKER': 'Aqua Affinity' NUMERALS = '1': 'I' '2': 'II' '3': 'III' '4': 'IV' '5': 'V'
180306
## MCSHOPDEX by <NAME> ## (c) 2017 ## AVAILABLE UNDER THE MIT LICENSE ## PROJECT HOMEPAGE: HTTPS://GITLAB.COM/LAKEN/MCSHOPDEX/ # creating a few variables, setting them to null for now symbol = null dynmapURL = null # on page load, starts all other functions $ -> # loading our config $.getJSON 'config.json', (configData) -> console.log "Recieved Config..." # assigning each key's value in the config to a variable name = configData.shopdexName ip = configData.serverIP json = configData.shopData dynmapURL = configData.dynmapURL itemApi = configData.itemAPI symbol = configData.currencySymbol # filling blanks spots with the variables we set $('#shopdexName').text name $('#shopdexIp').text ip # now we're going to grab data about the server... getServerData ip # going to load item api now... idItems itemApi, (itemNames) -> # while we are still dealing with the config, we need to load the shopdata loadShopData json, itemNames getServerData = (ip) -> # using https://mcapi.ca/ # first going to check if the server specified is online or not... $.getJSON 'https://mcapi.ca/query/' + ip + '/info', (serverData) -> status = serverData.status version = serverData.version if status is true # because it defaults to red text saying `Offline` we are removing the red text class, adding the green one, and replacing text contents $('#shopdexStatusColor').removeClass 'red-text' $('#shopdexStatusColor').addClass 'green-text' $('#shopdexStatus').text 'Online' $('#shopdexVersion').text version # changing displayed picture to the official server one... $('#shopdexImage').attr 'src', 'https://mcapi.ca/query/' + ip + '/icon' console.log "Loaded Config!" idItems = (itemApi, callback) -> $.getJSON itemApi, (items) -> console.log "Recieved Item JSON..." itemIds = {} for itemData, itemDataVal of items # here we're turning the array of objects into an easier format.. plain 'ol array itemId = itemDataVal.type + ":" + itemDataVal.meta itemIds[itemId] = itemDataVal.name.toLowerCase() console.log "Converted Item JSON!" console.log itemIds callback itemIds shops = [] loadShopData = (json, itemNames) -> $.getJSON json, (jsonData) -> console.log "Recieved Shop JSON..." # because of the way the json is structured, we have to nest all of these loops # i know it's horrible validSigns = ["buy", "sell", "ibuy", "isell"] for root, rootVal of jsonData if rootVal.invItems.length < 2 # now we're checking for if there are multiple items sold in a shop # less than 2 objects in InvItems means that it isn't a multi-item shop multiShop = false else multiShop = true shopGroup = [] for invItems, invItemsVal of rootVal.invItems if rootVal.signType in validSigns # looping through the invitems to grab the name and amount of each item sold @ the same shop # atm we only grab those 2, so any meta values (such as enchantments) are not recorded there.. might fix in the future shopGroupItemId = invItemsVal.type + ":" + invItemsVal.durability shopGroup.push invItemsVal.amount + " " + itemNames[shopGroupItemId] multiShopItems = shopGroup.join(', ') for invItems, invItemsVal of rootVal.invItems if rootVal.signType in validSigns # this makes it much easier to work with the data, can go through all this only once instead of during every damn search shop = {} shop.itemId = invItemsVal.type + ":" + invItemsVal.durability shop.name = itemNames[shop.itemId] shop.type = rootVal.signType shop.price = rootVal.signPrice shop.amount = invItemsVal.amount shop.owner = rootVal.ownerName shop.owner = "Server" if shop.type is "ibuy" or shop.type is "isell" shop.stock = rootVal.invInStock shop.stock = "infinite" if shop.type is "ibuy" or shop.type is "isell" shop.world = rootVal.locWorld shop.x = rootVal.locX shop.y = rootVal.locY shop.z = rootVal.locZ shop.enchants = null; if invItemsVal.meta if invItemsVal.meta.enchantments enchantList = [] for enchant, level of invItemsVal.meta.enchantments # turning the enchants into a more familiar format... enchantList.push ENCHANTS[enchant] + " " + NUMERALS[level] # if multiple enchantments, we are joining them together with a comma and a space ;) shop.enchants = enchantList.join(', ') shop.multi = multiShopItems if multiShop isnt false if shop.multi or shop.enchants shop.hasMeta = true shops.push shop shops = shops.sort (a, b) -> # defaulting to sorting by price, in the future this may be a search option.. pricePerA = a.price / a.amount pricePerB = b.price / b.amount pricePerA - pricePerB console.log shops console.log "Loaded Shops!" $('#loadingSpinner').hide() $('#itemSearchBox').removeAttr 'disabled' $('#playerSearchBox').removeAttr 'disabled' $('#itemSearchBox').on 'input', () -> # this function searches the data based on itemname provided on each value change in the input $('#results').html "" $('#playerSearchBox').val "" search = $('#itemSearchBox').val().toLowerCase() $('#resultsLabel').show() $('#query').text search for searchShop, shop of shops if shop.enchants enchantSearch = shop.enchants.toLowerCase() if shop.name and shop.name.includes(search) or enchantSearch.includes(search) generateResults shop else if shop.name and shop.name.includes(search) generateResults shop $('#playerSearchBox').on 'input', () -> # this function searches the data based on playername provided on each value change in the input $('#results').html "" $('#itemSearchBox').val "" search = $('#playerSearchBox').val().toLowerCase() $('#resultsLabel').show() $('#query').text search for searchShop, shop of shops shopOwner = shop.owner.toLowerCase() if shopOwner and shopOwner.includes(search) generateResults shop generateResults = (shop) -> # this function generates results from the shop given to it if shop.stock is true color = 'green-text' inStock = 'In Stock' else if shop.stock is "infinite" color = 'green-text' inStock = '&infin; Stock' else color = 'red-text' inStock = 'No Stock' shopImage = shop.itemId.replace ':', '-' playerHead = "https://mcapi.ca/avatar/" + shop.owner if shop.owner is "Server" playerHead = "https://mcapi.ca/query/" + $('#shopdexIp').text() + "/icon/" if shop.enchants enchantDisplay = "<p>Enchanted with<em> " + shop.enchants + "</em></p>" else enchantDisplay = "" if shop.multi multiDisplay = "<p>Includes<em> " + shop.multi + "</em></p>" else multiDisplay = "" if shop.hasMeta is true $('#results').append """ <div class="result"> <img class="result-image" src="img/#{ shopImage }.png" alt="#{ shop.name }"> <div class="result-info"> <p><strong>#{ shop.type }</strong> #{ shop.amount } #{ shop.name } for #{ symbol }#{ shop.price }</p> <p><span class="#{ color }">#{ inStock }</span> @ <a href="#{ dynmapURL + "?worldname=" + shop.world + "&mapname=surface&zoom=20&x=" + shop.x + "&y=" + shop.y + "&z=" + shop.z }" target="_blank">x#{ shop.x }, y#{ shop.y }, z#{ shop.z }</a> <p><i class="icon-globe"></i> #{ shop.world } &nbsp; <button class="show-on-mobile show-more-info">More Details</button><small class="show-on-desktop">Hover to See More Details</small></p> <div class="result-player"><img src="#{ playerHead }" width="30px" height="30px"><p> #{ shop.owner }</p></div> <div class="result-more-info"> #{ enchantDisplay } #{ multiDisplay } </div> </div> </div> """ else $('#results').append """ <div class="result"> <img class="result-image" src="img/#{ shopImage }.png" alt="#{ shop.name }"> <div class="result-info"> <p><strong>#{ shop.type }</strong> #{ shop.amount } #{ shop.name } for #{ symbol }#{ shop.price }</p> <p><span class="#{ color }">#{ inStock }</span> @ <a href="#{ dynmapURL + "?worldname=" + shop.world + "&mapname=surface&zoom=20&x=" + shop.x + "&y=" + shop.y + "&z=" + shop.z }" target="_blank">x#{ shop.x }, y#{ shop.y }, z#{ shop.z }</a> <p><i class="icon-globe"></i> #{ shop.world }</p> <div class="result-player"><img src="#{ playerHead }" width="30px" height="30px"><p> #{ shop.owner }</p></div> </div> </div> """ # enchant and numerals clean names below ENCHANTS = 'ARROW_DAMAGE': 'Power' 'ARROW_FIRE': 'Flame' 'ARROW_INFINITE': 'Infinity' 'ARROW_KNOCKBACK': 'Punch' 'BINDING_CURSE': 'Curse of Binding' 'DAMAGE_ALL': 'Sharpness' 'DAMAGE_ARTHROPODS': 'Bane of Arthropods' 'DAMAGE_UNDEAD': 'Smite' 'DEPTH_STRIDER': 'Depth Strider' 'DIG_SPEED': 'Efficiency' 'DURABILITY': 'Unbreaking' 'FIRE_ASPECT': 'Fire Aspect' 'FROST_WALKER': 'Frost Walker' 'KNOCKBACK': 'Knockback' 'LOOT_BONUS_BLOCKS': 'Fortune' 'LOOT_BONUS_MOBS': 'Looting' 'LUCK': 'Luck of the Sea' 'LURE': 'Lure' 'MENDING': 'Mending' 'OXYGEN': 'Respiration' 'PROTECTION_ENVIRONMENTAL': 'Protection' 'PROTECTION_EXPLOSIONS': 'Blast Protection' 'PROTECTION_FALL': 'Feather Falling' 'PROTECTION_FIRE': 'Fire Protection' 'PROTECTION_PROJECTILE': 'Projectile Protection' 'SILK_TOUCH': 'Silk Touch' 'SWEEPING': 'Sweeping Edge' 'THORNS': 'Thorns' 'VANISHING_CURSE': 'Curse of Vanishing' 'WATER_WORKER': 'Aqua Affinity' NUMERALS = '1': 'I' '2': 'II' '3': 'III' '4': 'IV' '5': 'V'
true
## MCSHOPDEX by PI:NAME:<NAME>END_PI ## (c) 2017 ## AVAILABLE UNDER THE MIT LICENSE ## PROJECT HOMEPAGE: HTTPS://GITLAB.COM/LAKEN/MCSHOPDEX/ # creating a few variables, setting them to null for now symbol = null dynmapURL = null # on page load, starts all other functions $ -> # loading our config $.getJSON 'config.json', (configData) -> console.log "Recieved Config..." # assigning each key's value in the config to a variable name = configData.shopdexName ip = configData.serverIP json = configData.shopData dynmapURL = configData.dynmapURL itemApi = configData.itemAPI symbol = configData.currencySymbol # filling blanks spots with the variables we set $('#shopdexName').text name $('#shopdexIp').text ip # now we're going to grab data about the server... getServerData ip # going to load item api now... idItems itemApi, (itemNames) -> # while we are still dealing with the config, we need to load the shopdata loadShopData json, itemNames getServerData = (ip) -> # using https://mcapi.ca/ # first going to check if the server specified is online or not... $.getJSON 'https://mcapi.ca/query/' + ip + '/info', (serverData) -> status = serverData.status version = serverData.version if status is true # because it defaults to red text saying `Offline` we are removing the red text class, adding the green one, and replacing text contents $('#shopdexStatusColor').removeClass 'red-text' $('#shopdexStatusColor').addClass 'green-text' $('#shopdexStatus').text 'Online' $('#shopdexVersion').text version # changing displayed picture to the official server one... $('#shopdexImage').attr 'src', 'https://mcapi.ca/query/' + ip + '/icon' console.log "Loaded Config!" idItems = (itemApi, callback) -> $.getJSON itemApi, (items) -> console.log "Recieved Item JSON..." itemIds = {} for itemData, itemDataVal of items # here we're turning the array of objects into an easier format.. plain 'ol array itemId = itemDataVal.type + ":" + itemDataVal.meta itemIds[itemId] = itemDataVal.name.toLowerCase() console.log "Converted Item JSON!" console.log itemIds callback itemIds shops = [] loadShopData = (json, itemNames) -> $.getJSON json, (jsonData) -> console.log "Recieved Shop JSON..." # because of the way the json is structured, we have to nest all of these loops # i know it's horrible validSigns = ["buy", "sell", "ibuy", "isell"] for root, rootVal of jsonData if rootVal.invItems.length < 2 # now we're checking for if there are multiple items sold in a shop # less than 2 objects in InvItems means that it isn't a multi-item shop multiShop = false else multiShop = true shopGroup = [] for invItems, invItemsVal of rootVal.invItems if rootVal.signType in validSigns # looping through the invitems to grab the name and amount of each item sold @ the same shop # atm we only grab those 2, so any meta values (such as enchantments) are not recorded there.. might fix in the future shopGroupItemId = invItemsVal.type + ":" + invItemsVal.durability shopGroup.push invItemsVal.amount + " " + itemNames[shopGroupItemId] multiShopItems = shopGroup.join(', ') for invItems, invItemsVal of rootVal.invItems if rootVal.signType in validSigns # this makes it much easier to work with the data, can go through all this only once instead of during every damn search shop = {} shop.itemId = invItemsVal.type + ":" + invItemsVal.durability shop.name = itemNames[shop.itemId] shop.type = rootVal.signType shop.price = rootVal.signPrice shop.amount = invItemsVal.amount shop.owner = rootVal.ownerName shop.owner = "Server" if shop.type is "ibuy" or shop.type is "isell" shop.stock = rootVal.invInStock shop.stock = "infinite" if shop.type is "ibuy" or shop.type is "isell" shop.world = rootVal.locWorld shop.x = rootVal.locX shop.y = rootVal.locY shop.z = rootVal.locZ shop.enchants = null; if invItemsVal.meta if invItemsVal.meta.enchantments enchantList = [] for enchant, level of invItemsVal.meta.enchantments # turning the enchants into a more familiar format... enchantList.push ENCHANTS[enchant] + " " + NUMERALS[level] # if multiple enchantments, we are joining them together with a comma and a space ;) shop.enchants = enchantList.join(', ') shop.multi = multiShopItems if multiShop isnt false if shop.multi or shop.enchants shop.hasMeta = true shops.push shop shops = shops.sort (a, b) -> # defaulting to sorting by price, in the future this may be a search option.. pricePerA = a.price / a.amount pricePerB = b.price / b.amount pricePerA - pricePerB console.log shops console.log "Loaded Shops!" $('#loadingSpinner').hide() $('#itemSearchBox').removeAttr 'disabled' $('#playerSearchBox').removeAttr 'disabled' $('#itemSearchBox').on 'input', () -> # this function searches the data based on itemname provided on each value change in the input $('#results').html "" $('#playerSearchBox').val "" search = $('#itemSearchBox').val().toLowerCase() $('#resultsLabel').show() $('#query').text search for searchShop, shop of shops if shop.enchants enchantSearch = shop.enchants.toLowerCase() if shop.name and shop.name.includes(search) or enchantSearch.includes(search) generateResults shop else if shop.name and shop.name.includes(search) generateResults shop $('#playerSearchBox').on 'input', () -> # this function searches the data based on playername provided on each value change in the input $('#results').html "" $('#itemSearchBox').val "" search = $('#playerSearchBox').val().toLowerCase() $('#resultsLabel').show() $('#query').text search for searchShop, shop of shops shopOwner = shop.owner.toLowerCase() if shopOwner and shopOwner.includes(search) generateResults shop generateResults = (shop) -> # this function generates results from the shop given to it if shop.stock is true color = 'green-text' inStock = 'In Stock' else if shop.stock is "infinite" color = 'green-text' inStock = '&infin; Stock' else color = 'red-text' inStock = 'No Stock' shopImage = shop.itemId.replace ':', '-' playerHead = "https://mcapi.ca/avatar/" + shop.owner if shop.owner is "Server" playerHead = "https://mcapi.ca/query/" + $('#shopdexIp').text() + "/icon/" if shop.enchants enchantDisplay = "<p>Enchanted with<em> " + shop.enchants + "</em></p>" else enchantDisplay = "" if shop.multi multiDisplay = "<p>Includes<em> " + shop.multi + "</em></p>" else multiDisplay = "" if shop.hasMeta is true $('#results').append """ <div class="result"> <img class="result-image" src="img/#{ shopImage }.png" alt="#{ shop.name }"> <div class="result-info"> <p><strong>#{ shop.type }</strong> #{ shop.amount } #{ shop.name } for #{ symbol }#{ shop.price }</p> <p><span class="#{ color }">#{ inStock }</span> @ <a href="#{ dynmapURL + "?worldname=" + shop.world + "&mapname=surface&zoom=20&x=" + shop.x + "&y=" + shop.y + "&z=" + shop.z }" target="_blank">x#{ shop.x }, y#{ shop.y }, z#{ shop.z }</a> <p><i class="icon-globe"></i> #{ shop.world } &nbsp; <button class="show-on-mobile show-more-info">More Details</button><small class="show-on-desktop">Hover to See More Details</small></p> <div class="result-player"><img src="#{ playerHead }" width="30px" height="30px"><p> #{ shop.owner }</p></div> <div class="result-more-info"> #{ enchantDisplay } #{ multiDisplay } </div> </div> </div> """ else $('#results').append """ <div class="result"> <img class="result-image" src="img/#{ shopImage }.png" alt="#{ shop.name }"> <div class="result-info"> <p><strong>#{ shop.type }</strong> #{ shop.amount } #{ shop.name } for #{ symbol }#{ shop.price }</p> <p><span class="#{ color }">#{ inStock }</span> @ <a href="#{ dynmapURL + "?worldname=" + shop.world + "&mapname=surface&zoom=20&x=" + shop.x + "&y=" + shop.y + "&z=" + shop.z }" target="_blank">x#{ shop.x }, y#{ shop.y }, z#{ shop.z }</a> <p><i class="icon-globe"></i> #{ shop.world }</p> <div class="result-player"><img src="#{ playerHead }" width="30px" height="30px"><p> #{ shop.owner }</p></div> </div> </div> """ # enchant and numerals clean names below ENCHANTS = 'ARROW_DAMAGE': 'Power' 'ARROW_FIRE': 'Flame' 'ARROW_INFINITE': 'Infinity' 'ARROW_KNOCKBACK': 'Punch' 'BINDING_CURSE': 'Curse of Binding' 'DAMAGE_ALL': 'Sharpness' 'DAMAGE_ARTHROPODS': 'Bane of Arthropods' 'DAMAGE_UNDEAD': 'Smite' 'DEPTH_STRIDER': 'Depth Strider' 'DIG_SPEED': 'Efficiency' 'DURABILITY': 'Unbreaking' 'FIRE_ASPECT': 'Fire Aspect' 'FROST_WALKER': 'Frost Walker' 'KNOCKBACK': 'Knockback' 'LOOT_BONUS_BLOCKS': 'Fortune' 'LOOT_BONUS_MOBS': 'Looting' 'LUCK': 'Luck of the Sea' 'LURE': 'Lure' 'MENDING': 'Mending' 'OXYGEN': 'Respiration' 'PROTECTION_ENVIRONMENTAL': 'Protection' 'PROTECTION_EXPLOSIONS': 'Blast Protection' 'PROTECTION_FALL': 'Feather Falling' 'PROTECTION_FIRE': 'Fire Protection' 'PROTECTION_PROJECTILE': 'Projectile Protection' 'SILK_TOUCH': 'Silk Touch' 'SWEEPING': 'Sweeping Edge' 'THORNS': 'Thorns' 'VANISHING_CURSE': 'Curse of Vanishing' 'WATER_WORKER': 'Aqua Affinity' NUMERALS = '1': 'I' '2': 'II' '3': 'III' '4': 'IV' '5': 'V'
[ { "context": "y The Mousetrap key combo string (e.g. \"k\", \"shift+s\", \"command+t\")\n @param {function} fn The callb", "end": 466, "score": 0.6316704154014587, "start": 465, "tag": "KEY", "value": "s" }, { "context": "ap key combo string (e.g. \"k\", \"shift+s\", \"command+t\")\n @param {function} fn The callback.\n @par", "end": 479, "score": 0.613407552242279, "start": 478, "tag": "KEY", "value": "t" }, { "context": "y The Mousetrap key combo string (e.g. \"k\", \"shift+s\", \"command+t\")\n ###\n unbind: (key) ->\n ", "end": 1073, "score": 0.6424009799957275, "start": 1072, "tag": "KEY", "value": "s" }, { "context": "ap key combo string (e.g. \"k\", \"shift+s\", \"command+t\")\n ###\n unbind: (key) ->\n Mousetrap.un", "end": 1086, "score": 0.6566119194030762, "start": 1085, "tag": "KEY", "value": "t" } ]
src/common/keyCommands/keyCommands.coffee
anandthakker/yawpcow
1
angular.module("yawpcow.keyCommands", [] ).config( () -> stopCallback = Mousetrap.stopCallback Mousetrap.stopCallback = (e, element, combo) -> return not combo.match(/ctrl|alt|option|meta|command|esc/i) and stopCallback(e,element,combo) ).factory("keyCommands", ($log) -> glossary = {} keyCommands = ### @param {Object} scope The scope associated with this key binding. @param {String} key The Mousetrap key combo string (e.g. "k", "shift+s", "command+t") @param {function} fn The callback. @param {String} description A description for this key command, for use in the glossary. BUG: No history/stack on a given key combo, so if a binding is overwritten, then when scope of the latter is destroyed, the former won't be restored. ### bind: (scope, key, fn, description) -> Mousetrap.bind key, fn if(description?) glossary[key] = description scope.$on "$destroy", (event)-> keyCommands.unbind key ### @param {String} key The Mousetrap key combo string (e.g. "k", "shift+s", "command+t") ### unbind: (key) -> Mousetrap.unbind(key) delete glossary[key] ### @property An object whose properties are key combo strings and values are descriptions. ### glossary: glossary ).directive("ycKey", ($log, $parse, $window, $rootScope, $location, keyCommands) -> safeApply = (scope, fn) -> if(scope.$$phase) fn() else scope.$apply fn restrict: "A" ### Expected attributes: yc-key can be in the form "key" or "key:description" yc-key-command is an expression to be evaluated when yc-key is pressed. If it's absent, we'll try to either follow the link or else trigger the click event. ### link: (scope, element, attrs) -> ## This is hacky, and prevents ":" from being used as an actual key binding. delim = attrs.ycKey.indexOf(":") #parse yc-key attribute [key, desc] = if delim > 0 [attrs.ycKey.substring(0,delim), attrs.ycKey.substring(delim+1)] else [attrs.ycKey, element.text()] #parse key as an array if appropriate. if key.trim().indexOf("[") is 0 key = scope.$eval(key) preventDefault = true if attrs.ycKeyCommand? cmd = (e) -> safeApply(scope, () -> e.preventDefault() if preventDefault scope.$eval(attrs.ycKeyCommand) ) else if (element.prop('tagName')?.match /a/i) cmd = (e) -> e.preventDefault() if preventDefault if(element.prop('href')?.length > 0) safeApply scope, () -> $window.location.href = element.prop('href') else #keeping this out of $apply because ng-click calls apply. element.triggerHandler 'click' else #keeping this out of $apply because ng-click calls apply. cmd = (e) -> e.preventDefault() if preventDefault element.triggerHandler 'click' keyCommands.bind scope, key, cmd, desc ) ### TBD: A little directive to insert shortcut key label onto controls. ### ### TBD: A glossary directive? ###
210345
angular.module("yawpcow.keyCommands", [] ).config( () -> stopCallback = Mousetrap.stopCallback Mousetrap.stopCallback = (e, element, combo) -> return not combo.match(/ctrl|alt|option|meta|command|esc/i) and stopCallback(e,element,combo) ).factory("keyCommands", ($log) -> glossary = {} keyCommands = ### @param {Object} scope The scope associated with this key binding. @param {String} key The Mousetrap key combo string (e.g. "k", "shift+<KEY>", "command+<KEY>") @param {function} fn The callback. @param {String} description A description for this key command, for use in the glossary. BUG: No history/stack on a given key combo, so if a binding is overwritten, then when scope of the latter is destroyed, the former won't be restored. ### bind: (scope, key, fn, description) -> Mousetrap.bind key, fn if(description?) glossary[key] = description scope.$on "$destroy", (event)-> keyCommands.unbind key ### @param {String} key The Mousetrap key combo string (e.g. "k", "shift+<KEY>", "command+<KEY>") ### unbind: (key) -> Mousetrap.unbind(key) delete glossary[key] ### @property An object whose properties are key combo strings and values are descriptions. ### glossary: glossary ).directive("ycKey", ($log, $parse, $window, $rootScope, $location, keyCommands) -> safeApply = (scope, fn) -> if(scope.$$phase) fn() else scope.$apply fn restrict: "A" ### Expected attributes: yc-key can be in the form "key" or "key:description" yc-key-command is an expression to be evaluated when yc-key is pressed. If it's absent, we'll try to either follow the link or else trigger the click event. ### link: (scope, element, attrs) -> ## This is hacky, and prevents ":" from being used as an actual key binding. delim = attrs.ycKey.indexOf(":") #parse yc-key attribute [key, desc] = if delim > 0 [attrs.ycKey.substring(0,delim), attrs.ycKey.substring(delim+1)] else [attrs.ycKey, element.text()] #parse key as an array if appropriate. if key.trim().indexOf("[") is 0 key = scope.$eval(key) preventDefault = true if attrs.ycKeyCommand? cmd = (e) -> safeApply(scope, () -> e.preventDefault() if preventDefault scope.$eval(attrs.ycKeyCommand) ) else if (element.prop('tagName')?.match /a/i) cmd = (e) -> e.preventDefault() if preventDefault if(element.prop('href')?.length > 0) safeApply scope, () -> $window.location.href = element.prop('href') else #keeping this out of $apply because ng-click calls apply. element.triggerHandler 'click' else #keeping this out of $apply because ng-click calls apply. cmd = (e) -> e.preventDefault() if preventDefault element.triggerHandler 'click' keyCommands.bind scope, key, cmd, desc ) ### TBD: A little directive to insert shortcut key label onto controls. ### ### TBD: A glossary directive? ###
true
angular.module("yawpcow.keyCommands", [] ).config( () -> stopCallback = Mousetrap.stopCallback Mousetrap.stopCallback = (e, element, combo) -> return not combo.match(/ctrl|alt|option|meta|command|esc/i) and stopCallback(e,element,combo) ).factory("keyCommands", ($log) -> glossary = {} keyCommands = ### @param {Object} scope The scope associated with this key binding. @param {String} key The Mousetrap key combo string (e.g. "k", "shift+PI:KEY:<KEY>END_PI", "command+PI:KEY:<KEY>END_PI") @param {function} fn The callback. @param {String} description A description for this key command, for use in the glossary. BUG: No history/stack on a given key combo, so if a binding is overwritten, then when scope of the latter is destroyed, the former won't be restored. ### bind: (scope, key, fn, description) -> Mousetrap.bind key, fn if(description?) glossary[key] = description scope.$on "$destroy", (event)-> keyCommands.unbind key ### @param {String} key The Mousetrap key combo string (e.g. "k", "shift+PI:KEY:<KEY>END_PI", "command+PI:KEY:<KEY>END_PI") ### unbind: (key) -> Mousetrap.unbind(key) delete glossary[key] ### @property An object whose properties are key combo strings and values are descriptions. ### glossary: glossary ).directive("ycKey", ($log, $parse, $window, $rootScope, $location, keyCommands) -> safeApply = (scope, fn) -> if(scope.$$phase) fn() else scope.$apply fn restrict: "A" ### Expected attributes: yc-key can be in the form "key" or "key:description" yc-key-command is an expression to be evaluated when yc-key is pressed. If it's absent, we'll try to either follow the link or else trigger the click event. ### link: (scope, element, attrs) -> ## This is hacky, and prevents ":" from being used as an actual key binding. delim = attrs.ycKey.indexOf(":") #parse yc-key attribute [key, desc] = if delim > 0 [attrs.ycKey.substring(0,delim), attrs.ycKey.substring(delim+1)] else [attrs.ycKey, element.text()] #parse key as an array if appropriate. if key.trim().indexOf("[") is 0 key = scope.$eval(key) preventDefault = true if attrs.ycKeyCommand? cmd = (e) -> safeApply(scope, () -> e.preventDefault() if preventDefault scope.$eval(attrs.ycKeyCommand) ) else if (element.prop('tagName')?.match /a/i) cmd = (e) -> e.preventDefault() if preventDefault if(element.prop('href')?.length > 0) safeApply scope, () -> $window.location.href = element.prop('href') else #keeping this out of $apply because ng-click calls apply. element.triggerHandler 'click' else #keeping this out of $apply because ng-click calls apply. cmd = (e) -> e.preventDefault() if preventDefault element.triggerHandler 'click' keyCommands.bind scope, key, cmd, desc ) ### TBD: A little directive to insert shortcut key label onto controls. ### ### TBD: A glossary directive? ###
[ { "context": "s private message\n# * Based on welcome.coffee by Bob Silverberg <bob.silverberg@gmail.com>\n#\n# Commands:\n# hubo", "end": 233, "score": 0.9996009469032288, "start": 219, "tag": "NAME", "value": "Bob Silverberg" }, { "context": "\n# * Based on welcome.coffee by Bob Silverberg <bob.silverberg@gmail.com>\n#\n# Commands:\n# hubot la bienvenida\n\n# Author:", "end": 259, "score": 0.999923586845398, "start": 235, "tag": "EMAIL", "value": "bob.silverberg@gmail.com" }, { "context": "# Commands:\n# hubot la bienvenida\n\n# Author:\n# Francho\n\nhubot = require 'hubot'\ninspect = require('util'", "end": 321, "score": 0.8577459454536438, "start": 314, "tag": "NAME", "value": "Francho" }, { "context": "obot.messageRoom '#presentaciones', \"Hola @#{user.name} ¿por qué no te presentas para que sepamos quién ", "end": 1952, "score": 0.7105505466461182, "start": 1948, "tag": "USERNAME", "value": "name" }, { "context": "amos quién eres?\"\n robot.messageRoom \"@#{user.name}\", welcomeMsg(user.name)\n add_nicks user.nam", "end": 2046, "score": 0.7311394214630127, "start": 2042, "tag": "USERNAME", "value": "name" } ]
scripts/welcome-to-zihub.coffee
francho/agilico
1
# Description: # Welcome to Zithub. # # Configuration: # * A persistent brain store like hubot-redis-brain is highly recommended. # # Notes: # * Sends welcome as private message # * Based on welcome.coffee by Bob Silverberg <bob.silverberg@gmail.com> # # Commands: # hubot la bienvenida # Author: # Francho hubot = require 'hubot' inspect = require('util').inspect module.exports = (robot) -> welcomeMsg = (nick) -> msg = """ Hola {nick}, soy Robotico...un bot, un amigo, un sirviente Te recomiendo que antes de nada revises tu perfil y te pongas un avatar (nos gusta ver la cara a la gente para conocernos cuando coincidamos en algún sarao) y una pequeña bio para poder situarte. Luego puedes presentarte en el canal #presentaciones para que sepan que has llegado, quién eres y a qué te dedicas. Por aquí usamos la regla de los dos pies, así que echa un vistazo a los canales y únete a los de tu interés. En el momento que veas que no te aportan nada o que tu no puedes aportar nada puedes (debes) abandonar el canal y aquí no ha pasado nada. Bienvenid@ """ msg.replace '{nick}', nick add_nicks = (nicks) -> robot.brain.data.nicks ||= [] nicks = [nicks] unless Array.isArray nicks for nick in nicks unless nick in robot.brain.data.nicks robot.brain.data.nicks.push nick robot.logger.debug "Added nick: #{nick}" welcomeGif = (user, room) -> msg = new hubot.TextMessage(user, robot.name + ' gif me hello') msg.room = room robot.receive msg robot.brain.on 'loaded', => robot.brain.data.nicks ||= [] robot.enter (res) -> robot.logger.debug inspect(res.message) user = res.message.user robot.logger.debug "User enter #{user.name}" if Array.isArray robot.brain.data.nicks if user.name in robot.brain.data.nicks robot.logger.debug "Already know #{user.name}" return robot.messageRoom '#presentaciones', "Hola @#{user.name} ¿por qué no te presentas para que sepamos quién eres?" robot.messageRoom "@#{user.name}", welcomeMsg(user.name) add_nicks user.name # welcomeGif(user, user.name) robot.respond /la bienvenida/i, (msg) -> msg.reply welcomeMsg('')
133256
# Description: # Welcome to Zithub. # # Configuration: # * A persistent brain store like hubot-redis-brain is highly recommended. # # Notes: # * Sends welcome as private message # * Based on welcome.coffee by <NAME> <<EMAIL>> # # Commands: # hubot la bienvenida # Author: # <NAME> hubot = require 'hubot' inspect = require('util').inspect module.exports = (robot) -> welcomeMsg = (nick) -> msg = """ Hola {nick}, soy Robotico...un bot, un amigo, un sirviente Te recomiendo que antes de nada revises tu perfil y te pongas un avatar (nos gusta ver la cara a la gente para conocernos cuando coincidamos en algún sarao) y una pequeña bio para poder situarte. Luego puedes presentarte en el canal #presentaciones para que sepan que has llegado, quién eres y a qué te dedicas. Por aquí usamos la regla de los dos pies, así que echa un vistazo a los canales y únete a los de tu interés. En el momento que veas que no te aportan nada o que tu no puedes aportar nada puedes (debes) abandonar el canal y aquí no ha pasado nada. Bienvenid@ """ msg.replace '{nick}', nick add_nicks = (nicks) -> robot.brain.data.nicks ||= [] nicks = [nicks] unless Array.isArray nicks for nick in nicks unless nick in robot.brain.data.nicks robot.brain.data.nicks.push nick robot.logger.debug "Added nick: #{nick}" welcomeGif = (user, room) -> msg = new hubot.TextMessage(user, robot.name + ' gif me hello') msg.room = room robot.receive msg robot.brain.on 'loaded', => robot.brain.data.nicks ||= [] robot.enter (res) -> robot.logger.debug inspect(res.message) user = res.message.user robot.logger.debug "User enter #{user.name}" if Array.isArray robot.brain.data.nicks if user.name in robot.brain.data.nicks robot.logger.debug "Already know #{user.name}" return robot.messageRoom '#presentaciones', "Hola @#{user.name} ¿por qué no te presentas para que sepamos quién eres?" robot.messageRoom "@#{user.name}", welcomeMsg(user.name) add_nicks user.name # welcomeGif(user, user.name) robot.respond /la bienvenida/i, (msg) -> msg.reply welcomeMsg('')
true
# Description: # Welcome to Zithub. # # Configuration: # * A persistent brain store like hubot-redis-brain is highly recommended. # # Notes: # * Sends welcome as private message # * Based on welcome.coffee by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Commands: # hubot la bienvenida # Author: # PI:NAME:<NAME>END_PI hubot = require 'hubot' inspect = require('util').inspect module.exports = (robot) -> welcomeMsg = (nick) -> msg = """ Hola {nick}, soy Robotico...un bot, un amigo, un sirviente Te recomiendo que antes de nada revises tu perfil y te pongas un avatar (nos gusta ver la cara a la gente para conocernos cuando coincidamos en algún sarao) y una pequeña bio para poder situarte. Luego puedes presentarte en el canal #presentaciones para que sepan que has llegado, quién eres y a qué te dedicas. Por aquí usamos la regla de los dos pies, así que echa un vistazo a los canales y únete a los de tu interés. En el momento que veas que no te aportan nada o que tu no puedes aportar nada puedes (debes) abandonar el canal y aquí no ha pasado nada. Bienvenid@ """ msg.replace '{nick}', nick add_nicks = (nicks) -> robot.brain.data.nicks ||= [] nicks = [nicks] unless Array.isArray nicks for nick in nicks unless nick in robot.brain.data.nicks robot.brain.data.nicks.push nick robot.logger.debug "Added nick: #{nick}" welcomeGif = (user, room) -> msg = new hubot.TextMessage(user, robot.name + ' gif me hello') msg.room = room robot.receive msg robot.brain.on 'loaded', => robot.brain.data.nicks ||= [] robot.enter (res) -> robot.logger.debug inspect(res.message) user = res.message.user robot.logger.debug "User enter #{user.name}" if Array.isArray robot.brain.data.nicks if user.name in robot.brain.data.nicks robot.logger.debug "Already know #{user.name}" return robot.messageRoom '#presentaciones', "Hola @#{user.name} ¿por qué no te presentas para que sepamos quién eres?" robot.messageRoom "@#{user.name}", welcomeMsg(user.name) add_nicks user.name # welcomeGif(user, user.name) robot.respond /la bienvenida/i, (msg) -> msg.reply welcomeMsg('')
[ { "context": "\n \"id\" : \"2.16.840.1.113883.3.464.1003.102.12.1011\"\n }, {\n \"name\" : \"Acute Tonsil", "end": 3534, "score": 0.9349563717842102, "start": 3523, "tag": "IP_ADDRESS", "value": "102.12.1011" }, { "context": "\n \"id\" : \"2.16.840.1.113883.3.464.1003.102.12.1012\"\n }, {\n \"name\" : \"Ambulatory/E", "end": 3652, "score": 0.9514535665512085, "start": 3641, "tag": "IP_ADDRESS", "value": "102.12.1012" }, { "context": ".101.12.1061\"\n }, {\n \"name\" : \"Antibiotic Medications\",\n \"id\" : \"2.16.840.1.113883.3.464.100", "end": 3832, "score": 0.9970932602882385, "start": 3810, "tag": "NAME", "value": "Antibiotic Medications" }, { "context": ".196.12.1001\"\n }, {\n \"name\" : \"Group A Streptococcus Test\",\n \"id\" : \"2.16.8", "end": 3938, "score": 0.5513060092926025, "start": 3933, "tag": "NAME", "value": "Group" }, { "context": " }, {\n \"name\" : \"Group A Streptococcus Test\",\n \"id\" : \"2.16.840.1.113883.3.464.100", "end": 3959, "score": 0.6833828091621399, "start": 3955, "tag": "NAME", "value": "Test" }, { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 4119, "score": 0.9992060661315918, "start": 4112, "tag": "NAME", "value": "Patient" }, { "context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ", "end": 4485, "score": 0.9974014163017273, "start": 4472, "tag": "NAME", "value": "InDemographic" }, { "context": " }\n }, {\n \"name\" : \"Pharyngitis\",\n \"context\" : \"Patient\",\n ", "end": 6549, "score": 0.9996729493141174, "start": 6538, "tag": "NAME", "value": "Pharyngitis" }, { "context": " }\n }, {\n \"name\" : \"Antibiotics\",\n \"context\" : \"Patient\",\n ", "end": 7464, "score": 0.9995462894439697, "start": 7453, "tag": "NAME", "value": "Antibiotics" }, { "context": " }\n }, {\n \"name\" : \"TargetEncounters\",\n \"context\" : \"Patient\",\n ", "end": 7957, "score": 0.7429919242858887, "start": 7941, "tag": "NAME", "value": "TargetEncounters" }, { "context": " \"expression\" : {\n \"name\" : \"Pharyngitis\",\n \"type\" : \"ExpressionRef\"\n ", "end": 8745, "score": 0.9291560649871826, "start": 8734, "tag": "NAME", "value": "Pharyngitis" }, { "context": " \"expression\" : {\n \"name\" : \"Antibiotics\",\n \"type\" : \"ExpressionRef\"\n ", "end": 9830, "score": 0.9597554802894592, "start": 9819, "tag": "NAME", "value": "Antibiotics" }, { "context": " }\n }, {\n \"name\" : \"TargetDiagnoses\",\n \"context\" : \"Patient\",\n ", "end": 11854, "score": 0.8053615093231201, "start": 11848, "tag": "NAME", "value": "Target" }, { "context": " }\n }, {\n \"name\" : \"TargetDiagnoses\",\n \"context\" : \"Patient\",\n ", "end": 11863, "score": 0.5435625314712524, "start": 11858, "tag": "NAME", "value": "noses" }, { "context": " \"expression\" : {\n \"name\" : \"Pharyngitis\",\n \"type\" : \"ExpressionRef\"\n ", "end": 12103, "score": 0.9855750203132629, "start": 12092, "tag": "NAME", "value": "Pharyngitis" }, { "context": " \"expression\" : {\n \"name\" : \"TargetEncounters\",\n \"type\" : \"ExpressionRef\"\n ", "end": 12378, "score": 0.9298899173736572, "start": 12362, "tag": "NAME", "value": "TargetEncounters" }, { "context": " }\n }, {\n \"name\" : \"HasPriorAntibiotics\",\n \"context\" : \"Patien", "end": 13370, "score": 0.5953342914581299, "start": 13367, "tag": "NAME", "value": "Has" }, { "context": "expression\" : {\n \"name\" : \"Antibiotics\",\n \"type\" : \"Expre", "end": 13696, "score": 0.9646793603897095, "start": 13693, "tag": "NAME", "value": "Ant" } ]
Src/coffeescript/cql-execution/src/example/CMS146v2_CQM.coffee
esteban-aliverti/clinical_quality_language
0
module.exports = { "library" : { "identifier" : { "id" : "CMS146", "version" : "2" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "parameters" : { "def" : [ { "name" : "MeasurementPeriod", "default" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } } ] }, "valueSets" : { "def" : [ { "name" : "Acute Pharyngitis", "id" : "2.16.840.1.113883.3.464.1003.102.12.1011" }, { "name" : "Acute Tonsillitis", "id" : "2.16.840.1.113883.3.464.1003.102.12.1012" }, { "name" : "Ambulatory/ED Visit", "id" : "2.16.840.1.113883.3.464.1003.101.12.1061" }, { "name" : "Antibiotic Medications", "id" : "2.16.840.1.113883.3.464.1003.196.12.1001" }, { "name" : "Group A Streptococcus Test", "id" : "2.16.840.1.113883.3.464.1003.198.12.1012" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "InDemographic", "context" : "Patient", "expression" : { "type" : "And", "operand" : [ { "type" : "GreaterOrEqual", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" } ] }, { "type" : "Less", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "18", "type" : "Literal" } ] } ] } }, { "name" : "Pharyngitis", "context" : "Patient", "expression" : { "type" : "Union", "operand" : [ { "dataType" : "{http://org.hl7.fhir}Condition", "templateId" : "cqf-condition", "codeProperty" : "code", "type" : "Retrieve", "codes" : { "name" : "Acute Pharyngitis", "type" : "ValueSetRef" } }, { "dataType" : "{http://org.hl7.fhir}Condition", "templateId" : "cqf-condition", "codeProperty" : "code", "type" : "Retrieve", "codes" : { "name" : "Acute Tonsillitis", "type" : "ValueSetRef" } } ] } }, { "name" : "Antibiotics", "context" : "Patient", "expression" : { "dataType" : "{http://org.hl7.fhir}MedicationPrescription", "templateId" : "cqf-medicationprescription", "codeProperty" : "medication.code", "type" : "Retrieve", "codes" : { "name" : "Antibiotic Medications", "type" : "ValueSetRef" } } }, { "name" : "TargetEncounters", "context" : "Patient", "expression" : { "type" : "Query", "source" : [ { "alias" : "E", "expression" : { "dataType" : "{http://org.hl7.fhir}Encounter", "templateId" : "cqf-encounter", "codeProperty" : "class", "type" : "Retrieve", "codes" : { "name" : "Ambulatory/ED Visit", "type" : "ValueSetRef" } } } ], "relationship" : [ { "alias" : "P", "type" : "With", "expression" : { "name" : "Pharyngitis", "type" : "ExpressionRef" }, "suchThat" : { "type" : "OverlapsAfter", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "path" : "onsetDate", "scope" : "P", "type" : "Property" }, "high" : { "path" : "abatementDate", "scope" : "P", "type" : "Property" } }, { "path" : "period", "scope" : "E", "type" : "Property" } ] } }, { "alias" : "A", "type" : "With", "expression" : { "name" : "Antibiotics", "type" : "ExpressionRef" }, "suchThat" : { "type" : "In", "operand" : [ { "precision" : "Day", "type" : "DurationBetween", "operand" : [ { "path" : "dateWritten", "scope" : "A", "type" : "Property" }, { "type" : "Start", "operand" : { "path" : "period", "scope" : "E", "type" : "Property" } } ] }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "type" : "Negate", "operand" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" } }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } } ] } } ], "where" : { "type" : "IncludedIn", "operand" : [ { "path" : "performedAtTime", "scope" : "E", "type" : "Property" }, { "name" : "MeasurementPeriod", "type" : "ParameterRef" } ] } } }, { "name" : "TargetDiagnoses", "context" : "Patient", "expression" : { "type" : "Query", "source" : [ { "alias" : "P", "expression" : { "name" : "Pharyngitis", "type" : "ExpressionRef" } } ], "relationship" : [ { "alias" : "E", "type" : "With", "expression" : { "name" : "TargetEncounters", "type" : "ExpressionRef" }, "suchThat" : { "type" : "OverlapsAfter", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "path" : "onsetDate", "scope" : "P", "type" : "Property" }, "high" : { "path" : "abatementDate", "scope" : "P", "type" : "Property" } }, { "path" : "period", "scope" : "E", "type" : "Property" } ] } } ] } }, { "name" : "HasPriorAntibiotics", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "type" : "Query", "source" : [ { "alias" : "A", "expression" : { "name" : "Antibiotics", "type" : "ExpressionRef" } } ], "relationship" : [ { "alias" : "D", "type" : "With", "expression" : { "name" : "TargetDiagnoses", "type" : "ExpressionRef" }, "suchThat" : { "type" : "In", "operand" : [ { "precision" : "Day", "type" : "DurationBetween", "operand" : [ { "type" : "Start", "operand" : { "path" : "dateWritten", "scope" : "A", "type" : "Property" } }, { "path" : "onsetDate", "scope" : "D", "type" : "Property" } ] }, { "lowClosed" : false, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "30", "type" : "Literal" } } ] } } ] } } }, { "name" : "HasTargetEncounter", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "name" : "TargetEncounters", "type" : "ExpressionRef" } } }, { "name" : "InInitialPopulation", "context" : "Patient", "expression" : { "type" : "And", "operand" : [ { "name" : "InDemographic", "type" : "ExpressionRef" }, { "name" : "HasTargetEncounter", "type" : "ExpressionRef" } ] } }, { "name" : "InDenominator", "context" : "Patient", "expression" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}bool", "value" : "true", "type" : "Literal" } }, { "name" : "InDenominatorExclusions", "context" : "Patient", "expression" : { "name" : "HasPriorAntibiotics", "type" : "ExpressionRef" } }, { "name" : "InNumerator", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "type" : "Query", "source" : [ { "alias" : "R", "expression" : { "dataType" : "{http://org.hl7.fhir}DiagnosticReport", "templateId" : "cqf-diagnosticreport", "codeProperty" : "name", "type" : "Retrieve", "codes" : { "name" : "Group A Streptococcus Test", "type" : "ValueSetRef" } } } ], "relationship" : [ ], "where" : { "type" : "And", "operand" : [ { "type" : "IncludedIn", "operand" : [ { "path" : "diagnosticDateTime", "scope" : "R", "type" : "Property" }, { "name" : "MeasurementPeriod", "type" : "ParameterRef" } ] }, { "type" : "Not", "operand" : { "type" : "IsNull", "operand" : { "path" : "result", "scope" : "R", "type" : "Property" } } } ] } } } } ] } } }
154577
module.exports = { "library" : { "identifier" : { "id" : "CMS146", "version" : "2" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "parameters" : { "def" : [ { "name" : "MeasurementPeriod", "default" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } } ] }, "valueSets" : { "def" : [ { "name" : "Acute Pharyngitis", "id" : "2.16.840.1.113883.3.464.1003.102.12.1011" }, { "name" : "Acute Tonsillitis", "id" : "2.16.840.1.113883.3.464.1003.102.12.1012" }, { "name" : "Ambulatory/ED Visit", "id" : "2.16.840.1.113883.3.464.1003.101.12.1061" }, { "name" : "<NAME>", "id" : "2.16.840.1.113883.3.464.1003.196.12.1001" }, { "name" : "<NAME> A Streptococcus <NAME>", "id" : "2.16.840.1.113883.3.464.1003.198.12.1012" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "And", "operand" : [ { "type" : "GreaterOrEqual", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" } ] }, { "type" : "Less", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "18", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "Union", "operand" : [ { "dataType" : "{http://org.hl7.fhir}Condition", "templateId" : "cqf-condition", "codeProperty" : "code", "type" : "Retrieve", "codes" : { "name" : "Acute Pharyngitis", "type" : "ValueSetRef" } }, { "dataType" : "{http://org.hl7.fhir}Condition", "templateId" : "cqf-condition", "codeProperty" : "code", "type" : "Retrieve", "codes" : { "name" : "Acute Tonsillitis", "type" : "ValueSetRef" } } ] } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "dataType" : "{http://org.hl7.fhir}MedicationPrescription", "templateId" : "cqf-medicationprescription", "codeProperty" : "medication.code", "type" : "Retrieve", "codes" : { "name" : "Antibiotic Medications", "type" : "ValueSetRef" } } }, { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "Query", "source" : [ { "alias" : "E", "expression" : { "dataType" : "{http://org.hl7.fhir}Encounter", "templateId" : "cqf-encounter", "codeProperty" : "class", "type" : "Retrieve", "codes" : { "name" : "Ambulatory/ED Visit", "type" : "ValueSetRef" } } } ], "relationship" : [ { "alias" : "P", "type" : "With", "expression" : { "name" : "<NAME>", "type" : "ExpressionRef" }, "suchThat" : { "type" : "OverlapsAfter", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "path" : "onsetDate", "scope" : "P", "type" : "Property" }, "high" : { "path" : "abatementDate", "scope" : "P", "type" : "Property" } }, { "path" : "period", "scope" : "E", "type" : "Property" } ] } }, { "alias" : "A", "type" : "With", "expression" : { "name" : "<NAME>", "type" : "ExpressionRef" }, "suchThat" : { "type" : "In", "operand" : [ { "precision" : "Day", "type" : "DurationBetween", "operand" : [ { "path" : "dateWritten", "scope" : "A", "type" : "Property" }, { "type" : "Start", "operand" : { "path" : "period", "scope" : "E", "type" : "Property" } } ] }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "type" : "Negate", "operand" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" } }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } } ] } } ], "where" : { "type" : "IncludedIn", "operand" : [ { "path" : "performedAtTime", "scope" : "E", "type" : "Property" }, { "name" : "MeasurementPeriod", "type" : "ParameterRef" } ] } } }, { "name" : "<NAME>Diag<NAME>", "context" : "Patient", "expression" : { "type" : "Query", "source" : [ { "alias" : "P", "expression" : { "name" : "<NAME>", "type" : "ExpressionRef" } } ], "relationship" : [ { "alias" : "E", "type" : "With", "expression" : { "name" : "<NAME>", "type" : "ExpressionRef" }, "suchThat" : { "type" : "OverlapsAfter", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "path" : "onsetDate", "scope" : "P", "type" : "Property" }, "high" : { "path" : "abatementDate", "scope" : "P", "type" : "Property" } }, { "path" : "period", "scope" : "E", "type" : "Property" } ] } } ] } }, { "name" : "<NAME>PriorAntibiotics", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "type" : "Query", "source" : [ { "alias" : "A", "expression" : { "name" : "<NAME>ibiotics", "type" : "ExpressionRef" } } ], "relationship" : [ { "alias" : "D", "type" : "With", "expression" : { "name" : "TargetDiagnoses", "type" : "ExpressionRef" }, "suchThat" : { "type" : "In", "operand" : [ { "precision" : "Day", "type" : "DurationBetween", "operand" : [ { "type" : "Start", "operand" : { "path" : "dateWritten", "scope" : "A", "type" : "Property" } }, { "path" : "onsetDate", "scope" : "D", "type" : "Property" } ] }, { "lowClosed" : false, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "30", "type" : "Literal" } } ] } } ] } } }, { "name" : "HasTargetEncounter", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "name" : "TargetEncounters", "type" : "ExpressionRef" } } }, { "name" : "InInitialPopulation", "context" : "Patient", "expression" : { "type" : "And", "operand" : [ { "name" : "InDemographic", "type" : "ExpressionRef" }, { "name" : "HasTargetEncounter", "type" : "ExpressionRef" } ] } }, { "name" : "InDenominator", "context" : "Patient", "expression" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}bool", "value" : "true", "type" : "Literal" } }, { "name" : "InDenominatorExclusions", "context" : "Patient", "expression" : { "name" : "HasPriorAntibiotics", "type" : "ExpressionRef" } }, { "name" : "InNumerator", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "type" : "Query", "source" : [ { "alias" : "R", "expression" : { "dataType" : "{http://org.hl7.fhir}DiagnosticReport", "templateId" : "cqf-diagnosticreport", "codeProperty" : "name", "type" : "Retrieve", "codes" : { "name" : "Group A Streptococcus Test", "type" : "ValueSetRef" } } } ], "relationship" : [ ], "where" : { "type" : "And", "operand" : [ { "type" : "IncludedIn", "operand" : [ { "path" : "diagnosticDateTime", "scope" : "R", "type" : "Property" }, { "name" : "MeasurementPeriod", "type" : "ParameterRef" } ] }, { "type" : "Not", "operand" : { "type" : "IsNull", "operand" : { "path" : "result", "scope" : "R", "type" : "Property" } } } ] } } } } ] } } }
true
module.exports = { "library" : { "identifier" : { "id" : "CMS146", "version" : "2" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "QUICK", "uri" : "http://org.hl7.fhir" } ] }, "parameters" : { "def" : [ { "name" : "MeasurementPeriod", "default" : { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2013", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] }, "high" : { "name" : "DateTime", "type" : "FunctionRef", "operand" : [ { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2014", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "1", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } ] } } } ] }, "valueSets" : { "def" : [ { "name" : "Acute Pharyngitis", "id" : "2.16.840.1.113883.3.464.1003.102.12.1011" }, { "name" : "Acute Tonsillitis", "id" : "2.16.840.1.113883.3.464.1003.102.12.1012" }, { "name" : "Ambulatory/ED Visit", "id" : "2.16.840.1.113883.3.464.1003.101.12.1061" }, { "name" : "PI:NAME:<NAME>END_PI", "id" : "2.16.840.1.113883.3.464.1003.196.12.1001" }, { "name" : "PI:NAME:<NAME>END_PI A Streptococcus PI:NAME:<NAME>END_PI", "id" : "2.16.840.1.113883.3.464.1003.198.12.1012" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://org.hl7.fhir}Patient", "templateId" : "cqf-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "And", "operand" : [ { "type" : "GreaterOrEqual", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "2", "type" : "Literal" } ] }, { "type" : "Less", "operand" : [ { "precision" : "Year", "type" : "CalculateAgeAt", "operand" : [ { "path" : "birthDate", "type" : "Property", "source" : { "name" : "Patient", "type" : "ExpressionRef" } }, { "type" : "Start", "operand" : { "name" : "MeasurementPeriod", "type" : "ParameterRef" } } ] }, { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "18", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "Union", "operand" : [ { "dataType" : "{http://org.hl7.fhir}Condition", "templateId" : "cqf-condition", "codeProperty" : "code", "type" : "Retrieve", "codes" : { "name" : "Acute Pharyngitis", "type" : "ValueSetRef" } }, { "dataType" : "{http://org.hl7.fhir}Condition", "templateId" : "cqf-condition", "codeProperty" : "code", "type" : "Retrieve", "codes" : { "name" : "Acute Tonsillitis", "type" : "ValueSetRef" } } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "dataType" : "{http://org.hl7.fhir}MedicationPrescription", "templateId" : "cqf-medicationprescription", "codeProperty" : "medication.code", "type" : "Retrieve", "codes" : { "name" : "Antibiotic Medications", "type" : "ValueSetRef" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "Query", "source" : [ { "alias" : "E", "expression" : { "dataType" : "{http://org.hl7.fhir}Encounter", "templateId" : "cqf-encounter", "codeProperty" : "class", "type" : "Retrieve", "codes" : { "name" : "Ambulatory/ED Visit", "type" : "ValueSetRef" } } } ], "relationship" : [ { "alias" : "P", "type" : "With", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" }, "suchThat" : { "type" : "OverlapsAfter", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "path" : "onsetDate", "scope" : "P", "type" : "Property" }, "high" : { "path" : "abatementDate", "scope" : "P", "type" : "Property" } }, { "path" : "period", "scope" : "E", "type" : "Property" } ] } }, { "alias" : "A", "type" : "With", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" }, "suchThat" : { "type" : "In", "operand" : [ { "precision" : "Day", "type" : "DurationBetween", "operand" : [ { "path" : "dateWritten", "scope" : "A", "type" : "Property" }, { "type" : "Start", "operand" : { "path" : "period", "scope" : "E", "type" : "Property" } } ] }, { "lowClosed" : true, "highClosed" : false, "type" : "Interval", "low" : { "type" : "Negate", "operand" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "3", "type" : "Literal" } }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" } } ] } } ], "where" : { "type" : "IncludedIn", "operand" : [ { "path" : "performedAtTime", "scope" : "E", "type" : "Property" }, { "name" : "MeasurementPeriod", "type" : "ParameterRef" } ] } } }, { "name" : "PI:NAME:<NAME>END_PIDiagPI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "Query", "source" : [ { "alias" : "P", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" } } ], "relationship" : [ { "alias" : "E", "type" : "With", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" }, "suchThat" : { "type" : "OverlapsAfter", "operand" : [ { "lowClosed" : true, "highClosed" : true, "type" : "Interval", "low" : { "path" : "onsetDate", "scope" : "P", "type" : "Property" }, "high" : { "path" : "abatementDate", "scope" : "P", "type" : "Property" } }, { "path" : "period", "scope" : "E", "type" : "Property" } ] } } ] } }, { "name" : "PI:NAME:<NAME>END_PIPriorAntibiotics", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "type" : "Query", "source" : [ { "alias" : "A", "expression" : { "name" : "PI:NAME:<NAME>END_PIibiotics", "type" : "ExpressionRef" } } ], "relationship" : [ { "alias" : "D", "type" : "With", "expression" : { "name" : "TargetDiagnoses", "type" : "ExpressionRef" }, "suchThat" : { "type" : "In", "operand" : [ { "precision" : "Day", "type" : "DurationBetween", "operand" : [ { "type" : "Start", "operand" : { "path" : "dateWritten", "scope" : "A", "type" : "Property" } }, { "path" : "onsetDate", "scope" : "D", "type" : "Property" } ] }, { "lowClosed" : false, "highClosed" : true, "type" : "Interval", "low" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "0", "type" : "Literal" }, "high" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}int", "value" : "30", "type" : "Literal" } } ] } } ] } } }, { "name" : "HasTargetEncounter", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "name" : "TargetEncounters", "type" : "ExpressionRef" } } }, { "name" : "InInitialPopulation", "context" : "Patient", "expression" : { "type" : "And", "operand" : [ { "name" : "InDemographic", "type" : "ExpressionRef" }, { "name" : "HasTargetEncounter", "type" : "ExpressionRef" } ] } }, { "name" : "InDenominator", "context" : "Patient", "expression" : { "valueType" : "{http://www.w3.org/2001/XMLSchema}bool", "value" : "true", "type" : "Literal" } }, { "name" : "InDenominatorExclusions", "context" : "Patient", "expression" : { "name" : "HasPriorAntibiotics", "type" : "ExpressionRef" } }, { "name" : "InNumerator", "context" : "Patient", "expression" : { "type" : "Exists", "operand" : { "type" : "Query", "source" : [ { "alias" : "R", "expression" : { "dataType" : "{http://org.hl7.fhir}DiagnosticReport", "templateId" : "cqf-diagnosticreport", "codeProperty" : "name", "type" : "Retrieve", "codes" : { "name" : "Group A Streptococcus Test", "type" : "ValueSetRef" } } } ], "relationship" : [ ], "where" : { "type" : "And", "operand" : [ { "type" : "IncludedIn", "operand" : [ { "path" : "diagnosticDateTime", "scope" : "R", "type" : "Property" }, { "name" : "MeasurementPeriod", "type" : "ParameterRef" } ] }, { "type" : "Not", "operand" : { "type" : "IsNull", "operand" : { "path" : "result", "scope" : "R", "type" : "Property" } } } ] } } } } ] } } }
[ { "context": "\n backbone-articulation.js 0.3.4\n (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/backbone-articulati", "end": 68, "score": 0.9998233318328857, "start": 54, "tag": "NAME", "value": "Kevin Malakoff" }, { "context": "js 0.3.4\n (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/backbone-articulation/\n License: MIT ", "end": 87, "score": 0.9878807067871094, "start": 78, "tag": "USERNAME", "value": "kmalakoff" } ]
src/backbone-articulation.coffee
kmalakoff/backbone-articulation
2
### backbone-articulation.js 0.3.4 (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/backbone-articulation/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, and Underscore.js. ### # import and re-export Underscore (or Lo-Dash with precedence), Backbone, and Knockout if not @_ and (typeof(require) isnt 'undefined') then (try _ = require('lodash') catch e then _ = require('underscore')) else _ = @_ _ = if _.hasOwnProperty('_') then _._ else _ # LEGACY Backbone = if not @Backbone and (typeof(require) isnt 'undefined') then require('backbone') else @Backbone # import JSON-Serialize.js (JSONS.serialize, JSONS) and Lifecycle.js (LC.own, LC.disown) JSONS = if not @JSONS and (typeof(require) != 'undefined') then require('json-serialize') else @JSONS LC = if not @LC and (typeof(require) != 'undefined') then require('lifecycle') else @LC ############################################## # export or create Articulation namespace Backbone.Articulation = Articulation = if (typeof(exports) != 'undefined') then exports else {} Articulation.VERSION = '0.3.4' # setting - if you set to true, you must provide String.prototype.underscore and String.prototype.singularize (for example, from inflection.js) # Note: @ is not guaranteed to work unless Class.constructor.name exists Articulation.TYPE_UNDERSCORE_SINGULARIZE = false Articulation._mixin = (target_constructor, source_constructor, source_fns) -> fns = _.pick(source_constructor.prototype, source_fns) # create a dummy super class for chaining the overridden methods class Link extends target_constructor.__super__.constructor # mixin the required functions Link.prototype[name] = fn for name, fn of fns Link.prototype.__bba_super = target_constructor.__super__.constructor Link.prototype.__bba_toJSON = Link.prototype['toJSON'] # set up the hierarchy target_constructor.prototype.__proto__ = Link.prototype target_constructor.__super__ = Link.prototype ################################## # Articulation.Model ################################## class Articulation.Model extends Backbone.Model @extend = Backbone.Model.extend __bba_super: Backbone.Model # provide the super class to mixin functions # Converts a model attributes from objects to plain old JSON (if needed). toJSON: -> json = JSONS.serialize(@attributes, properties: true) # ensure there is a type field return json if json.hasOwnProperty(JSONS.TYPE_FIELD) # use the type field (json[JSONS.TYPE_FIELD] = @[JSONS.TYPE_FIELD]; return json) if @[JSONS.TYPE_FIELD] # use the class name class_name = Object.getPrototypeOf(Object(@)).constructor.name return json unless class_name # convert the class using an underscore and singularize convention, eg. CouchDB "type" field convention if Articulation.TYPE_UNDERSCORE_SINGULARIZE throw 'Missing String.prototype.underscore' unless String::underscore throw 'Missing String.prototype.singularize' unless String::singularize json[JSONS.TYPE_FIELD] = class_name.underscore().singularize() else json[JSONS.TYPE_FIELD] = class_name return json # Converts a model attributes from plain old JSON to objects (if needed). parse: (resp, xhr) -> return resp unless resp return JSONS.deserialize( resp, {properties: true, skip_type_field: true}) set: (attrs, options) -> return @ unless attrs attrs = attrs.attributes if attrs.attributes # if an attribute changes, release the previous since it will get replaced for key, value of attrs continue if _.isEqual(@attributes[key], value) @_disownAttribute(key, @_previousAttributes[key]) if @_previousAttributes and (@_previousAttributes.hasOwnProperty(key)) @_ownAttribute(key, value) @__bba_super.prototype.set.apply(@, arguments) unset: (attr, options) -> return @ unless attr of @attributes @_disownAttribute(attr, @attributes[attr]) # if an attribute is unset, disown it @__bba_super.prototype.unset.apply(@, arguments) clear: (options) -> # release attributes and previous attributes @_disownAttribute(key, @attributes[key]) for key of @attributes # if is it not silent, it will call change which will clear previous attributes (@_disownAttribute(key, @_previousAttributes[key]) for key of @_previousAttributes) if options and options.silent @__bba_super.prototype.clear.apply(@, arguments) change: (options) -> # disown the previous attributes (@_disownAttribute key, @_previousAttributes[key]) for key of @_previousAttributes result = @__bba_super.prototype.change.apply(@, arguments) # own the new previous attributes (@_previousAttributes[key] = @_ownAttribute(key, @_previousAttributes[key])) for key of @_previousAttributes return result ################################## # Internal ################################## # Uses LC.own to clone(), retain(), or just stores a reference to an articulated attribute object (if needed). _ownAttribute: (key, value) -> return unless value return value if (value instanceof Backbone.Model) or (value instanceof Backbone.Collection) return value if _.isArray(value) and value.length and (value[0] instanceof Backbone.Model) or (value[0] instanceof Backbone.Collection) LC.own(value) _disownAllAttributes: -> # Uses LC.disown to destroy() or release() to an attribute object (if needed). _disownAttribute: (key, value) -> return unless value return value if (value instanceof Backbone.Model) or (value instanceof Backbone.Collection) return value if _.isArray(value) and value.length and (value[0] instanceof Backbone.Model) or (value[0] instanceof Backbone.Collection) LC.disown(value) # allows mixin of Articulation.Model into existing hierarchies. Pass the constructor in to be mixed in. @mixin: (target_constructor) -> Articulation._mixin(target_constructor, Articulation.Model, ['toJSON', 'parse', 'set', 'unset', 'clear', 'change', '_ownAttribute', '_disownAttribute']) ################################## # Articulation.Collection ################################## class Articulation.Collection extends Backbone.Collection @extend = Backbone.Collection.extend __bba_super: Backbone.Collection # provide the super class to mixin functions model: Articulation.Model # default model type # Converts all of its models to plain old JSON (if needed) using JSONS.serialize. toJSON: -> models_as_JSON = [] models_as_JSON.push(model.toJSON()) for model in @models return models_as_JSON # Articulates all of its model attributes from plain old JSON to objects (if needed) using JSONS. # JSONS looks for a \_type attribute to find a fromJSON method. parse: (resp, xhr) -> return resp unless (resp and _.isArray(resp)) articulated_model_attributes = [] articulated_model_attributes.push JSONS.deserialize(model_resp, skip_type_field: true) for model_resp in resp return articulated_model_attributes _onModelEvent: (event, model, collection, options) -> if event is "destroy" model._disownAttribute(key, model._previousAttributes[key]) for key of model._previousAttributes model._disownAttribute(key, model.attributes[key]) for key of model.attributes @__bba_super.prototype._onModelEvent.apply(@, arguments) _removeReference: (model) -> model.clear({silent: true}) if model @__bba_super.prototype._removeReference.apply(@, arguments) # allows mixin of Articulation.Model into existing hierarchies. Pass the constructor in to be mixed in. @mixin: (target_constructor) -> Articulation._mixin(target_constructor, Articulation.Collection, ['toJSON', 'parse', '_reset', '_onModelEvent'])
84921
### backbone-articulation.js 0.3.4 (c) 2011, 2012 <NAME> - http://kmalakoff.github.com/backbone-articulation/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, and Underscore.js. ### # import and re-export Underscore (or Lo-Dash with precedence), Backbone, and Knockout if not @_ and (typeof(require) isnt 'undefined') then (try _ = require('lodash') catch e then _ = require('underscore')) else _ = @_ _ = if _.hasOwnProperty('_') then _._ else _ # LEGACY Backbone = if not @Backbone and (typeof(require) isnt 'undefined') then require('backbone') else @Backbone # import JSON-Serialize.js (JSONS.serialize, JSONS) and Lifecycle.js (LC.own, LC.disown) JSONS = if not @JSONS and (typeof(require) != 'undefined') then require('json-serialize') else @JSONS LC = if not @LC and (typeof(require) != 'undefined') then require('lifecycle') else @LC ############################################## # export or create Articulation namespace Backbone.Articulation = Articulation = if (typeof(exports) != 'undefined') then exports else {} Articulation.VERSION = '0.3.4' # setting - if you set to true, you must provide String.prototype.underscore and String.prototype.singularize (for example, from inflection.js) # Note: @ is not guaranteed to work unless Class.constructor.name exists Articulation.TYPE_UNDERSCORE_SINGULARIZE = false Articulation._mixin = (target_constructor, source_constructor, source_fns) -> fns = _.pick(source_constructor.prototype, source_fns) # create a dummy super class for chaining the overridden methods class Link extends target_constructor.__super__.constructor # mixin the required functions Link.prototype[name] = fn for name, fn of fns Link.prototype.__bba_super = target_constructor.__super__.constructor Link.prototype.__bba_toJSON = Link.prototype['toJSON'] # set up the hierarchy target_constructor.prototype.__proto__ = Link.prototype target_constructor.__super__ = Link.prototype ################################## # Articulation.Model ################################## class Articulation.Model extends Backbone.Model @extend = Backbone.Model.extend __bba_super: Backbone.Model # provide the super class to mixin functions # Converts a model attributes from objects to plain old JSON (if needed). toJSON: -> json = JSONS.serialize(@attributes, properties: true) # ensure there is a type field return json if json.hasOwnProperty(JSONS.TYPE_FIELD) # use the type field (json[JSONS.TYPE_FIELD] = @[JSONS.TYPE_FIELD]; return json) if @[JSONS.TYPE_FIELD] # use the class name class_name = Object.getPrototypeOf(Object(@)).constructor.name return json unless class_name # convert the class using an underscore and singularize convention, eg. CouchDB "type" field convention if Articulation.TYPE_UNDERSCORE_SINGULARIZE throw 'Missing String.prototype.underscore' unless String::underscore throw 'Missing String.prototype.singularize' unless String::singularize json[JSONS.TYPE_FIELD] = class_name.underscore().singularize() else json[JSONS.TYPE_FIELD] = class_name return json # Converts a model attributes from plain old JSON to objects (if needed). parse: (resp, xhr) -> return resp unless resp return JSONS.deserialize( resp, {properties: true, skip_type_field: true}) set: (attrs, options) -> return @ unless attrs attrs = attrs.attributes if attrs.attributes # if an attribute changes, release the previous since it will get replaced for key, value of attrs continue if _.isEqual(@attributes[key], value) @_disownAttribute(key, @_previousAttributes[key]) if @_previousAttributes and (@_previousAttributes.hasOwnProperty(key)) @_ownAttribute(key, value) @__bba_super.prototype.set.apply(@, arguments) unset: (attr, options) -> return @ unless attr of @attributes @_disownAttribute(attr, @attributes[attr]) # if an attribute is unset, disown it @__bba_super.prototype.unset.apply(@, arguments) clear: (options) -> # release attributes and previous attributes @_disownAttribute(key, @attributes[key]) for key of @attributes # if is it not silent, it will call change which will clear previous attributes (@_disownAttribute(key, @_previousAttributes[key]) for key of @_previousAttributes) if options and options.silent @__bba_super.prototype.clear.apply(@, arguments) change: (options) -> # disown the previous attributes (@_disownAttribute key, @_previousAttributes[key]) for key of @_previousAttributes result = @__bba_super.prototype.change.apply(@, arguments) # own the new previous attributes (@_previousAttributes[key] = @_ownAttribute(key, @_previousAttributes[key])) for key of @_previousAttributes return result ################################## # Internal ################################## # Uses LC.own to clone(), retain(), or just stores a reference to an articulated attribute object (if needed). _ownAttribute: (key, value) -> return unless value return value if (value instanceof Backbone.Model) or (value instanceof Backbone.Collection) return value if _.isArray(value) and value.length and (value[0] instanceof Backbone.Model) or (value[0] instanceof Backbone.Collection) LC.own(value) _disownAllAttributes: -> # Uses LC.disown to destroy() or release() to an attribute object (if needed). _disownAttribute: (key, value) -> return unless value return value if (value instanceof Backbone.Model) or (value instanceof Backbone.Collection) return value if _.isArray(value) and value.length and (value[0] instanceof Backbone.Model) or (value[0] instanceof Backbone.Collection) LC.disown(value) # allows mixin of Articulation.Model into existing hierarchies. Pass the constructor in to be mixed in. @mixin: (target_constructor) -> Articulation._mixin(target_constructor, Articulation.Model, ['toJSON', 'parse', 'set', 'unset', 'clear', 'change', '_ownAttribute', '_disownAttribute']) ################################## # Articulation.Collection ################################## class Articulation.Collection extends Backbone.Collection @extend = Backbone.Collection.extend __bba_super: Backbone.Collection # provide the super class to mixin functions model: Articulation.Model # default model type # Converts all of its models to plain old JSON (if needed) using JSONS.serialize. toJSON: -> models_as_JSON = [] models_as_JSON.push(model.toJSON()) for model in @models return models_as_JSON # Articulates all of its model attributes from plain old JSON to objects (if needed) using JSONS. # JSONS looks for a \_type attribute to find a fromJSON method. parse: (resp, xhr) -> return resp unless (resp and _.isArray(resp)) articulated_model_attributes = [] articulated_model_attributes.push JSONS.deserialize(model_resp, skip_type_field: true) for model_resp in resp return articulated_model_attributes _onModelEvent: (event, model, collection, options) -> if event is "destroy" model._disownAttribute(key, model._previousAttributes[key]) for key of model._previousAttributes model._disownAttribute(key, model.attributes[key]) for key of model.attributes @__bba_super.prototype._onModelEvent.apply(@, arguments) _removeReference: (model) -> model.clear({silent: true}) if model @__bba_super.prototype._removeReference.apply(@, arguments) # allows mixin of Articulation.Model into existing hierarchies. Pass the constructor in to be mixed in. @mixin: (target_constructor) -> Articulation._mixin(target_constructor, Articulation.Collection, ['toJSON', 'parse', '_reset', '_onModelEvent'])
true
### backbone-articulation.js 0.3.4 (c) 2011, 2012 PI:NAME:<NAME>END_PI - http://kmalakoff.github.com/backbone-articulation/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, and Underscore.js. ### # import and re-export Underscore (or Lo-Dash with precedence), Backbone, and Knockout if not @_ and (typeof(require) isnt 'undefined') then (try _ = require('lodash') catch e then _ = require('underscore')) else _ = @_ _ = if _.hasOwnProperty('_') then _._ else _ # LEGACY Backbone = if not @Backbone and (typeof(require) isnt 'undefined') then require('backbone') else @Backbone # import JSON-Serialize.js (JSONS.serialize, JSONS) and Lifecycle.js (LC.own, LC.disown) JSONS = if not @JSONS and (typeof(require) != 'undefined') then require('json-serialize') else @JSONS LC = if not @LC and (typeof(require) != 'undefined') then require('lifecycle') else @LC ############################################## # export or create Articulation namespace Backbone.Articulation = Articulation = if (typeof(exports) != 'undefined') then exports else {} Articulation.VERSION = '0.3.4' # setting - if you set to true, you must provide String.prototype.underscore and String.prototype.singularize (for example, from inflection.js) # Note: @ is not guaranteed to work unless Class.constructor.name exists Articulation.TYPE_UNDERSCORE_SINGULARIZE = false Articulation._mixin = (target_constructor, source_constructor, source_fns) -> fns = _.pick(source_constructor.prototype, source_fns) # create a dummy super class for chaining the overridden methods class Link extends target_constructor.__super__.constructor # mixin the required functions Link.prototype[name] = fn for name, fn of fns Link.prototype.__bba_super = target_constructor.__super__.constructor Link.prototype.__bba_toJSON = Link.prototype['toJSON'] # set up the hierarchy target_constructor.prototype.__proto__ = Link.prototype target_constructor.__super__ = Link.prototype ################################## # Articulation.Model ################################## class Articulation.Model extends Backbone.Model @extend = Backbone.Model.extend __bba_super: Backbone.Model # provide the super class to mixin functions # Converts a model attributes from objects to plain old JSON (if needed). toJSON: -> json = JSONS.serialize(@attributes, properties: true) # ensure there is a type field return json if json.hasOwnProperty(JSONS.TYPE_FIELD) # use the type field (json[JSONS.TYPE_FIELD] = @[JSONS.TYPE_FIELD]; return json) if @[JSONS.TYPE_FIELD] # use the class name class_name = Object.getPrototypeOf(Object(@)).constructor.name return json unless class_name # convert the class using an underscore and singularize convention, eg. CouchDB "type" field convention if Articulation.TYPE_UNDERSCORE_SINGULARIZE throw 'Missing String.prototype.underscore' unless String::underscore throw 'Missing String.prototype.singularize' unless String::singularize json[JSONS.TYPE_FIELD] = class_name.underscore().singularize() else json[JSONS.TYPE_FIELD] = class_name return json # Converts a model attributes from plain old JSON to objects (if needed). parse: (resp, xhr) -> return resp unless resp return JSONS.deserialize( resp, {properties: true, skip_type_field: true}) set: (attrs, options) -> return @ unless attrs attrs = attrs.attributes if attrs.attributes # if an attribute changes, release the previous since it will get replaced for key, value of attrs continue if _.isEqual(@attributes[key], value) @_disownAttribute(key, @_previousAttributes[key]) if @_previousAttributes and (@_previousAttributes.hasOwnProperty(key)) @_ownAttribute(key, value) @__bba_super.prototype.set.apply(@, arguments) unset: (attr, options) -> return @ unless attr of @attributes @_disownAttribute(attr, @attributes[attr]) # if an attribute is unset, disown it @__bba_super.prototype.unset.apply(@, arguments) clear: (options) -> # release attributes and previous attributes @_disownAttribute(key, @attributes[key]) for key of @attributes # if is it not silent, it will call change which will clear previous attributes (@_disownAttribute(key, @_previousAttributes[key]) for key of @_previousAttributes) if options and options.silent @__bba_super.prototype.clear.apply(@, arguments) change: (options) -> # disown the previous attributes (@_disownAttribute key, @_previousAttributes[key]) for key of @_previousAttributes result = @__bba_super.prototype.change.apply(@, arguments) # own the new previous attributes (@_previousAttributes[key] = @_ownAttribute(key, @_previousAttributes[key])) for key of @_previousAttributes return result ################################## # Internal ################################## # Uses LC.own to clone(), retain(), or just stores a reference to an articulated attribute object (if needed). _ownAttribute: (key, value) -> return unless value return value if (value instanceof Backbone.Model) or (value instanceof Backbone.Collection) return value if _.isArray(value) and value.length and (value[0] instanceof Backbone.Model) or (value[0] instanceof Backbone.Collection) LC.own(value) _disownAllAttributes: -> # Uses LC.disown to destroy() or release() to an attribute object (if needed). _disownAttribute: (key, value) -> return unless value return value if (value instanceof Backbone.Model) or (value instanceof Backbone.Collection) return value if _.isArray(value) and value.length and (value[0] instanceof Backbone.Model) or (value[0] instanceof Backbone.Collection) LC.disown(value) # allows mixin of Articulation.Model into existing hierarchies. Pass the constructor in to be mixed in. @mixin: (target_constructor) -> Articulation._mixin(target_constructor, Articulation.Model, ['toJSON', 'parse', 'set', 'unset', 'clear', 'change', '_ownAttribute', '_disownAttribute']) ################################## # Articulation.Collection ################################## class Articulation.Collection extends Backbone.Collection @extend = Backbone.Collection.extend __bba_super: Backbone.Collection # provide the super class to mixin functions model: Articulation.Model # default model type # Converts all of its models to plain old JSON (if needed) using JSONS.serialize. toJSON: -> models_as_JSON = [] models_as_JSON.push(model.toJSON()) for model in @models return models_as_JSON # Articulates all of its model attributes from plain old JSON to objects (if needed) using JSONS. # JSONS looks for a \_type attribute to find a fromJSON method. parse: (resp, xhr) -> return resp unless (resp and _.isArray(resp)) articulated_model_attributes = [] articulated_model_attributes.push JSONS.deserialize(model_resp, skip_type_field: true) for model_resp in resp return articulated_model_attributes _onModelEvent: (event, model, collection, options) -> if event is "destroy" model._disownAttribute(key, model._previousAttributes[key]) for key of model._previousAttributes model._disownAttribute(key, model.attributes[key]) for key of model.attributes @__bba_super.prototype._onModelEvent.apply(@, arguments) _removeReference: (model) -> model.clear({silent: true}) if model @__bba_super.prototype._removeReference.apply(@, arguments) # allows mixin of Articulation.Model into existing hierarchies. Pass the constructor in to be mixed in. @mixin: (target_constructor) -> Articulation._mixin(target_constructor, Articulation.Collection, ['toJSON', 'parse', '_reset', '_onModelEvent'])
[ { "context": " = children.last()\n if last.mx_hash.hash_key == \"rextem_end\"\n ret += \"\"\"\",\"#{last.flags}\"\"\" if last.flags\n", "end": 13010, "score": 0.9800094366073608, "start": 13000, "tag": "KEY", "value": "rextem_end" }, { "context": "in node.value_array\n if v.mx_hash.hash_key == 'comma_rvalue'\n comma_rvalue_node = v\n \n arg_list = []\n ", "end": 18626, "score": 0.9761204719543457, "start": 18614, "tag": "KEY", "value": "comma_rvalue" }, { "context": "ode.value_array\n if v.mx_hash.hash_key == 'rvalue'\n arg_list.push ctx.translate v\n ", "end": 18840, "score": 0.8540623188018799, "start": 18834, "tag": "KEY", "value": "rvalue" }, { "context": "ctx.translate v\n if v.mx_hash.hash_key == 'comma_rvalue'\n walk v\n rvalue\n walk comma_rva", "end": 18928, "score": 0.9716041088104248, "start": 18916, "tag": "KEY", "value": "comma_rvalue" } ]
src/translator.coffee
hu2prod/scriptscript
1
require 'fy' require 'fy/lib/codegen' { Translator un_op_translator_holder un_op_translator_framework bin_op_translator_holder bin_op_translator_framework } = require 'gram2' module = @ # ################################################################################################### trans = new Translator trans.trans_skip = indent : true dedent : true eol : true trans.trans_value = bracket : true comma : true pair_separator: true arrow_function: true trans.trans_token = comment : (v)-> "//" + v.substr 1 deep = (ctx, node)-> list = [] # if node.mx_hash.deep? # node.mx_hash.deep = '0' if node.mx_hash.deep == false # special case for deep=0 # value_array = (node.value_array[pos] for pos in node.mx_hash.deep.split ',') # else # value_array = node.value_array value_array = node.value_array for v,k in value_array if trans.trans_skip[v.mx_hash.hash_key]? # LATER if node.mx_hash.eol_pass and v.mx_hash.hash_key == 'eol' list.push ";\n" else if fn = trans.trans_token[v.mx_hash.hash_key] list.push fn v.value else if trans.trans_value[v.mx_hash.hash_key]? list.push v.value else list.push ctx.translate v if delimiter = node.mx_hash.delimiter # delimiter = ' ' if delimiter == "'[SPACE]'" # not used -> commented list = [ list.join(delimiter) ] list trans.translator_hash['value'] = translate:(ctx, node)->node.value_view trans.translator_hash['deep'] = translate:(ctx, node)-> list = deep ctx, node list.join('') trans.translator_hash['block'] = translate:(ctx, node)-> list = deep ctx, node make_tab list.join(''), ' ' ensure_bracket = (t)-> return t if t[0] == "(" and t[t.length-1] == ")" "(#{t})" # ################################################################################################### # bin_op # ################################################################################################### do ()-> holder = new bin_op_translator_holder for v in "+ - * / % += -= *= /= %= = < <= > >= << >> >>>".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" holder.op_list["**"] = new bin_op_translator_framework "Math.pow($1, $2)" holder.op_list["//"] = new bin_op_translator_framework "Math.floor($1 / $2)" holder.op_list["%%"] = new bin_op_translator_framework "(_tmp_b=$2,($1 % _tmp_b + _tmp_b) % _tmp_b)" holder.op_list["**="] = new bin_op_translator_framework "$1 = Math.pow($1, $2)" holder.op_list["//="] = new bin_op_translator_framework "$1 = Math.floor($1 / $2)" holder.op_list["%%="] = new bin_op_translator_framework "$1 = (_tmp_b=$2,($1 % _tmp_b + _tmp_b) % _tmp_b)" holder.op_list["=="] = new bin_op_translator_framework "($1===$2)" holder.op_list["!="] = new bin_op_translator_framework "($1!==$2)" trans.translator_hash['bin_op'] = translate:(ctx, node)-> op = node.value_array[1].value_view # PORTING BUG gram2 node.value_array[1].value = node.value_array[1].value_view # return is implied, I actually mean it. This if block is intended to be the last statement in the function. if op of holder.op_list holder.translate ctx, node else [a,_skip,b] = node.value_array a_tr = ctx.translate a b_tr = ctx.translate b logical_or_bitwise = (char) -> postfix = if op[-1..] == '=' then '=' else '' if a.mx_hash.type.toString() == "int" # type inference ensures the second operand to be int "(#{a_tr}#{char}#{postfix}#{b_tr})" else # type inference ensures operands to be bools if char == '^' if postfix "(#{a_tr}=!!(#{a_tr}^#{b_tr}))" else "(!!(#{a_tr}#{char}#{b_tr}))" else if postfix "(#{a_tr}=(#{a_tr}#{char}#{char}#{b_tr}))" else "(#{a_tr}#{char}#{char}#{b_tr})" switch op when "and", "and=" logical_or_bitwise '&' when "or", "or=" logical_or_bitwise '|' when "xor", "xor=" logical_or_bitwise '^' when '|' # pipes logic if b.mx_hash.type? switch b.mx_hash.type.main when "function" nest = b.mx_hash.type.nest # NOTE 1st nest == return type if nest.length == 2 # is_map "#{ensure_bracket a_tr}.map(#{b_tr})" else if nest.length == 3 ### TODO Array.prototype.async_map -> ?Promise? ?Promise?.prototype (need all Array stuff) ### if nest[2].main == 'function' # async map "#{ensure_bracket a_tr}.async_map(#{b_tr})" else # reduce "#{ensure_bracket a_tr}.reduce(#{b_tr})" else if nest.length == 4 if nest[3].main == 'function' # async reduce "#{ensure_bracket a_tr}.async_reduce(#{b_tr})" else throw new Error "unknown pipe function signature [1]" else throw new Error "unknown pipe function signature [2]" when "array" "#{b_tr} = #{a_tr}" when "Sink" """ var ref = #{ensure_bracket a_tr}; for (var i = 0, len = ref.length; i < len; i++) { #{b_tr}(ref[i]); } """ # else для switch не нужен т.к. не пропустит type inference else "#{b_tr} = #{a_tr}" else ### !pragma coverage-skip-block ### throw new Error "Translator: can't figure out how to translate '#{op}'" # Don't put code down here below if block without a good reason (unless you're ready for refactoring). # The preceding block should remain the last statement in the function as long as possible. # Here is some old code (maybe del later): # if op in ['or', 'and'] # # needs type inference # [a,_skip,b] = node.value_array # a_tr = ctx.translate a # b_tr = ctx.translate b # if !a.mx_hash.type? or !b.mx_hash.type? # throw new Error "can't translate op=#{op} because type inference can't detect type of arguments" # if !a.mx_hash.type.eq b.mx_hash.type # # не пропустит type inference # ### !pragma coverage-skip-block ### # throw new Error "can't translate op=#{op} because type mismatch #{a.mx_hash.type} != #{b.mx_hash.type}" # switch a.mx_hash.type.toString() # when 'int' # return "(#{a_tr}|#{b_tr})" # when 'bool' # return "(#{a_tr}||#{b_tr})" # else # # не пропустит type inference # ### !pragma coverage-skip-block ### # throw new Error "op=#{op} doesn't support type #{a.mx_hash.type}" # ################################################################################################### # pre_op # ################################################################################################### do ()-> holder = new un_op_translator_holder holder.mode_pre() for v in un_op_list = "~ + - !".split ' ' holder.op_list[v] = new un_op_translator_framework "$op$1" holder.op_list["void"] = new un_op_translator_framework "null" for v in un_op_list = "typeof new delete".split ' ' holder.op_list[v] = new un_op_translator_framework "($op $1)" # trans.translator_hash['pre_op'] = holder # PORTING BUG UGLY FIX gram2 trans.translator_hash['pre_op'] = translate:(ctx, node)-> op = node.value_array[0].value_view node.value_array[0].value = node.value_array[0].value_view if op == "not" a = node.value_array[1] a_tr = ctx.translate a if !a.mx_hash.type throw new Error "can't translate not operation because no type inferenced" if a.mx_hash.type.toString() == "int" "~#{a_tr}" else "!#{a_tr}" # type inference ensures bool else holder.translate ctx, node # ################################################################################################### # post_op # ################################################################################################### do ()-> holder = new un_op_translator_holder holder.mode_post() for v in un_op_list = ["++", '--'] holder.op_list[v] = new un_op_translator_framework "($1$op)" # trans.translator_hash['post_op'] = holder # PORTING BUG UGLY FIX gram2 trans.translator_hash['post_op'] = translate:(ctx, node)-> node.value_array[1].value = node.value_array[1].value_view holder.translate ctx, node # ################################################################################################### # str # ################################################################################################### trans.translator_hash['string_singleq'] = translate:(ctx, node)-> s = node.value_view[1...-1] s = s.replace /"/g, '\\"' s = s.replace /^\s+/g, '' s = s.replace /\s+$/g, '' s = s.replace /\s*\n\s*/g, ' ' '"' + s + '"' #" trans.translator_hash['string_doubleq'] = translate:(ctx, node)-> s = node.value_view s = s.replace /^"\s+/g, '"' s = s.replace /\s+"$/g, '"' s = s.replace /\s*\n\s*/g, ' ' trans.translator_hash['block_string_singleq'] = translate:(ctx, node)-> s = node.value_view[3...-3] s = s.replace /^\n/g, '' s = s.replace /\n$/g, '' s = s.replace /\n/g, '\\n' s = s.replace /"/g, '\\"' '"' + s + '"' trans.translator_hash['block_string_doubleq'] = trans.translator_hash['block_string_singleq'] # for now... trans.translator_hash['string_interpolation_prepare'] = translate:(ctx, node)-> ret = switch node.mx_hash.hash_key when 'st1_start' node.value_view[1...-2] # '"text#{' -> 'text' .replace(/^\s+/g, '') .replace /\s*\n\s*/g, ' ' when 'st3_start' node.value_view[3...-2] # '"""text#{' -> 'text' when 'st_mid' node.value_view[1...-2] # '}text#{' -> 'text' when 'st1_end' node.value_view[1...-1] # '}text"' -> 'text' .replace(/\s+$/g, '') .replace /\s*\n\s*/g, ' ' when 'st3_end' node.value_view[1...-3] # '}text"""' -> 'text' ret = ret.replace /"/, '\\"' trans.translator_hash['string_interpolation_put_together'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]) when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]) if children.last().mx_hash.hash_key[-3...] == "end" ret = '("' + ret + '")' ret = ret.replace /\+""/g, '' # some cleanup ret trans.translator_hash['string_interpolation_put_together_m1'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]).replace /\s*\n\s*/g, ' ' when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]).replace /\s*\n\s*/g, ' ' ret # ################################################################################################### # regexp # ################################################################################################### trans.translator_hash['block_regexp'] = translate:(ctx, node)-> [_skip, body, flags] = node.value_view.split "///" # '///ab+c///imgy' -> ['', 'ab+c', 'imgy'] body = body.replace /\s#.*/g, '' # comments body = body.replace /\s/g, '' # whitespace if body == "" body = "(?:)" else body = body.replace /\//g, '\\/' # escaping forward slashes '/' + body + '/' + flags trans.translator_hash['regexp_interpolation_prepare'] = translate:(ctx, node)-> switch node.mx_hash.hash_key when 'rextem_start' ret = node.value_view[3...-2] # '///ab+c#{' -> 'ab+c' when 'rextem_mid' ret = node.value_view[1...-2] # '}ab+c#{' -> 'ab+c' when 'rextem_end' [body, flags] = node.value_view.split "///" # '}ab+c///imgy' -> ['}ab+c', 'imgy'] node.flags = flags ret = body[1...] # '}ab+c' -> 'ab+c' ret = ret.replace /\s#.*/g, '' # comments ret = ret.replace /\s/g, '' # whitespace ret = ret.replace /"/g, '\\"' # escaping quotes trans.translator_hash['regexp_interpolation_put_together'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]) when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]) last = children.last() if last.mx_hash.hash_key == "rextem_end" ret += """","#{last.flags}""" if last.flags ret = """RegExp("#{ret}")""" ret = ret.replace /\+""/g, '' # 'RegExp("a"+"b")' -> 'RegExp("ab")' ret # ################################################################################################### # bracket # ################################################################################################### trans.translator_hash["bracket"] = translate:(ctx,node)-> ensure_bracket ctx.translate node.value_array[1] # ################################################################################################### # ternary # ################################################################################################### trans.translator_hash["ternary"] = translate:(ctx,node)-> [cond, _s1, tnode, _s2, fnode] = node.value_array "#{ctx.translate cond} ? #{ctx.translate tnode} : #{ctx.translate fnode}" # ################################################################################################### # hash # ################################################################################################### trans.translator_hash["hash_pair_simple"] = translate:(ctx,node)-> [key, _skip, value] = node.value_array "#{key.value}:#{ctx.translate value}" trans.translator_hash["hash_pair_auto"] = translate:(ctx,node)-> [value] = node.value_array "#{value.value}:#{value.value}" trans.translator_hash['hash_wrap'] = translate:(ctx, node)-> list = deep ctx, node "{"+list.join('')+"}" # ################################################################################################### # array # ################################################################################################### trans.translator_hash["num_array"] = translate:(ctx, node)-> # [_skip1, a, _skip2, b, _skip3] = node.value_array a = +node.value_array[1].value_view b = +node.value_array[3].value_view if b - a > 20 """ (function() { var results = []; for (var i = #{a}; i <= #{b}; i++){ results.push(i); } return results; })() """ else if a - b > 20 """ (function() { var results = []; for (var i = #{a}; i >= #{b}; i--){ results.push(i); } return results; })() """ else "[#{[a..b].join ", "}]" # ################################################################################################### # access # ################################################################################################### trans.translator_hash["field_access"] = translate:(ctx,node)-> [root, _skip, field] = node.value_array "#{ctx.translate root}.#{field.value}" trans.translator_hash["array_access"] = translate:(ctx,node)-> [root, _skip, field, _skip] = node.value_array "#{ctx.translate root}[#{ctx.translate field}]" trans.translator_hash["opencl_access"] = translate:(ctx,node)-> [root, _skip, field] = node.value_array root_tr = ctx.translate root key = field.value if key.length == 1 return "#{root_tr}[#{key}]" # TODO ref ret = [] for k in key ret.push "#{root_tr}[#{k}]" "[#{ret.join ','}]" # ################################################################################################### # func_decl # ################################################################################################### trans.translator_hash["func_decl_return"] = translate:(ctx,node)-> str = ctx.translate node.value_array[0] "return(#{str})" trans.translator_hash["func_decl"] = translate:(ctx,node)-> arg_list = [] walk = (arg)-> default_value_node = null if arg.value_array.length == 1 name_node = arg.value_array[0] else if arg.value_array.length == 3 if arg.value_array[1].value == "=" name_node = arg.value_array[0] default_value_node= arg.value_array[2] else if arg.value_array[1].value == ":" ### !pragma coverage-skip-block ### throw new Error "types are unsupported arg syntax yet" else if arg.value_array[1].value == "," walk arg.value_array[0] walk arg.value_array[2] return else ### !pragma coverage-skip-block ### throw new Error "unsupported arg syntax" else ### !pragma coverage-skip-block ### throw new Error "unsupported arg syntax" default_value = null if default_value_node default_value = ctx.translate default_value_node arg_list.push { name : name_node.value or name_node.value_view type : null default_value } return if node.value_array[0].value == '(' and node.value_array[2].value == ')' arg_list_node = node.value_array[1] for arg in arg_list_node.value_array continue if arg.value == "," walk arg body_node = node.value_array.last() body_node = null if body_node.value in ["->", "=>"] # no body arg_str_list = [] default_arg_str_list = [] for arg in arg_list arg_str_list.push arg.name if arg.default_value default_arg_str_list.push """ #{arg.name}=#{arg.name}==null?#{ensure_bracket arg.default_value}:#{arg.name}; """ body = "" body = ctx.translate body_node if body_node body = """ { #{join_list default_arg_str_list, ' '} #{body} } """ body = body.replace /^{\s+/, '{\n ' body = body.replace /\s+}$/, '\n}' body = "{}" if /^\{\s+\}$/.test body "(function(#{arg_str_list.join ', '})#{body})" trans.translator_hash["func_call"] = translate:(ctx,node)-> rvalue = node.value_array[0] comma_rvalue_node = null for v in node.value_array if v.mx_hash.hash_key == 'comma_rvalue' comma_rvalue_node = v arg_list = [] func_code = ensure_bracket ctx.translate rvalue if comma_rvalue_node walk = (node)-> for v in node.value_array if v.mx_hash.hash_key == 'rvalue' arg_list.push ctx.translate v if v.mx_hash.hash_key == 'comma_rvalue' walk v rvalue walk comma_rvalue_node "#{func_code}(#{arg_list.join ', '})" # ################################################################################################### # macro-block # ################################################################################################### trans.macro_block_condition_hash = "if" : (ctx, condition, block)-> """ if (#{ctx.translate condition}) { #{make_tab ctx.translate(block), ' '} } """ "while" : (ctx, condition, block)-> """ while(#{ctx.translate condition}) { #{make_tab ctx.translate(block), ' '} } """ trans.macro_block_hash = "loop" : (ctx, block)-> """ while(true) { #{make_tab ctx.translate(block), ' '} } """ trans.translator_hash['macro_block'] = translate:(ctx,node)-> if node.value_array.length == 2 [name_node, body] = node.value_array name = name_node.value if !(fn = trans.macro_block_hash[name])? if trans.macro_block_condition_hash[name]? throw new Error "Missed condition for block '#{name}'" throw new Error "unknown conditionless macro block '#{name}'" fn ctx, body else [name_node, condition, body] = node.value_array name = name_node.value if !(fn = trans.macro_block_condition_hash[name])? if trans.macro_block_hash[name]? throw new Error "Extra condition for block '#{name}'" throw new Error "unknown conditionless macro block '#{name}'" fn ctx, condition, body # ################################################################################################### @_translate = (ast, opt={})-> trans.go ast @translate = (ast, opt, on_end)-> try res = module._translate ast, opt catch e return on_end e on_end null, res
70683
require 'fy' require 'fy/lib/codegen' { Translator un_op_translator_holder un_op_translator_framework bin_op_translator_holder bin_op_translator_framework } = require 'gram2' module = @ # ################################################################################################### trans = new Translator trans.trans_skip = indent : true dedent : true eol : true trans.trans_value = bracket : true comma : true pair_separator: true arrow_function: true trans.trans_token = comment : (v)-> "//" + v.substr 1 deep = (ctx, node)-> list = [] # if node.mx_hash.deep? # node.mx_hash.deep = '0' if node.mx_hash.deep == false # special case for deep=0 # value_array = (node.value_array[pos] for pos in node.mx_hash.deep.split ',') # else # value_array = node.value_array value_array = node.value_array for v,k in value_array if trans.trans_skip[v.mx_hash.hash_key]? # LATER if node.mx_hash.eol_pass and v.mx_hash.hash_key == 'eol' list.push ";\n" else if fn = trans.trans_token[v.mx_hash.hash_key] list.push fn v.value else if trans.trans_value[v.mx_hash.hash_key]? list.push v.value else list.push ctx.translate v if delimiter = node.mx_hash.delimiter # delimiter = ' ' if delimiter == "'[SPACE]'" # not used -> commented list = [ list.join(delimiter) ] list trans.translator_hash['value'] = translate:(ctx, node)->node.value_view trans.translator_hash['deep'] = translate:(ctx, node)-> list = deep ctx, node list.join('') trans.translator_hash['block'] = translate:(ctx, node)-> list = deep ctx, node make_tab list.join(''), ' ' ensure_bracket = (t)-> return t if t[0] == "(" and t[t.length-1] == ")" "(#{t})" # ################################################################################################### # bin_op # ################################################################################################### do ()-> holder = new bin_op_translator_holder for v in "+ - * / % += -= *= /= %= = < <= > >= << >> >>>".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" holder.op_list["**"] = new bin_op_translator_framework "Math.pow($1, $2)" holder.op_list["//"] = new bin_op_translator_framework "Math.floor($1 / $2)" holder.op_list["%%"] = new bin_op_translator_framework "(_tmp_b=$2,($1 % _tmp_b + _tmp_b) % _tmp_b)" holder.op_list["**="] = new bin_op_translator_framework "$1 = Math.pow($1, $2)" holder.op_list["//="] = new bin_op_translator_framework "$1 = Math.floor($1 / $2)" holder.op_list["%%="] = new bin_op_translator_framework "$1 = (_tmp_b=$2,($1 % _tmp_b + _tmp_b) % _tmp_b)" holder.op_list["=="] = new bin_op_translator_framework "($1===$2)" holder.op_list["!="] = new bin_op_translator_framework "($1!==$2)" trans.translator_hash['bin_op'] = translate:(ctx, node)-> op = node.value_array[1].value_view # PORTING BUG gram2 node.value_array[1].value = node.value_array[1].value_view # return is implied, I actually mean it. This if block is intended to be the last statement in the function. if op of holder.op_list holder.translate ctx, node else [a,_skip,b] = node.value_array a_tr = ctx.translate a b_tr = ctx.translate b logical_or_bitwise = (char) -> postfix = if op[-1..] == '=' then '=' else '' if a.mx_hash.type.toString() == "int" # type inference ensures the second operand to be int "(#{a_tr}#{char}#{postfix}#{b_tr})" else # type inference ensures operands to be bools if char == '^' if postfix "(#{a_tr}=!!(#{a_tr}^#{b_tr}))" else "(!!(#{a_tr}#{char}#{b_tr}))" else if postfix "(#{a_tr}=(#{a_tr}#{char}#{char}#{b_tr}))" else "(#{a_tr}#{char}#{char}#{b_tr})" switch op when "and", "and=" logical_or_bitwise '&' when "or", "or=" logical_or_bitwise '|' when "xor", "xor=" logical_or_bitwise '^' when '|' # pipes logic if b.mx_hash.type? switch b.mx_hash.type.main when "function" nest = b.mx_hash.type.nest # NOTE 1st nest == return type if nest.length == 2 # is_map "#{ensure_bracket a_tr}.map(#{b_tr})" else if nest.length == 3 ### TODO Array.prototype.async_map -> ?Promise? ?Promise?.prototype (need all Array stuff) ### if nest[2].main == 'function' # async map "#{ensure_bracket a_tr}.async_map(#{b_tr})" else # reduce "#{ensure_bracket a_tr}.reduce(#{b_tr})" else if nest.length == 4 if nest[3].main == 'function' # async reduce "#{ensure_bracket a_tr}.async_reduce(#{b_tr})" else throw new Error "unknown pipe function signature [1]" else throw new Error "unknown pipe function signature [2]" when "array" "#{b_tr} = #{a_tr}" when "Sink" """ var ref = #{ensure_bracket a_tr}; for (var i = 0, len = ref.length; i < len; i++) { #{b_tr}(ref[i]); } """ # else для switch не нужен т.к. не пропустит type inference else "#{b_tr} = #{a_tr}" else ### !pragma coverage-skip-block ### throw new Error "Translator: can't figure out how to translate '#{op}'" # Don't put code down here below if block without a good reason (unless you're ready for refactoring). # The preceding block should remain the last statement in the function as long as possible. # Here is some old code (maybe del later): # if op in ['or', 'and'] # # needs type inference # [a,_skip,b] = node.value_array # a_tr = ctx.translate a # b_tr = ctx.translate b # if !a.mx_hash.type? or !b.mx_hash.type? # throw new Error "can't translate op=#{op} because type inference can't detect type of arguments" # if !a.mx_hash.type.eq b.mx_hash.type # # не пропустит type inference # ### !pragma coverage-skip-block ### # throw new Error "can't translate op=#{op} because type mismatch #{a.mx_hash.type} != #{b.mx_hash.type}" # switch a.mx_hash.type.toString() # when 'int' # return "(#{a_tr}|#{b_tr})" # when 'bool' # return "(#{a_tr}||#{b_tr})" # else # # не пропустит type inference # ### !pragma coverage-skip-block ### # throw new Error "op=#{op} doesn't support type #{a.mx_hash.type}" # ################################################################################################### # pre_op # ################################################################################################### do ()-> holder = new un_op_translator_holder holder.mode_pre() for v in un_op_list = "~ + - !".split ' ' holder.op_list[v] = new un_op_translator_framework "$op$1" holder.op_list["void"] = new un_op_translator_framework "null" for v in un_op_list = "typeof new delete".split ' ' holder.op_list[v] = new un_op_translator_framework "($op $1)" # trans.translator_hash['pre_op'] = holder # PORTING BUG UGLY FIX gram2 trans.translator_hash['pre_op'] = translate:(ctx, node)-> op = node.value_array[0].value_view node.value_array[0].value = node.value_array[0].value_view if op == "not" a = node.value_array[1] a_tr = ctx.translate a if !a.mx_hash.type throw new Error "can't translate not operation because no type inferenced" if a.mx_hash.type.toString() == "int" "~#{a_tr}" else "!#{a_tr}" # type inference ensures bool else holder.translate ctx, node # ################################################################################################### # post_op # ################################################################################################### do ()-> holder = new un_op_translator_holder holder.mode_post() for v in un_op_list = ["++", '--'] holder.op_list[v] = new un_op_translator_framework "($1$op)" # trans.translator_hash['post_op'] = holder # PORTING BUG UGLY FIX gram2 trans.translator_hash['post_op'] = translate:(ctx, node)-> node.value_array[1].value = node.value_array[1].value_view holder.translate ctx, node # ################################################################################################### # str # ################################################################################################### trans.translator_hash['string_singleq'] = translate:(ctx, node)-> s = node.value_view[1...-1] s = s.replace /"/g, '\\"' s = s.replace /^\s+/g, '' s = s.replace /\s+$/g, '' s = s.replace /\s*\n\s*/g, ' ' '"' + s + '"' #" trans.translator_hash['string_doubleq'] = translate:(ctx, node)-> s = node.value_view s = s.replace /^"\s+/g, '"' s = s.replace /\s+"$/g, '"' s = s.replace /\s*\n\s*/g, ' ' trans.translator_hash['block_string_singleq'] = translate:(ctx, node)-> s = node.value_view[3...-3] s = s.replace /^\n/g, '' s = s.replace /\n$/g, '' s = s.replace /\n/g, '\\n' s = s.replace /"/g, '\\"' '"' + s + '"' trans.translator_hash['block_string_doubleq'] = trans.translator_hash['block_string_singleq'] # for now... trans.translator_hash['string_interpolation_prepare'] = translate:(ctx, node)-> ret = switch node.mx_hash.hash_key when 'st1_start' node.value_view[1...-2] # '"text#{' -> 'text' .replace(/^\s+/g, '') .replace /\s*\n\s*/g, ' ' when 'st3_start' node.value_view[3...-2] # '"""text#{' -> 'text' when 'st_mid' node.value_view[1...-2] # '}text#{' -> 'text' when 'st1_end' node.value_view[1...-1] # '}text"' -> 'text' .replace(/\s+$/g, '') .replace /\s*\n\s*/g, ' ' when 'st3_end' node.value_view[1...-3] # '}text"""' -> 'text' ret = ret.replace /"/, '\\"' trans.translator_hash['string_interpolation_put_together'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]) when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]) if children.last().mx_hash.hash_key[-3...] == "end" ret = '("' + ret + '")' ret = ret.replace /\+""/g, '' # some cleanup ret trans.translator_hash['string_interpolation_put_together_m1'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]).replace /\s*\n\s*/g, ' ' when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]).replace /\s*\n\s*/g, ' ' ret # ################################################################################################### # regexp # ################################################################################################### trans.translator_hash['block_regexp'] = translate:(ctx, node)-> [_skip, body, flags] = node.value_view.split "///" # '///ab+c///imgy' -> ['', 'ab+c', 'imgy'] body = body.replace /\s#.*/g, '' # comments body = body.replace /\s/g, '' # whitespace if body == "" body = "(?:)" else body = body.replace /\//g, '\\/' # escaping forward slashes '/' + body + '/' + flags trans.translator_hash['regexp_interpolation_prepare'] = translate:(ctx, node)-> switch node.mx_hash.hash_key when 'rextem_start' ret = node.value_view[3...-2] # '///ab+c#{' -> 'ab+c' when 'rextem_mid' ret = node.value_view[1...-2] # '}ab+c#{' -> 'ab+c' when 'rextem_end' [body, flags] = node.value_view.split "///" # '}ab+c///imgy' -> ['}ab+c', 'imgy'] node.flags = flags ret = body[1...] # '}ab+c' -> 'ab+c' ret = ret.replace /\s#.*/g, '' # comments ret = ret.replace /\s/g, '' # whitespace ret = ret.replace /"/g, '\\"' # escaping quotes trans.translator_hash['regexp_interpolation_put_together'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]) when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]) last = children.last() if last.mx_hash.hash_key == "<KEY>" ret += """","#{last.flags}""" if last.flags ret = """RegExp("#{ret}")""" ret = ret.replace /\+""/g, '' # 'RegExp("a"+"b")' -> 'RegExp("ab")' ret # ################################################################################################### # bracket # ################################################################################################### trans.translator_hash["bracket"] = translate:(ctx,node)-> ensure_bracket ctx.translate node.value_array[1] # ################################################################################################### # ternary # ################################################################################################### trans.translator_hash["ternary"] = translate:(ctx,node)-> [cond, _s1, tnode, _s2, fnode] = node.value_array "#{ctx.translate cond} ? #{ctx.translate tnode} : #{ctx.translate fnode}" # ################################################################################################### # hash # ################################################################################################### trans.translator_hash["hash_pair_simple"] = translate:(ctx,node)-> [key, _skip, value] = node.value_array "#{key.value}:#{ctx.translate value}" trans.translator_hash["hash_pair_auto"] = translate:(ctx,node)-> [value] = node.value_array "#{value.value}:#{value.value}" trans.translator_hash['hash_wrap'] = translate:(ctx, node)-> list = deep ctx, node "{"+list.join('')+"}" # ################################################################################################### # array # ################################################################################################### trans.translator_hash["num_array"] = translate:(ctx, node)-> # [_skip1, a, _skip2, b, _skip3] = node.value_array a = +node.value_array[1].value_view b = +node.value_array[3].value_view if b - a > 20 """ (function() { var results = []; for (var i = #{a}; i <= #{b}; i++){ results.push(i); } return results; })() """ else if a - b > 20 """ (function() { var results = []; for (var i = #{a}; i >= #{b}; i--){ results.push(i); } return results; })() """ else "[#{[a..b].join ", "}]" # ################################################################################################### # access # ################################################################################################### trans.translator_hash["field_access"] = translate:(ctx,node)-> [root, _skip, field] = node.value_array "#{ctx.translate root}.#{field.value}" trans.translator_hash["array_access"] = translate:(ctx,node)-> [root, _skip, field, _skip] = node.value_array "#{ctx.translate root}[#{ctx.translate field}]" trans.translator_hash["opencl_access"] = translate:(ctx,node)-> [root, _skip, field] = node.value_array root_tr = ctx.translate root key = field.value if key.length == 1 return "#{root_tr}[#{key}]" # TODO ref ret = [] for k in key ret.push "#{root_tr}[#{k}]" "[#{ret.join ','}]" # ################################################################################################### # func_decl # ################################################################################################### trans.translator_hash["func_decl_return"] = translate:(ctx,node)-> str = ctx.translate node.value_array[0] "return(#{str})" trans.translator_hash["func_decl"] = translate:(ctx,node)-> arg_list = [] walk = (arg)-> default_value_node = null if arg.value_array.length == 1 name_node = arg.value_array[0] else if arg.value_array.length == 3 if arg.value_array[1].value == "=" name_node = arg.value_array[0] default_value_node= arg.value_array[2] else if arg.value_array[1].value == ":" ### !pragma coverage-skip-block ### throw new Error "types are unsupported arg syntax yet" else if arg.value_array[1].value == "," walk arg.value_array[0] walk arg.value_array[2] return else ### !pragma coverage-skip-block ### throw new Error "unsupported arg syntax" else ### !pragma coverage-skip-block ### throw new Error "unsupported arg syntax" default_value = null if default_value_node default_value = ctx.translate default_value_node arg_list.push { name : name_node.value or name_node.value_view type : null default_value } return if node.value_array[0].value == '(' and node.value_array[2].value == ')' arg_list_node = node.value_array[1] for arg in arg_list_node.value_array continue if arg.value == "," walk arg body_node = node.value_array.last() body_node = null if body_node.value in ["->", "=>"] # no body arg_str_list = [] default_arg_str_list = [] for arg in arg_list arg_str_list.push arg.name if arg.default_value default_arg_str_list.push """ #{arg.name}=#{arg.name}==null?#{ensure_bracket arg.default_value}:#{arg.name}; """ body = "" body = ctx.translate body_node if body_node body = """ { #{join_list default_arg_str_list, ' '} #{body} } """ body = body.replace /^{\s+/, '{\n ' body = body.replace /\s+}$/, '\n}' body = "{}" if /^\{\s+\}$/.test body "(function(#{arg_str_list.join ', '})#{body})" trans.translator_hash["func_call"] = translate:(ctx,node)-> rvalue = node.value_array[0] comma_rvalue_node = null for v in node.value_array if v.mx_hash.hash_key == '<KEY>' comma_rvalue_node = v arg_list = [] func_code = ensure_bracket ctx.translate rvalue if comma_rvalue_node walk = (node)-> for v in node.value_array if v.mx_hash.hash_key == '<KEY>' arg_list.push ctx.translate v if v.mx_hash.hash_key == '<KEY>' walk v rvalue walk comma_rvalue_node "#{func_code}(#{arg_list.join ', '})" # ################################################################################################### # macro-block # ################################################################################################### trans.macro_block_condition_hash = "if" : (ctx, condition, block)-> """ if (#{ctx.translate condition}) { #{make_tab ctx.translate(block), ' '} } """ "while" : (ctx, condition, block)-> """ while(#{ctx.translate condition}) { #{make_tab ctx.translate(block), ' '} } """ trans.macro_block_hash = "loop" : (ctx, block)-> """ while(true) { #{make_tab ctx.translate(block), ' '} } """ trans.translator_hash['macro_block'] = translate:(ctx,node)-> if node.value_array.length == 2 [name_node, body] = node.value_array name = name_node.value if !(fn = trans.macro_block_hash[name])? if trans.macro_block_condition_hash[name]? throw new Error "Missed condition for block '#{name}'" throw new Error "unknown conditionless macro block '#{name}'" fn ctx, body else [name_node, condition, body] = node.value_array name = name_node.value if !(fn = trans.macro_block_condition_hash[name])? if trans.macro_block_hash[name]? throw new Error "Extra condition for block '#{name}'" throw new Error "unknown conditionless macro block '#{name}'" fn ctx, condition, body # ################################################################################################### @_translate = (ast, opt={})-> trans.go ast @translate = (ast, opt, on_end)-> try res = module._translate ast, opt catch e return on_end e on_end null, res
true
require 'fy' require 'fy/lib/codegen' { Translator un_op_translator_holder un_op_translator_framework bin_op_translator_holder bin_op_translator_framework } = require 'gram2' module = @ # ################################################################################################### trans = new Translator trans.trans_skip = indent : true dedent : true eol : true trans.trans_value = bracket : true comma : true pair_separator: true arrow_function: true trans.trans_token = comment : (v)-> "//" + v.substr 1 deep = (ctx, node)-> list = [] # if node.mx_hash.deep? # node.mx_hash.deep = '0' if node.mx_hash.deep == false # special case for deep=0 # value_array = (node.value_array[pos] for pos in node.mx_hash.deep.split ',') # else # value_array = node.value_array value_array = node.value_array for v,k in value_array if trans.trans_skip[v.mx_hash.hash_key]? # LATER if node.mx_hash.eol_pass and v.mx_hash.hash_key == 'eol' list.push ";\n" else if fn = trans.trans_token[v.mx_hash.hash_key] list.push fn v.value else if trans.trans_value[v.mx_hash.hash_key]? list.push v.value else list.push ctx.translate v if delimiter = node.mx_hash.delimiter # delimiter = ' ' if delimiter == "'[SPACE]'" # not used -> commented list = [ list.join(delimiter) ] list trans.translator_hash['value'] = translate:(ctx, node)->node.value_view trans.translator_hash['deep'] = translate:(ctx, node)-> list = deep ctx, node list.join('') trans.translator_hash['block'] = translate:(ctx, node)-> list = deep ctx, node make_tab list.join(''), ' ' ensure_bracket = (t)-> return t if t[0] == "(" and t[t.length-1] == ")" "(#{t})" # ################################################################################################### # bin_op # ################################################################################################### do ()-> holder = new bin_op_translator_holder for v in "+ - * / % += -= *= /= %= = < <= > >= << >> >>>".split ' ' holder.op_list[v] = new bin_op_translator_framework "($1$op$2)" holder.op_list["**"] = new bin_op_translator_framework "Math.pow($1, $2)" holder.op_list["//"] = new bin_op_translator_framework "Math.floor($1 / $2)" holder.op_list["%%"] = new bin_op_translator_framework "(_tmp_b=$2,($1 % _tmp_b + _tmp_b) % _tmp_b)" holder.op_list["**="] = new bin_op_translator_framework "$1 = Math.pow($1, $2)" holder.op_list["//="] = new bin_op_translator_framework "$1 = Math.floor($1 / $2)" holder.op_list["%%="] = new bin_op_translator_framework "$1 = (_tmp_b=$2,($1 % _tmp_b + _tmp_b) % _tmp_b)" holder.op_list["=="] = new bin_op_translator_framework "($1===$2)" holder.op_list["!="] = new bin_op_translator_framework "($1!==$2)" trans.translator_hash['bin_op'] = translate:(ctx, node)-> op = node.value_array[1].value_view # PORTING BUG gram2 node.value_array[1].value = node.value_array[1].value_view # return is implied, I actually mean it. This if block is intended to be the last statement in the function. if op of holder.op_list holder.translate ctx, node else [a,_skip,b] = node.value_array a_tr = ctx.translate a b_tr = ctx.translate b logical_or_bitwise = (char) -> postfix = if op[-1..] == '=' then '=' else '' if a.mx_hash.type.toString() == "int" # type inference ensures the second operand to be int "(#{a_tr}#{char}#{postfix}#{b_tr})" else # type inference ensures operands to be bools if char == '^' if postfix "(#{a_tr}=!!(#{a_tr}^#{b_tr}))" else "(!!(#{a_tr}#{char}#{b_tr}))" else if postfix "(#{a_tr}=(#{a_tr}#{char}#{char}#{b_tr}))" else "(#{a_tr}#{char}#{char}#{b_tr})" switch op when "and", "and=" logical_or_bitwise '&' when "or", "or=" logical_or_bitwise '|' when "xor", "xor=" logical_or_bitwise '^' when '|' # pipes logic if b.mx_hash.type? switch b.mx_hash.type.main when "function" nest = b.mx_hash.type.nest # NOTE 1st nest == return type if nest.length == 2 # is_map "#{ensure_bracket a_tr}.map(#{b_tr})" else if nest.length == 3 ### TODO Array.prototype.async_map -> ?Promise? ?Promise?.prototype (need all Array stuff) ### if nest[2].main == 'function' # async map "#{ensure_bracket a_tr}.async_map(#{b_tr})" else # reduce "#{ensure_bracket a_tr}.reduce(#{b_tr})" else if nest.length == 4 if nest[3].main == 'function' # async reduce "#{ensure_bracket a_tr}.async_reduce(#{b_tr})" else throw new Error "unknown pipe function signature [1]" else throw new Error "unknown pipe function signature [2]" when "array" "#{b_tr} = #{a_tr}" when "Sink" """ var ref = #{ensure_bracket a_tr}; for (var i = 0, len = ref.length; i < len; i++) { #{b_tr}(ref[i]); } """ # else для switch не нужен т.к. не пропустит type inference else "#{b_tr} = #{a_tr}" else ### !pragma coverage-skip-block ### throw new Error "Translator: can't figure out how to translate '#{op}'" # Don't put code down here below if block without a good reason (unless you're ready for refactoring). # The preceding block should remain the last statement in the function as long as possible. # Here is some old code (maybe del later): # if op in ['or', 'and'] # # needs type inference # [a,_skip,b] = node.value_array # a_tr = ctx.translate a # b_tr = ctx.translate b # if !a.mx_hash.type? or !b.mx_hash.type? # throw new Error "can't translate op=#{op} because type inference can't detect type of arguments" # if !a.mx_hash.type.eq b.mx_hash.type # # не пропустит type inference # ### !pragma coverage-skip-block ### # throw new Error "can't translate op=#{op} because type mismatch #{a.mx_hash.type} != #{b.mx_hash.type}" # switch a.mx_hash.type.toString() # when 'int' # return "(#{a_tr}|#{b_tr})" # when 'bool' # return "(#{a_tr}||#{b_tr})" # else # # не пропустит type inference # ### !pragma coverage-skip-block ### # throw new Error "op=#{op} doesn't support type #{a.mx_hash.type}" # ################################################################################################### # pre_op # ################################################################################################### do ()-> holder = new un_op_translator_holder holder.mode_pre() for v in un_op_list = "~ + - !".split ' ' holder.op_list[v] = new un_op_translator_framework "$op$1" holder.op_list["void"] = new un_op_translator_framework "null" for v in un_op_list = "typeof new delete".split ' ' holder.op_list[v] = new un_op_translator_framework "($op $1)" # trans.translator_hash['pre_op'] = holder # PORTING BUG UGLY FIX gram2 trans.translator_hash['pre_op'] = translate:(ctx, node)-> op = node.value_array[0].value_view node.value_array[0].value = node.value_array[0].value_view if op == "not" a = node.value_array[1] a_tr = ctx.translate a if !a.mx_hash.type throw new Error "can't translate not operation because no type inferenced" if a.mx_hash.type.toString() == "int" "~#{a_tr}" else "!#{a_tr}" # type inference ensures bool else holder.translate ctx, node # ################################################################################################### # post_op # ################################################################################################### do ()-> holder = new un_op_translator_holder holder.mode_post() for v in un_op_list = ["++", '--'] holder.op_list[v] = new un_op_translator_framework "($1$op)" # trans.translator_hash['post_op'] = holder # PORTING BUG UGLY FIX gram2 trans.translator_hash['post_op'] = translate:(ctx, node)-> node.value_array[1].value = node.value_array[1].value_view holder.translate ctx, node # ################################################################################################### # str # ################################################################################################### trans.translator_hash['string_singleq'] = translate:(ctx, node)-> s = node.value_view[1...-1] s = s.replace /"/g, '\\"' s = s.replace /^\s+/g, '' s = s.replace /\s+$/g, '' s = s.replace /\s*\n\s*/g, ' ' '"' + s + '"' #" trans.translator_hash['string_doubleq'] = translate:(ctx, node)-> s = node.value_view s = s.replace /^"\s+/g, '"' s = s.replace /\s+"$/g, '"' s = s.replace /\s*\n\s*/g, ' ' trans.translator_hash['block_string_singleq'] = translate:(ctx, node)-> s = node.value_view[3...-3] s = s.replace /^\n/g, '' s = s.replace /\n$/g, '' s = s.replace /\n/g, '\\n' s = s.replace /"/g, '\\"' '"' + s + '"' trans.translator_hash['block_string_doubleq'] = trans.translator_hash['block_string_singleq'] # for now... trans.translator_hash['string_interpolation_prepare'] = translate:(ctx, node)-> ret = switch node.mx_hash.hash_key when 'st1_start' node.value_view[1...-2] # '"text#{' -> 'text' .replace(/^\s+/g, '') .replace /\s*\n\s*/g, ' ' when 'st3_start' node.value_view[3...-2] # '"""text#{' -> 'text' when 'st_mid' node.value_view[1...-2] # '}text#{' -> 'text' when 'st1_end' node.value_view[1...-1] # '}text"' -> 'text' .replace(/\s+$/g, '') .replace /\s*\n\s*/g, ' ' when 'st3_end' node.value_view[1...-3] # '}text"""' -> 'text' ret = ret.replace /"/, '\\"' trans.translator_hash['string_interpolation_put_together'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]) when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]) if children.last().mx_hash.hash_key[-3...] == "end" ret = '("' + ret + '")' ret = ret.replace /\+""/g, '' # some cleanup ret trans.translator_hash['string_interpolation_put_together_m1'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]).replace /\s*\n\s*/g, ' ' when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]).replace /\s*\n\s*/g, ' ' ret # ################################################################################################### # regexp # ################################################################################################### trans.translator_hash['block_regexp'] = translate:(ctx, node)-> [_skip, body, flags] = node.value_view.split "///" # '///ab+c///imgy' -> ['', 'ab+c', 'imgy'] body = body.replace /\s#.*/g, '' # comments body = body.replace /\s/g, '' # whitespace if body == "" body = "(?:)" else body = body.replace /\//g, '\\/' # escaping forward slashes '/' + body + '/' + flags trans.translator_hash['regexp_interpolation_prepare'] = translate:(ctx, node)-> switch node.mx_hash.hash_key when 'rextem_start' ret = node.value_view[3...-2] # '///ab+c#{' -> 'ab+c' when 'rextem_mid' ret = node.value_view[1...-2] # '}ab+c#{' -> 'ab+c' when 'rextem_end' [body, flags] = node.value_view.split "///" # '}ab+c///imgy' -> ['}ab+c', 'imgy'] node.flags = flags ret = body[1...] # '}ab+c' -> 'ab+c' ret = ret.replace /\s#.*/g, '' # comments ret = ret.replace /\s/g, '' # whitespace ret = ret.replace /"/g, '\\"' # escaping quotes trans.translator_hash['regexp_interpolation_put_together'] = translate:(ctx, node)-> children = node.value_array ret = switch children.length when 2 ctx.translate(children[0]) + ctx.translate(children[1]) when 3 ctx.translate(children[0]) + '"+' + ensure_bracket(ctx.translate(children[1])) + '+"' + ctx.translate(children[2]) last = children.last() if last.mx_hash.hash_key == "PI:KEY:<KEY>END_PI" ret += """","#{last.flags}""" if last.flags ret = """RegExp("#{ret}")""" ret = ret.replace /\+""/g, '' # 'RegExp("a"+"b")' -> 'RegExp("ab")' ret # ################################################################################################### # bracket # ################################################################################################### trans.translator_hash["bracket"] = translate:(ctx,node)-> ensure_bracket ctx.translate node.value_array[1] # ################################################################################################### # ternary # ################################################################################################### trans.translator_hash["ternary"] = translate:(ctx,node)-> [cond, _s1, tnode, _s2, fnode] = node.value_array "#{ctx.translate cond} ? #{ctx.translate tnode} : #{ctx.translate fnode}" # ################################################################################################### # hash # ################################################################################################### trans.translator_hash["hash_pair_simple"] = translate:(ctx,node)-> [key, _skip, value] = node.value_array "#{key.value}:#{ctx.translate value}" trans.translator_hash["hash_pair_auto"] = translate:(ctx,node)-> [value] = node.value_array "#{value.value}:#{value.value}" trans.translator_hash['hash_wrap'] = translate:(ctx, node)-> list = deep ctx, node "{"+list.join('')+"}" # ################################################################################################### # array # ################################################################################################### trans.translator_hash["num_array"] = translate:(ctx, node)-> # [_skip1, a, _skip2, b, _skip3] = node.value_array a = +node.value_array[1].value_view b = +node.value_array[3].value_view if b - a > 20 """ (function() { var results = []; for (var i = #{a}; i <= #{b}; i++){ results.push(i); } return results; })() """ else if a - b > 20 """ (function() { var results = []; for (var i = #{a}; i >= #{b}; i--){ results.push(i); } return results; })() """ else "[#{[a..b].join ", "}]" # ################################################################################################### # access # ################################################################################################### trans.translator_hash["field_access"] = translate:(ctx,node)-> [root, _skip, field] = node.value_array "#{ctx.translate root}.#{field.value}" trans.translator_hash["array_access"] = translate:(ctx,node)-> [root, _skip, field, _skip] = node.value_array "#{ctx.translate root}[#{ctx.translate field}]" trans.translator_hash["opencl_access"] = translate:(ctx,node)-> [root, _skip, field] = node.value_array root_tr = ctx.translate root key = field.value if key.length == 1 return "#{root_tr}[#{key}]" # TODO ref ret = [] for k in key ret.push "#{root_tr}[#{k}]" "[#{ret.join ','}]" # ################################################################################################### # func_decl # ################################################################################################### trans.translator_hash["func_decl_return"] = translate:(ctx,node)-> str = ctx.translate node.value_array[0] "return(#{str})" trans.translator_hash["func_decl"] = translate:(ctx,node)-> arg_list = [] walk = (arg)-> default_value_node = null if arg.value_array.length == 1 name_node = arg.value_array[0] else if arg.value_array.length == 3 if arg.value_array[1].value == "=" name_node = arg.value_array[0] default_value_node= arg.value_array[2] else if arg.value_array[1].value == ":" ### !pragma coverage-skip-block ### throw new Error "types are unsupported arg syntax yet" else if arg.value_array[1].value == "," walk arg.value_array[0] walk arg.value_array[2] return else ### !pragma coverage-skip-block ### throw new Error "unsupported arg syntax" else ### !pragma coverage-skip-block ### throw new Error "unsupported arg syntax" default_value = null if default_value_node default_value = ctx.translate default_value_node arg_list.push { name : name_node.value or name_node.value_view type : null default_value } return if node.value_array[0].value == '(' and node.value_array[2].value == ')' arg_list_node = node.value_array[1] for arg in arg_list_node.value_array continue if arg.value == "," walk arg body_node = node.value_array.last() body_node = null if body_node.value in ["->", "=>"] # no body arg_str_list = [] default_arg_str_list = [] for arg in arg_list arg_str_list.push arg.name if arg.default_value default_arg_str_list.push """ #{arg.name}=#{arg.name}==null?#{ensure_bracket arg.default_value}:#{arg.name}; """ body = "" body = ctx.translate body_node if body_node body = """ { #{join_list default_arg_str_list, ' '} #{body} } """ body = body.replace /^{\s+/, '{\n ' body = body.replace /\s+}$/, '\n}' body = "{}" if /^\{\s+\}$/.test body "(function(#{arg_str_list.join ', '})#{body})" trans.translator_hash["func_call"] = translate:(ctx,node)-> rvalue = node.value_array[0] comma_rvalue_node = null for v in node.value_array if v.mx_hash.hash_key == 'PI:KEY:<KEY>END_PI' comma_rvalue_node = v arg_list = [] func_code = ensure_bracket ctx.translate rvalue if comma_rvalue_node walk = (node)-> for v in node.value_array if v.mx_hash.hash_key == 'PI:KEY:<KEY>END_PI' arg_list.push ctx.translate v if v.mx_hash.hash_key == 'PI:KEY:<KEY>END_PI' walk v rvalue walk comma_rvalue_node "#{func_code}(#{arg_list.join ', '})" # ################################################################################################### # macro-block # ################################################################################################### trans.macro_block_condition_hash = "if" : (ctx, condition, block)-> """ if (#{ctx.translate condition}) { #{make_tab ctx.translate(block), ' '} } """ "while" : (ctx, condition, block)-> """ while(#{ctx.translate condition}) { #{make_tab ctx.translate(block), ' '} } """ trans.macro_block_hash = "loop" : (ctx, block)-> """ while(true) { #{make_tab ctx.translate(block), ' '} } """ trans.translator_hash['macro_block'] = translate:(ctx,node)-> if node.value_array.length == 2 [name_node, body] = node.value_array name = name_node.value if !(fn = trans.macro_block_hash[name])? if trans.macro_block_condition_hash[name]? throw new Error "Missed condition for block '#{name}'" throw new Error "unknown conditionless macro block '#{name}'" fn ctx, body else [name_node, condition, body] = node.value_array name = name_node.value if !(fn = trans.macro_block_condition_hash[name])? if trans.macro_block_hash[name]? throw new Error "Extra condition for block '#{name}'" throw new Error "unknown conditionless macro block '#{name}'" fn ctx, condition, body # ################################################################################################### @_translate = (ast, opt={})-> trans.go ast @translate = (ast, opt, on_end)-> try res = module._translate ast, opt catch e return on_end e on_end null, res
[ { "context": "(done) ->\n user = App.User.build(firstName: 'Lance')\n\n Tower.StoreTransportAjax.create [user], ", "end": 845, "score": 0.9994208812713623, "start": 840, "tag": "NAME", "value": "Lance" }, { "context": "(done) ->\n user = App.User.build(firstName: 'Lance')\n\n Tower.StoreTransportAjax.create [user], ", "end": 1508, "score": 0.9994070529937744, "start": 1503, "tag": "NAME", "value": "Lance" }, { "context": "'success', (done) ->\n user.set('firstName', 'John')\n\n Tower.StoreTransportAjax.update [user], ", "end": 1689, "score": 0.9889405369758606, "start": 1685, "tag": "NAME", "value": "John" }, { "context": "(done) ->\n user = App.User.build(firstName: 'Lance')\n\n Tower.StoreTransportAjax.create [user], ", "end": 2021, "score": 0.9997197389602661, "start": 2016, "tag": "NAME", "value": "Lance" }, { "context": ") ->\n criteria = App.User.where(firstName: 'L').compile()\n \n Tower.StoreTransportAjax", "end": 2434, "score": 0.9331391453742981, "start": 2433, "tag": "NAME", "value": "L" } ]
test/cases/store/client/ajaxTest.coffee
jivagoalves/tower
1
describe 'Tower.StoreTransportAjax', -> describe 'params', -> test 'conditions', -> criteria = App.User.where(firstName: '=~': 'L').compile() params = criteria.toParams() expected = conditions: firstName: '=~': 'L' assert.deepEqual expected, params test 'conditions, pagination and sort', -> criteria = App.User.where(firstName: {'=~': 'L'}, lastName: {'=~': 'l'}).page(2).limit(2).asc('lastName').compile() params = criteria.toParams() expected = conditions: firstName: '=~': 'L' lastName: '=~': 'l' limit: 2 page: 2 sort: [ ['lastName', 'asc'] ] assert.deepEqual expected, params describe 'create', -> test 'success', (done) -> user = App.User.build(firstName: 'Lance') Tower.StoreTransportAjax.create [user], (error, updatedUser) => assert.isTrue !!updatedUser done() #test 'failure', (done) -> # user = App.User.build() # # Tower.StoreTransportAjax.create user, (error, updatedUser) => # assert.ok !error # done() # #test 'error (before it even makes a request)', (done) -> # user = {} # # Tower.StoreTransportAjax.create user, (error, updatedUser) => # assert.ok !error # done() describe 'update', -> user = null # need to create some records on the server first... beforeEach (done) -> user = App.User.build(firstName: 'Lance') Tower.StoreTransportAjax.create [user], (error, updatedUser) => user = updatedUser done() test 'success', (done) -> user.set('firstName', 'John') Tower.StoreTransportAjax.update [user], (error, updatedUser) => assert.isTrue !!updatedUser done() test 'failure' test 'error' describe 'destroy', -> user = null # need to create some records on the server first... beforeEach (done) -> user = App.User.build(firstName: 'Lance') Tower.StoreTransportAjax.create [user], (error, updatedUser) => user = updatedUser done() test 'success', (done) -> Tower.StoreTransportAjax.destroy [user], (error, destroyedUser) => assert.isTrue !!destroyedUser done() test 'failure' test 'error' describe 'find', -> test 'conditions', (done) -> criteria = App.User.where(firstName: 'L').compile() Tower.StoreTransportAjax.find criteria, (error, data) => assert.isTrue !!data done()
105451
describe 'Tower.StoreTransportAjax', -> describe 'params', -> test 'conditions', -> criteria = App.User.where(firstName: '=~': 'L').compile() params = criteria.toParams() expected = conditions: firstName: '=~': 'L' assert.deepEqual expected, params test 'conditions, pagination and sort', -> criteria = App.User.where(firstName: {'=~': 'L'}, lastName: {'=~': 'l'}).page(2).limit(2).asc('lastName').compile() params = criteria.toParams() expected = conditions: firstName: '=~': 'L' lastName: '=~': 'l' limit: 2 page: 2 sort: [ ['lastName', 'asc'] ] assert.deepEqual expected, params describe 'create', -> test 'success', (done) -> user = App.User.build(firstName: '<NAME>') Tower.StoreTransportAjax.create [user], (error, updatedUser) => assert.isTrue !!updatedUser done() #test 'failure', (done) -> # user = App.User.build() # # Tower.StoreTransportAjax.create user, (error, updatedUser) => # assert.ok !error # done() # #test 'error (before it even makes a request)', (done) -> # user = {} # # Tower.StoreTransportAjax.create user, (error, updatedUser) => # assert.ok !error # done() describe 'update', -> user = null # need to create some records on the server first... beforeEach (done) -> user = App.User.build(firstName: '<NAME>') Tower.StoreTransportAjax.create [user], (error, updatedUser) => user = updatedUser done() test 'success', (done) -> user.set('firstName', '<NAME>') Tower.StoreTransportAjax.update [user], (error, updatedUser) => assert.isTrue !!updatedUser done() test 'failure' test 'error' describe 'destroy', -> user = null # need to create some records on the server first... beforeEach (done) -> user = App.User.build(firstName: '<NAME>') Tower.StoreTransportAjax.create [user], (error, updatedUser) => user = updatedUser done() test 'success', (done) -> Tower.StoreTransportAjax.destroy [user], (error, destroyedUser) => assert.isTrue !!destroyedUser done() test 'failure' test 'error' describe 'find', -> test 'conditions', (done) -> criteria = App.User.where(firstName: '<NAME>').compile() Tower.StoreTransportAjax.find criteria, (error, data) => assert.isTrue !!data done()
true
describe 'Tower.StoreTransportAjax', -> describe 'params', -> test 'conditions', -> criteria = App.User.where(firstName: '=~': 'L').compile() params = criteria.toParams() expected = conditions: firstName: '=~': 'L' assert.deepEqual expected, params test 'conditions, pagination and sort', -> criteria = App.User.where(firstName: {'=~': 'L'}, lastName: {'=~': 'l'}).page(2).limit(2).asc('lastName').compile() params = criteria.toParams() expected = conditions: firstName: '=~': 'L' lastName: '=~': 'l' limit: 2 page: 2 sort: [ ['lastName', 'asc'] ] assert.deepEqual expected, params describe 'create', -> test 'success', (done) -> user = App.User.build(firstName: 'PI:NAME:<NAME>END_PI') Tower.StoreTransportAjax.create [user], (error, updatedUser) => assert.isTrue !!updatedUser done() #test 'failure', (done) -> # user = App.User.build() # # Tower.StoreTransportAjax.create user, (error, updatedUser) => # assert.ok !error # done() # #test 'error (before it even makes a request)', (done) -> # user = {} # # Tower.StoreTransportAjax.create user, (error, updatedUser) => # assert.ok !error # done() describe 'update', -> user = null # need to create some records on the server first... beforeEach (done) -> user = App.User.build(firstName: 'PI:NAME:<NAME>END_PI') Tower.StoreTransportAjax.create [user], (error, updatedUser) => user = updatedUser done() test 'success', (done) -> user.set('firstName', 'PI:NAME:<NAME>END_PI') Tower.StoreTransportAjax.update [user], (error, updatedUser) => assert.isTrue !!updatedUser done() test 'failure' test 'error' describe 'destroy', -> user = null # need to create some records on the server first... beforeEach (done) -> user = App.User.build(firstName: 'PI:NAME:<NAME>END_PI') Tower.StoreTransportAjax.create [user], (error, updatedUser) => user = updatedUser done() test 'success', (done) -> Tower.StoreTransportAjax.destroy [user], (error, destroyedUser) => assert.isTrue !!destroyedUser done() test 'failure' test 'error' describe 'find', -> test 'conditions', (done) -> criteria = App.User.where(firstName: 'PI:NAME:<NAME>END_PI').compile() Tower.StoreTransportAjax.find criteria, (error, data) => assert.isTrue !!data done()
[ { "context": "tml(), \"some name\"\n c.scope.model.set \"name\", \"new name\"\n assert.equal h.$el.html(), \"new name\"\n\n h", "end": 3573, "score": 0.9001052975654602, "start": 3565, "tag": "NAME", "value": "new name" }, { "context": " ->\n c.scope.model = new Backbone.Model(name: \"some name\")\n h = new Neck.Helper.bind parent: c, el: $(\"", "end": 3862, "score": 0.9249686002731323, "start": 3853, "tag": "NAME", "value": "some name" }, { "context": "el\"\n c.scope.model = new Backbone.Model(name: \"new name\")\n\n assert.equal h.el.innerHTML, \"new name\"\n\n ", "end": 4024, "score": 0.9075853824615479, "start": 4016, "tag": "NAME", "value": "new name" }, { "context": " ->\n c.scope.model = new Backbone.Model(name: \"some name\")\n h = new Neck.Helper.bind parent: c, el: $(\"", "end": 4186, "score": 0.9269248843193054, "start": 4177, "tag": "NAME", "value": "some name" } ]
test/spec/helpers/bind.coffee
smalluban/neck
5
describe '[ui-bind]', -> c = null beforeEach -> c = new Neck.Controller() c.scope.text = 'someValue' c.scope.htmlText = '<b>someValue</b>' c.scope.boolTrue = true c.scope.boolFalse = false it 'should set proper value and listen changes', -> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" assert.equal h.el.outerHTML, "<div>someValue</div>" c.scope.text = 'newValue' assert.equal h.el.outerHTML, "<div>newValue</div>" h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "htmlText" assert.equal h.el.outerHTML, "<div><b>someValue</b></div>" h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "text" assert.equal h.$el.val(), "newValue" c.scope.text = 'someValue' assert.equal h.$el.val(), "someValue" h = new Neck.Helper.bind parent: c, el: $('<input type="checkbox"/>'), mainAttr: "boolTrue" assert.equal h.$el.prop('checked'), true c.scope.boolTrue = false assert.equal h.$el.prop('checked'), false it 'should set number value', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "number" h.$el.val 12.12 h.$el.trigger "change" setTimeout -> assert.equal c.scope.number, 12.12 assert.isNumber c.scope.number done() it 'should set number value as string', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text" bind-number="false" />'), mainAttr: "number" h.$el.val 12.12 h.$el.trigger "change" setTimeout -> assert.equal c.scope.number, "12.12" assert.isString c.scope.number done() it 'should listen to updates from input change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "text" assert.equal h.$el.val(), "someValue" h.$el.val "newValue" h.$el.trigger "change" setTimeout -> assert.equal c.scope.text, "newValue" done() it 'should listen to updates from checkbox change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="checkbox"/>'), mainAttr: "boolTrue" assert.equal h.$el.prop('checked'), true h.$el.prop "checked", false h.$el.trigger "change" setTimeout -> assert.equal c.scope.boolTrue, false done() it 'should listen to updates from node change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" h.el.innerHTML = "<b>newValue</b>" h.$el.trigger "change" setTimeout -> assert.equal c.scope.text, "<b>newValue</b>" done() it 'should not throw error when update trigger remove helper', -> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" assert.doesNotThrow -> h.$el.trigger "change" h.remove() it "should throw error for model without 'bind-property' set", -> assert.throw -> c.scope.model = new Backbone.Model() h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "model" it "should throw error for 'bind-property' not set as string", -> assert.throw -> c.scope.model = new Backbone.Model() h = new Neck.Helper.bind parent: c, el: $('<div bind-property="123"></div>'), mainAttr: "model" it "should bind Backbone.Model attribute", (done)-> c.scope.model = new Backbone.Model(name: "some name") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" assert.equal h.$el.html(), "some name" c.scope.model.set "name", "new name" assert.equal h.$el.html(), "new name" h.el.innerHTML = "some name" h.$el.trigger "change" setTimeout -> assert.equal c.scope.model.get("name"), "some name" done() it "should listen to new model", -> c.scope.model = new Backbone.Model(name: "some name") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" c.scope.model = new Backbone.Model(name: "new name") assert.equal h.el.innerHTML, "new name" it "should listen to new property other than model", -> c.scope.model = new Backbone.Model(name: "some name") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" c.scope.model = "asd" assert.equal h.el.innerHTML, "asd"
111244
describe '[ui-bind]', -> c = null beforeEach -> c = new Neck.Controller() c.scope.text = 'someValue' c.scope.htmlText = '<b>someValue</b>' c.scope.boolTrue = true c.scope.boolFalse = false it 'should set proper value and listen changes', -> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" assert.equal h.el.outerHTML, "<div>someValue</div>" c.scope.text = 'newValue' assert.equal h.el.outerHTML, "<div>newValue</div>" h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "htmlText" assert.equal h.el.outerHTML, "<div><b>someValue</b></div>" h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "text" assert.equal h.$el.val(), "newValue" c.scope.text = 'someValue' assert.equal h.$el.val(), "someValue" h = new Neck.Helper.bind parent: c, el: $('<input type="checkbox"/>'), mainAttr: "boolTrue" assert.equal h.$el.prop('checked'), true c.scope.boolTrue = false assert.equal h.$el.prop('checked'), false it 'should set number value', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "number" h.$el.val 12.12 h.$el.trigger "change" setTimeout -> assert.equal c.scope.number, 12.12 assert.isNumber c.scope.number done() it 'should set number value as string', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text" bind-number="false" />'), mainAttr: "number" h.$el.val 12.12 h.$el.trigger "change" setTimeout -> assert.equal c.scope.number, "12.12" assert.isString c.scope.number done() it 'should listen to updates from input change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "text" assert.equal h.$el.val(), "someValue" h.$el.val "newValue" h.$el.trigger "change" setTimeout -> assert.equal c.scope.text, "newValue" done() it 'should listen to updates from checkbox change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="checkbox"/>'), mainAttr: "boolTrue" assert.equal h.$el.prop('checked'), true h.$el.prop "checked", false h.$el.trigger "change" setTimeout -> assert.equal c.scope.boolTrue, false done() it 'should listen to updates from node change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" h.el.innerHTML = "<b>newValue</b>" h.$el.trigger "change" setTimeout -> assert.equal c.scope.text, "<b>newValue</b>" done() it 'should not throw error when update trigger remove helper', -> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" assert.doesNotThrow -> h.$el.trigger "change" h.remove() it "should throw error for model without 'bind-property' set", -> assert.throw -> c.scope.model = new Backbone.Model() h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "model" it "should throw error for 'bind-property' not set as string", -> assert.throw -> c.scope.model = new Backbone.Model() h = new Neck.Helper.bind parent: c, el: $('<div bind-property="123"></div>'), mainAttr: "model" it "should bind Backbone.Model attribute", (done)-> c.scope.model = new Backbone.Model(name: "some name") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" assert.equal h.$el.html(), "some name" c.scope.model.set "name", "<NAME>" assert.equal h.$el.html(), "new name" h.el.innerHTML = "some name" h.$el.trigger "change" setTimeout -> assert.equal c.scope.model.get("name"), "some name" done() it "should listen to new model", -> c.scope.model = new Backbone.Model(name: "<NAME>") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" c.scope.model = new Backbone.Model(name: "<NAME>") assert.equal h.el.innerHTML, "new name" it "should listen to new property other than model", -> c.scope.model = new Backbone.Model(name: "<NAME>") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" c.scope.model = "asd" assert.equal h.el.innerHTML, "asd"
true
describe '[ui-bind]', -> c = null beforeEach -> c = new Neck.Controller() c.scope.text = 'someValue' c.scope.htmlText = '<b>someValue</b>' c.scope.boolTrue = true c.scope.boolFalse = false it 'should set proper value and listen changes', -> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" assert.equal h.el.outerHTML, "<div>someValue</div>" c.scope.text = 'newValue' assert.equal h.el.outerHTML, "<div>newValue</div>" h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "htmlText" assert.equal h.el.outerHTML, "<div><b>someValue</b></div>" h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "text" assert.equal h.$el.val(), "newValue" c.scope.text = 'someValue' assert.equal h.$el.val(), "someValue" h = new Neck.Helper.bind parent: c, el: $('<input type="checkbox"/>'), mainAttr: "boolTrue" assert.equal h.$el.prop('checked'), true c.scope.boolTrue = false assert.equal h.$el.prop('checked'), false it 'should set number value', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "number" h.$el.val 12.12 h.$el.trigger "change" setTimeout -> assert.equal c.scope.number, 12.12 assert.isNumber c.scope.number done() it 'should set number value as string', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text" bind-number="false" />'), mainAttr: "number" h.$el.val 12.12 h.$el.trigger "change" setTimeout -> assert.equal c.scope.number, "12.12" assert.isString c.scope.number done() it 'should listen to updates from input change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="text"/>'), mainAttr: "text" assert.equal h.$el.val(), "someValue" h.$el.val "newValue" h.$el.trigger "change" setTimeout -> assert.equal c.scope.text, "newValue" done() it 'should listen to updates from checkbox change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<input type="checkbox"/>'), mainAttr: "boolTrue" assert.equal h.$el.prop('checked'), true h.$el.prop "checked", false h.$el.trigger "change" setTimeout -> assert.equal c.scope.boolTrue, false done() it 'should listen to updates from node change', (done)-> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" h.el.innerHTML = "<b>newValue</b>" h.$el.trigger "change" setTimeout -> assert.equal c.scope.text, "<b>newValue</b>" done() it 'should not throw error when update trigger remove helper', -> h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "text" assert.doesNotThrow -> h.$el.trigger "change" h.remove() it "should throw error for model without 'bind-property' set", -> assert.throw -> c.scope.model = new Backbone.Model() h = new Neck.Helper.bind parent: c, el: $('<div/>'), mainAttr: "model" it "should throw error for 'bind-property' not set as string", -> assert.throw -> c.scope.model = new Backbone.Model() h = new Neck.Helper.bind parent: c, el: $('<div bind-property="123"></div>'), mainAttr: "model" it "should bind Backbone.Model attribute", (done)-> c.scope.model = new Backbone.Model(name: "some name") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" assert.equal h.$el.html(), "some name" c.scope.model.set "name", "PI:NAME:<NAME>END_PI" assert.equal h.$el.html(), "new name" h.el.innerHTML = "some name" h.$el.trigger "change" setTimeout -> assert.equal c.scope.model.get("name"), "some name" done() it "should listen to new model", -> c.scope.model = new Backbone.Model(name: "PI:NAME:<NAME>END_PI") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" c.scope.model = new Backbone.Model(name: "PI:NAME:<NAME>END_PI") assert.equal h.el.innerHTML, "new name" it "should listen to new property other than model", -> c.scope.model = new Backbone.Model(name: "PI:NAME:<NAME>END_PI") h = new Neck.Helper.bind parent: c, el: $("<div bind-property=\"'name'\"></div>"), mainAttr: "model" c.scope.model = "asd" assert.equal h.el.innerHTML, "asd"
[ { "context": " = {} #set of visited coordinates\n key = (x,y) -> \"\"+x+\"#\"+y\n has_cell = (x,y) -> mpattern.hasOwnProperty key", "end": 22674, "score": 0.7938884496688843, "start": 22664, "tag": "KEY", "value": "\"\"+x+\"#\"+y" } ]
tools/collider.coffee
Kosx-Kosx/js-revca
25
#!/usr/bin/env coffee "use strict" # Particle collider. # Make collision table fs = require "fs" {Cells, inverseTfm, evaluateCellList, getDualTransform, splitPattern} = require "../scripts-src/cells" {from_list_elem, parseElementary} = require "../scripts-src/rules" stdio = require "stdio" {mod,mod2} = require "../scripts-src/math_util" #GIven 2 3-vectors, return 3-ort, that forms full basis with both vectors opposingOrt = (v1, v2) -> for i in [0..2] ort = [0,0,0] ort[i] = 1 if isCompleteBasis v1, v2, ort return [i, ort] throw new Error "Two vectors are collinear" #Scalar product of 2 vectors dot = (a,b) -> s = 0 for ai, i in a s += ai*b[i] return s #project 3-vector vec to the null-space of ort #projectToNullSpace = (ort, vec) -> # if dot(ort,ort) isnt 1 # throw new Error "Not an ort!" # p = dot ort, vec # # return (vec[i] - ort[i]*p for i in [0...3] ) #Remove component from a vector removeComponent =( vec, index) -> result = [] for xi, i in vec if i isnt index result.push xi return result restoreComponent = (vec, index) -> #insert 0 into index i v = vec[..] v.splice index, 0, 0 return v isCompleteBasis = (v1, v2, v3) -> #determinant of a matrix of 3 vectors. copipe from maxima det = v1[0]*(v2[1]*v3[2]-v3[1]*v2[2])-v1[1]*(v2[0]*v3[2]-v3[0]*v2[2])+(v2[0]*v3[1]-v3[0]*v2[1])*v1[2] return det isnt 0 #Area of a tetragon, built on 2 vectors. May be negative. area2d = ([x1,y1],[x2,y2]) -> x1*y2 - x2*y1 vecSum = (v1, v2) -> (v1i+v2[i] for v1i, i in v1) vecDiff = (v1, v2) -> (v1i-v2[i] for v1i, i in v1) vecScale = (v1, k) -> (v1i*k for v1i in v1) #Returns list of coordinates of points in elementary cell # both vectors must be 2d, nonzero, non-collinear elementaryCell2d = (v1, v2) -> #vertices [x1,y1] = v1 [x2,y2] = v2 if area2d(v1,v2) is 0 throw new Error "vectors are collinear!" #orient vectors if x1 < 0 x1 = -x1 y1 = -y1 if x2 < 0 x2 = -x2 y2 = -y2 # x intervals: # 0, min(x1,x2), max(x1,x2), x1+x2 xs = [0, x1, x2, x1+x2] xmin = Math.min xs ... xmax = Math.max xs ... ys = [0, y1, y2, y1+y2] ymin = Math.min ys ... ymax = Math.max ys ... d = x2*y1-x1*y2 #determinant of the equation s = if d < 0 then -1 else 1 points = [] for x in [xmin .. xmax] by 1 for y in [ymin .. ymax] by 1 #check that the point belongs to the rhombus #[t1 = (x2*y-x*y2)/d, # t2 = -(x1*y-x*y1)/d] #condition is: t1,2 in [0, 1) if ( 0 <= (x2*y-x*y2)*s < d*s ) and ( 0 <= -(x1*y-x*y1)*s < d*s ) points.push [x,y] return points #Calculate parameters of the collision: # collision time, nearest node points, collision distance. # pos : position [x, y, t] # delta : velocity and period [dx, dy, dt] collisionParameters = (pos0, delta0, pos1, delta1) -> #pos and delta are 3-vectors: (x,y,t) # #deltax : dx+a*vx0-b*vx1; #deltay : dy+a*vy0-b*vy1; #deltat : dt+a*p0-b*p1; # Dropbox.Math.spaceship-collision [dx, dy, dt] = vecDiff pos0, pos1 [vx0, vy0, p0] = delta0 [vx1, vy1, p1] = delta1 # D = p0**2*vy1**2-2*p0*p1*vy0*vy1+p1**2*vy0**2 + p0**2*vx1**2-2*p0*p1*vx0*vx1+p1**2*vx0**2 D = (p0*vy1 - p1*vy0)**2 + (p0*vx1-p1*vx0)**2 a = -(dt*p0*vy1**2+(-dt*p1*vy0-dy*p0*p1)*vy1+dy*p1**2*vy0+dt*p0*vx1**2+(-dt*p1*vx0-dx*p0*p1)*vx1+dx*p1**2*vx0) / D b = -((dt*p0*vy0-dy*p0**2)*vy1-dt*p1*vy0**2+dy*p0*p1*vy0+(dt*p0*vx0-dx*p0**2)*vx1-dt*p1*vx0**2+dx*p0*p1*vx0) / D dist = Math.abs(dt*vx0*vy1-dx*p0*vy1-dt*vx1*vy0+dx*p1*vy0+dy*p0*vx1-dy*p1*vx0)/Math.sqrt(D) #nearest points with time before collision time ia = Math.floor(a)|0 ib = Math.floor(b)|0 npos0 = vecSum pos0, vecScale(delta0, ia) npos1 = vecSum pos1, vecScale(delta1, ib) tcoll = pos0[2] + delta0[2]*a tcoll1 = pos1[2] + delta1[2]*b #must be same as tcoll1 if Math.abs(tcoll-tcoll1) > 1e-6 then throw new Error "assert: tcoll" return { dist: dist #distance of the nearest approach npos0: npos0 npos1: npos1 #node point nearest to the collision (below) tcoll: tcoll #when nearest approach occurs } #In what rande DX can change, if minimal distanec between 2 patterns is less than dmax? # This fucntion gives the answer. # Calculation is in the maxima sheet: # solve( d2 = dd^2, dx ); dxRange = (dPos, v0, v1, dMax) -> #dPos, v0, v1 :: vector3 #dMax :: integer [_, dy, dt] = dPos #dx is ignored, because we will find its diapason [vx0, vy0, p0] = v0 [vx1, vy1, p1] = v1 #Solution from Maxima: # dx=-(dd*sqrt(p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2+p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2)-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0)/(p0*vy1-p1*vy0) # q = p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2+p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2 # # dx=(+-dd*sqrt(q)-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0)/(p1*vy0 - p0*vy1) num = p1*vy0 - p0*vy1 if num is 0 #throw new Error "Patterns are parallel and neveer touch" return [0, -1] dc = (-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0) / num #q = p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2 + p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2 q = (p0*vy1-p1*vy0)**2 + (p0*vx1-p1*vx0)**2 #after small simplification delta = Math.abs(Math.sqrt(q) * (dMax / num)) #return upper and lower limits, rounded to integers return [Math.floor(dc - delta)|0, Math.ceil(dc + delta)|0] #Same as dxRange, but for dy. Reuses dxRange dyRange = (dPos, v0, v1, dMax) -> swapxy = ([x,y,t]) -> [y,x,t] dxRange swapxy(dPos), swapxy(v0), swapxy(v1), dMax #Chooses one of dxRange, dyRange. freeIndexRange = (dPos, v0, v1, dMax, index) -> if index not in [0..1] then throw new Error "Unsupported index #{index}" [dxRange, dyRange][index](dPos, v0, v1, dMax) #Calculate time, when 2 spaceship approach to the specified distance. approachParameters = (pos0, delta0, pos1, delta1, approachDistance) -> [dx, dy, dt] = vecDiff pos0, pos1 [vx0, vy0, p0] = delta0 [vx1, vy1, p1] = delta1 #solve( [deltax^2 + deltay^2 = dd^2, deltat=0], [a,b] ); dd = approachDistance D = (p0**2*vy1**2-2*p0*p1*vy0*vy1+p1**2*vy0**2+p0**2*vx1**2-2*p0*p1*vx0*vx1+p1**2*vx0**2) #thanks maxima. The formula is not well optimized, but I don't care. Q2 = (-dt**2*vx0**2+2*dt*dx*p0*vx0+(dd**2-dx**2)*p0**2)*vy1**2+(((2*dt**2*vx0-2*dt*dx*p0)*vx1-2*dt*dx*p1*vx0+(2*dx**2-2*dd**2)*p0*p1)*vy0+(2*dx*dy*p0**2-2*dt*dy*p0*vx0)*vx1+2*dt*dy*p1*vx0**2-2*dx*dy*p0*p1*vx0)*vy1+(-dt**2*vx1**2+2*dt*dx*p1*vx1+(dd**2-dx**2)*p1**2)*vy0**2+(2*dt*dy*p0*vx1**2+(-2*dt*dy*p1*vx0-2*dx*dy*p0*p1)*vx1+2*dx*dy*p1**2*vx0)*vy0+(dd**2-dy**2)*p0**2*vx1**2+(2*dy**2-2*dd**2)*p0*p1*vx0*vx1+(dd**2-dy**2)*p1**2*vx0**2 if Q2 < 0 #Approach not possible, spaceships are not coming close enough return {approach: false} Q = Math.sqrt(Q2) a = -(p1*Q+dt*p0*vy1**2+(-dt*p1*vy0-dy*p0*p1)*vy1+dy*p1**2*vy0+dt*p0*vx1**2+(-dt*p1*vx0-dx*p0*p1)*vx1+dx*p1**2*vx0) / D b = -(p0*Q+(dt*p0*vy0-dy*p0**2)*vy1-dt*p1*vy0**2+dy*p0*p1*vy0+(dt*p0*vx0-dx*p0**2)*vx1-dt*p1*vx0**2+dx*p0*p1*vx0) / D tapp = pos0[2]+p0*a tapp1 = pos1[2]+p1*b if Math.abs(tapp1-tapp) >1e-6 then throw new Error "Assertion failed" ia = Math.floor(a)|0 ib = Math.floor(b)|0 npos0 = vecSum pos0, vecScale(delta0, ia) npos1 = vecSum pos1, vecScale(delta1, ib) return { approach: true npos0 : npos0 #nearest positions before approach npos1 : npos1 tapp : tapp } #Give n position: [x,y,t] and delta: [dx,dy,dt], # Return position with biggest time <= t (inclusive). firstPositionBefore = (pos, delta, time) -> # find integer i: # t + i*dt < time # # i*dt < time - t # i < (time-t)/dt i0 = (time - pos[2]) / delta[2] #not integer. #now find the nearest integer below i = (Math.floor i0) |0 #and return the position vecSum pos, vecScale delta, i #Given spaceship trajectory, returns first it position before the given moment of time (inclusive) firstPositionAfter = (pos, delta, time) -> i0 = (time - pos[2]) / delta[2] #not integer. i = (Math.ceil i0) |0 vecSum pos, vecScale delta, i #Normalize pattern and returns its rle. normalizedRle = (fld) -> ff = Cells.copy fld Cells.normalize ff Cells.to_rle ff evalToTime = (rule, fld, t0, tend) -> if t > tend then throw new Error "assert: bad time" for t in [t0 ... tend] by 1 fld = evaluateCellList rule, fld, mod2(t) return fld #put the pattern to the specified time and position, and return its state at time t patternAt = (rule, pattern, posAndTime, t) -> pattern = Cells.copy pattern [x0,y0,t0] = posAndTime Cells.offset pattern, x0, y0 evalToTime rule, pattern, t0, t # Collide 2 patterns: p1 and p2, # p1 at [0,0,0] and p2 at `offset`. # initialSeparation::int approximate initial distance to put patterns at. Should be large enought for patterns not to intersect # offset: [dx, dy, dt] - initial offset of the pattern p2 (p1 at 000) # collisionTreshold:: if patterns don't come closer than this distance, don't consider them colliding. # waitForCollision::int How many generations to wait after the approximate nearest approach, until the interaction would start. # # Returned value: object # collision::bool true if collision # patterns :: [p1, p2] two patterns # offsets :: [vec1, vec2] first position of each pattern before collision time # timeStart::int first generation, where interaction has started # products::[ ProductDesc ] list of collision products (patterns with their positions and classification doCollision = (rule, library, p1, v1, p2, v2, offset, initialSeparation = 30, collisionTreshold=20)-> waitForCollision = v1[2] + v2[2] #sum of periods params = collisionParameters [0,0,0], v1, offset, v2 ap = approachParameters [0,0,0], v1, offset, v2, initialSeparation collision = {collision:false} if not ap.approach #console.log "#### No approach, nearest approach: #{params.dist}" return collision if params.dist > collisionTreshold #console.log "#### Too far, nearest approach #{params.dist} > #{collisionTreshold}" return collision #console.log "#### CP: #{JSON.stringify params}" #console.log "#### AP: #{JSON.stringify ap}" #Create the initial field. Put 2 patterns: p1 and p2 at initial time #nwo promote them to the same time, using list evaluation time = Math.max ap.npos0[2], ap.npos1[2] fld1 = patternAt rule, p1, ap.npos0, time fld2 = patternAt rule, p2, ap.npos1, time #OK, collision prepared. Now simulate both spaceships separately and # together, waiting while interaction occurs timeGiveUp = params.tcoll + waitForCollision #when to stop waiting for some interaction coll = simulateUntilCollision rule, [fld1, fld2], time, timeGiveUp fld1 = fld2 = null #They are not needed anymore if not coll.collided #console.log "#### No interaction detected until T=#{timeGiveUp}. Give up." return collision #console.log "#### colliding:" #console.log "#### 1) #{normalizedRle p1} at [0, 0, 0]" #console.log "#### 2) #{normalizedRle p2} at #{JSON.stringify offset}" #console.log "#### collision at T=#{coll.time} (give up at #{timeGiveUp})" collision.timeStart = coll.time collision.patterns = [p1, p2] collision.offsets = [ firstPositionBefore([0,0,0], v1, coll.time-1), firstPositionBefore(offset, v2, coll.time-1), ] collision.collision = true {products, verifyTime, verifyField} = finishCollision rule, library, coll.field, coll.time collision.products = products #findEmergeTime = (rule, products, minimalTime) -> collision.timeEnd = findEmergeTime rule, collision.products, collision.timeStart, verifyField, verifyTime #Update positions of products for product in collision.products product.pos = firstPositionAfter product.pos, product.delta, collision.timeEnd+1 #normalize relative to the first spaceship translateCollision collision, vecScale(collision.offsets[0], -1) #Offser collision information record by the given amount, in time and space translateCollision = (collision, dpos) -> [dx, dy, dt] = dpos for o, i in collision.offsets collision.offsets[i] = vecSum o, dpos collision.timeStart += dt collision.timeEnd += dt for product in collision.products product.pos = vecSum product.pos, dpos return collision #Simulate several patterns until they collide. # Return first oment of time, when patterns started interacting. simulateUntilCollision = (rule, patterns, time, timeGiveUp) -> if patterns.length < 2 then return {collided: false} # 1 pattern can't collide. fld = [].concat patterns ... #concatenate all patterns while time < timeGiveUp phase = mod2 time #evaluate each pattern separately #console.log "### patterns: #{JSON.stringify patterns}" patterns = (evaluateCellList(rule, p, phase) for p in patterns) #console.log "### after eval: #{JSON.stringify patterns}" #And together fld = evaluateCellList rule, fld, phase time += 1 #check if they are different mergedPatterns = [].concat patterns... Cells.sortXY fld Cells.sortXY mergedPatterns if not Cells.areEqual fld, mergedPatterns #console.log "#### Collision detected! T=#{time}, #{normalizedRle fld}" return { collided: true time: time field: fld } return{ collided: false } ### Given the rule and the list of collition products (with their positions) # find a moment of time when they emerged. # verifyField, verifyTime: knwon state of the field, for verification. ### findEmergeTime = (rule, products, minimalTime, verifyField, verifyTime) -> invRule = rule.reverse() #Time position of the latest fragment maxTime = Math.max (p.pos[2] for p in products)... if verifyTime? and maxTime < verifyTime throw new Error "Something is strange: maximal time of fragments smaller than verification time" #Prepare all fragments, at time maxTime patterns = for product in products #console.log "#### Product: #{JSON.stringify product}" #first, calculate first space-time point before the maxTime initialPos = firstPositionBefore product.pos, product.delta, maxTime #Put the pattern at this point pattern = Cells.transform product.pattern, product.transform, false patternAt rule, pattern, initialPos, maxTime if verifyTime? allPatterns = [].concat(patterns...) patternEvolution invRule, allPatterns, 1-maxTime, (p, t)-> if t is (1 - verifyTime) #console.log "#### verifying. At time #{1-t} " #console.log "#### Expected: #{normalizedRle verifyField}" #console.log "#### Got : #{normalizedRle p}" Cells.sortXY p Cells.sortXY verifyField if not Cells.areEqual verifyField, p throw new Error "Verification failed: reconstructed backward collision did not match expected" return false else return true #console.log "#### Generated #{patterns.length} patterns at time #{maxTime}:" #console.log "#### #{normalizedRle [].concat(patterns...)}" #Now simulate it inverse in time invCollision = simulateUntilCollision invRule, patterns, -maxTime+1, -minimalTime if not invCollision.collided throw new Error "Something is wrong: patterns did not collided in inverse time" return 1-invCollision.time #simulate patern until it decomposes into several simple patterns # Return list of collision products finishCollision = (rule, library, field, time) -> #console.log "#### Collision RLE: #{normalizedRle field}" growthLimit = field.length*3 + 8 #when to try to separate pattern while true field = evaluateCellList rule, field, mod2(time) time += 1 [x0, y0, x1,y1] = Cells.bounds field size = Math.max (x1-x0), (y1-y0) #console.log "#### T:#{time}, s:#{size}, R:#{normalizedRle field}" if size > growthLimit #console.log "#### At time #{time}, pattern grew to #{size}: #{normalizedRle field}" verifyTime = time verifyField = field break #now try to split result into several patterns parts = separatePatternParts field #console.log "#### Detected #{parts.length} parts" if parts.length is 1 #TODO: increase growth limit? #console.log "#### only one part, try more time" return finishCollision rule, library, field, time results = [] for part, i in parts #now analyze this part res = analyzeFragment rule, library, part, time for r in res results.push r return{ products: results verifyTime: verifyTime verifyField: field } analyzeFragment = (rule, library, pattern, time, options={})-> analysys = determinePeriod rule, pattern, time, options if analysys.cycle #console.log "#### Pattern analysys: #{JSON.stringify analysys}" res = library.classifyPattern pattern, time, analysys.delta... [res] else console.log "#### Pattern not decomposed completely: #{normalizedRle pattern} #{time}" finishCollision(rule, library, pattern, time).products #detect periodicity in pattern # Returns : # cycle::bool - is cycle found # error::str - if not cycle, says error details. Otherwise - udefined. # delta::[dx, dy, dt] - velocity and period, if cycle is found. determinePeriod = (rule, pattern, time, options={})-> pattern = Cells.copy pattern Cells.sortXY pattern max_iters = options.max_iters ? 2048 max_population = options.max_population ? 1024 max_size = options.max_size ? 1024 #wait for the cycle result = {cycle: false} patternEvolution rule, pattern, time, (curPattern, t) -> dt = t-time if dt is 0 then return true Cells.sortXY curPattern eq = Cells.shiftEqual pattern, curPattern, mod2 dt if eq result.cycle = true eq.push dt result.delta = eq return false if curPattern.length > max_population result.error = "pattern grew too big" return false bounds = Cells.bounds curPattern if Math.max( bounds[2]-bounds[0], bounds[3]-bounds[1]) > max_size result.error = "pattern dimensions grew too big" return false return true #continue evaluation return result snap_below = (x,generation) -> x - mod2(x + generation) #move pattern to 0, offsetToOrigin = (pattern, generation) -> [x0,y0] = Cells.topLeft pattern x0 = snap_below x0, generation y0 = snap_below y0, generation Cells.offset pattern, -x0, -y0 return [x0, y0] #Continuousely evaluate the pattern # Only returns pattern in ruleset phase 0. patternEvolution = (rule, pattern, time, callback)-> #pattern = Cells.copy pattern stable_rules = [rule] vacuum_period = stable_rules.length #ruleset size curPattern = pattern while true phase = mod2 time sub_rule_idx = mod time, vacuum_period if sub_rule_idx is 0 break unless callback curPattern, time curPattern = evaluateCellList stable_rules[sub_rule_idx], curPattern, phase time += 1 return class Library constructor: (@rule) -> @rle2pattern = {} #Assumes that pattern is in its canonical form addPattern: (pattern, data) -> rle = Cells.to_rle pattern if @rle2pattern.hasOwnProperty rle throw new Error "Pattern already present: #{rle}" @rle2pattern[rle] = data addRle: (rle, data) -> pattern = Cells.from_rle rle analysys = determinePeriod @rule, pattern, 0 if not analysys.cycle then throw new Error "Pattern #{rle} is not periodic!" #console.log "#### add anal: #{JSON.stringify analysys}" [dx,dy,p]=delta=analysys.delta unless (dx>0 and dy>=0) or (dx is 0 and dy is 0) throw new Error "Pattern #{rle} moves in wrong direction: #{dx},#{dy}" @addPattern pattern, data ? {delta: delta} classifyPattern: (pattern, time, dx, dy, period) -> #determine canonical ofrm ofthe pattern, present in the library; # return its offset #first: rotate the pattern caninically, if it is moving if dx isnt 0 or dy isnt 0 [dx1, dy1, tfm] = Cells._find_normalizing_rotation dx, dy pattern1 = Cells.transform pattern, tfm, false #no need to normalize result = @_classifyNormalizedPattern pattern1, time, dx1, dy1, period result.transform = inverseTfm tfm else #it is not a spaceship - no way to find a normal rotation. Check all 4 rotations. for tfm in Cells._rotations pattern1 = Cells.transform pattern, tfm, false result = @_classifyNormalizedPattern pattern1, time, 0, 0, period result.transform = inverseTfm tfm if result.found break #reverse-transform position [x,y,t] = result.pos #console.log "#### Original pos: #{JSON.stringify result.pos}" [x,y] = Cells.transformVector [x,y], result.transform #no normalize! #console.log "#### after inverse rotate: #{JSON.stringify [x,y,t]}" result.pos = [x,y,t] result.delta = [dx,dy,period] return result _classifyNormalizedPattern: (pattern, time, dx, dy, period) -> #console.log "#### Classifying: #{JSON.stringify pattern} at #{time}" result = {found:false} self = this patternEvolution @rule, pattern, time, (p, t)-> p = Cells.copy p [dx, dy] = offsetToOrigin p, t Cells.sortXY p rle = Cells.to_rle p #console.log "#### T:#{t}, rle:#{rle}" if rle of self.rle2pattern #console.log "#### found! #{rle}" result.pos = [dx, dy, t] result.rle = rle result.pattern = p result.found=true result.info = self.rle2pattern[rle] return false return (t-time) < period if not result.found p = Cells.copy pattern [dx, dy] = offsetToOrigin p, time Cells.sortXY p result.pos = [dx, dy, time] result.rle = Cells.to_rle p result.pattern = p result.found = false result.transform = [1,0,0,1] return result #load library from the simple JSON file. # Library format is simplified: "rle": data, where data is arbitrary object load: (file) -> fs = require "fs" libData = JSON.parse fs.readFileSync file, "utf8" #re-parse library data to ensure its correctness n = 0 for rle, data of libData @addPattern Cells.from_rle(rle), data n += 1 console.log "#### Loaded #{n} patterns from library #{file}" return # geometrically separate pattern into several disconnected parts # returns: list of sub-patterns separatePatternParts = (pattern, range=4) -> mpattern = {} #set of visited coordinates key = (x,y) -> ""+x+"#"+y has_cell = (x,y) -> mpattern.hasOwnProperty key x, y erase = (x,y) -> delete mpattern[ key x, y ] #convert pattern to map-based repersentation for xy in pattern mpattern[key xy...] = xy cells = [] #return true, if max size reached. do_pick_at = (x,y)-> erase x, y cells.push [x,y] for dy in [-range..range] by 1 y1 = y+dy for dx in [-range..range] by 1 continue if dy is 0 and dx is 0 x1 = x+dx if has_cell x1, y1 do_pick_at x1, y1 return parts = [] while true hadPattern = false for _k, xy of mpattern hadPattern = true #found at least one non-picked cell do_pick_at xy ... break if hadPattern parts.push cells cells = [] else break return parts #in margolus neighborhood, not all offsets produce the same pattern isValidOffset = ([dx, dy, dt]) -> ((dx+dt)%2 is 0) and ((dy+dt)%2 is 0) ############################ #Mostly for debug: display cllision indormation showCollision = (collision)-> console.log "##########################################################" for key, value of collision switch key when "collision" null when "products" for p, i in value console.log "#### -> #{i+1}: #{JSON.stringify p}" when "patterns" [p1,p2] = collision.patterns console.log "#### patterns: #{Cells.to_rle p1}, #{Cells.to_rle p2}" else console.log "#### #{key}: #{JSON.stringify value}" #### colliding with offset [0,0,0] #### CP: {"dist":0,"npos0":[0,0,0],"npos1":[0,0,0],"tcoll":0} #### AP: {"approach":true,"npos0":[-30,0,-180],"npos1":[0,0,-180],"tapp":-180} #### Collision RLE: $1379bo22$2o2$2o ### Calculate the space of all principially different relative positions of 2 patterns # Returns: # elementaryCell: list of 3-vectors of relative positions # freeIndex: index of the coordinate, that changes freely. 0 or 1 for valid patterns ### determinePatternRelativePositionsSpace = (v1, v2) -> [freeIndex, freeOrt] = opposingOrt v1, v2 #console.log "Free offset direction: #{freeOrt}, free index is #{freeIndex}" pv1 = removeComponent v1, freeIndex pv2 = removeComponent v2, freeIndex #console.log "Projected to null-space of free ort:" #console.log " PV1=#{pv1}, PV2=#{pv2}" #s = area2d pv1, pv2 #console.log "Area of non-free section: #{s}" ecell = (restoreComponent(v,freeIndex) for v in elementaryCell2d(pv1, pv2)) if ecell.length isnt Math.abs area2d pv1, pv2 throw new Error "elementary cell size is wrong" return{ elementaryCell: ecell freeIndex: freeIndex } ### Call the callback for all collisions between these 2 patterns ### allCollisions = (rule, library, pattern1, pattern2, onCollision) -> v2 = (determinePeriod rule, pattern2, 0).delta v1 = (determinePeriod rule, pattern1, 0).delta console.log "Two velocities: #{v1}, #{v2}" {elementaryCell, freeIndex} = determinePatternRelativePositionsSpace v1, v2 #now we are ready to perform collisions # free index changes unboundedly, other variables change inside the elementary cell minimalTouchDistance = (pattern1.length + pattern2.length + 1)*3 #console.log "#### Minimal touch distance is #{minimalTouchDistance}" for offset in elementaryCell #dPos, v0, v1, dMax, index offsetRange = freeIndexRange offset, v1, v2, minimalTouchDistance, freeIndex #console.log "#### FOr offset #{JSON.stringify offset}, index range is #{JSON.stringify offsetRange}" for xFree in [offsetRange[0] .. offsetRange[1]] by 1 offset = offset[..] offset[freeIndex] = xFree if isValidOffset offset collision = doCollision rule, library, pattern1, v1, pattern2, v2, offset, minimalTouchDistance*2, minimalTouchDistance if collision.collision onCollision collision return runCollider = -> #single rotate - for test rule = from_list_elem [0,2,8,3,1,5,6,7,4,9,10,11,12,13,14,15] library = new Library rule library.load "./singlerot-simple.lib.json" #2-block pattern2 = Cells.from_rle "$2o2$2o" pattern1 = Cells.from_rle "o" allCollisions rule, library, pattern1, pattern2, (collision) -> showCollision collision makeCollisionCatalog = (rule, library, pattern1, pattern2) -> catalog = [] allCollisions rule, library, pattern1, pattern2, (collision) -> #showCollision collision catalog.push collision return catalog # Main fgunctons, that reads command line parameters and generates collision catalog mainCatalog = -> stdio = require "stdio" opts = stdio.getopt { output: key: 'o' args: 1 description: "Output file. Default is collisions-[p1]-[p2]-rule.json" rule: key:'r' args: 1 description: "Rule (16 integers). Default is SingleRotation" libs: key:"L" args: 1 description: "List of libraries to load. Use : to separate files" }, "pattern1 pattern2" ################# Parsing options ####################### unless opts.args? and opts.args.length in [2..2] process.stderr.write "Not enough arguments\n" process.exit 1 [rle1, rle2] = opts.args pattern1 = Cells.from_rle rle1 pattern2 = Cells.from_rle rle2 console.log "#### RLEs: #{rle1}, #{rle2}" console.log "Colliding 2 patterns:" console.log pattern2string pattern1 console.log "--------" console.log pattern2string pattern2 rule = if opts.rule? parseElementary opts.rule else from_list_elem [0,2,8,3,1,5,6,7,4,9,10,11,12,13,14,15] unless rule.is_vacuum_stable() throw new Error "Rule is not vacuum-stable. Not supported currently." unless rule.is_invertible() throw new Error "Rule is not invertible. Not supported currently." outputFile = if opts.output? opts.output else "collisions-#{normalizedRle pattern1}-#{normalizedRle pattern2}-#{rule.stringify()}.json" libFiles = if opts.libs? opts.libs.split ":" else [] ############### Running the collisions ################### library = new Library rule for libFile in libFiles library.load libFile czs = makeCollisionCatalog rule, library, pattern1, pattern2 console.log "Found #{czs.length} collisions, stored in #{outputFile}" fs = require "fs" czsData = rule: rule.to_list() patterns: [pattern1, pattern2] collisions: czs fs.writeFileSync outputFile, JSON.stringify(czsData), {encoding:"utf8"} pattern2string = (pattern, signs = ['.', '#']) -> [x0, y0, x1, y1] = Cells.bounds pattern x0 -= mod2 x0 y0 -= mod2 y0 x1 += 1 y1 += 1 x1 += mod2 x1 y1 += mod2 y1 w = x1 - x0 h = y1 - y0 fld = ((signs[0] for i in [0...w]) for j in [0...h]) for [x,y] in pattern fld[y-y0][x-x0] = signs[1] return (row.join("") for row in fld).join("\n") #runCollider() mainCatalog()
48061
#!/usr/bin/env coffee "use strict" # Particle collider. # Make collision table fs = require "fs" {Cells, inverseTfm, evaluateCellList, getDualTransform, splitPattern} = require "../scripts-src/cells" {from_list_elem, parseElementary} = require "../scripts-src/rules" stdio = require "stdio" {mod,mod2} = require "../scripts-src/math_util" #GIven 2 3-vectors, return 3-ort, that forms full basis with both vectors opposingOrt = (v1, v2) -> for i in [0..2] ort = [0,0,0] ort[i] = 1 if isCompleteBasis v1, v2, ort return [i, ort] throw new Error "Two vectors are collinear" #Scalar product of 2 vectors dot = (a,b) -> s = 0 for ai, i in a s += ai*b[i] return s #project 3-vector vec to the null-space of ort #projectToNullSpace = (ort, vec) -> # if dot(ort,ort) isnt 1 # throw new Error "Not an ort!" # p = dot ort, vec # # return (vec[i] - ort[i]*p for i in [0...3] ) #Remove component from a vector removeComponent =( vec, index) -> result = [] for xi, i in vec if i isnt index result.push xi return result restoreComponent = (vec, index) -> #insert 0 into index i v = vec[..] v.splice index, 0, 0 return v isCompleteBasis = (v1, v2, v3) -> #determinant of a matrix of 3 vectors. copipe from maxima det = v1[0]*(v2[1]*v3[2]-v3[1]*v2[2])-v1[1]*(v2[0]*v3[2]-v3[0]*v2[2])+(v2[0]*v3[1]-v3[0]*v2[1])*v1[2] return det isnt 0 #Area of a tetragon, built on 2 vectors. May be negative. area2d = ([x1,y1],[x2,y2]) -> x1*y2 - x2*y1 vecSum = (v1, v2) -> (v1i+v2[i] for v1i, i in v1) vecDiff = (v1, v2) -> (v1i-v2[i] for v1i, i in v1) vecScale = (v1, k) -> (v1i*k for v1i in v1) #Returns list of coordinates of points in elementary cell # both vectors must be 2d, nonzero, non-collinear elementaryCell2d = (v1, v2) -> #vertices [x1,y1] = v1 [x2,y2] = v2 if area2d(v1,v2) is 0 throw new Error "vectors are collinear!" #orient vectors if x1 < 0 x1 = -x1 y1 = -y1 if x2 < 0 x2 = -x2 y2 = -y2 # x intervals: # 0, min(x1,x2), max(x1,x2), x1+x2 xs = [0, x1, x2, x1+x2] xmin = Math.min xs ... xmax = Math.max xs ... ys = [0, y1, y2, y1+y2] ymin = Math.min ys ... ymax = Math.max ys ... d = x2*y1-x1*y2 #determinant of the equation s = if d < 0 then -1 else 1 points = [] for x in [xmin .. xmax] by 1 for y in [ymin .. ymax] by 1 #check that the point belongs to the rhombus #[t1 = (x2*y-x*y2)/d, # t2 = -(x1*y-x*y1)/d] #condition is: t1,2 in [0, 1) if ( 0 <= (x2*y-x*y2)*s < d*s ) and ( 0 <= -(x1*y-x*y1)*s < d*s ) points.push [x,y] return points #Calculate parameters of the collision: # collision time, nearest node points, collision distance. # pos : position [x, y, t] # delta : velocity and period [dx, dy, dt] collisionParameters = (pos0, delta0, pos1, delta1) -> #pos and delta are 3-vectors: (x,y,t) # #deltax : dx+a*vx0-b*vx1; #deltay : dy+a*vy0-b*vy1; #deltat : dt+a*p0-b*p1; # Dropbox.Math.spaceship-collision [dx, dy, dt] = vecDiff pos0, pos1 [vx0, vy0, p0] = delta0 [vx1, vy1, p1] = delta1 # D = p0**2*vy1**2-2*p0*p1*vy0*vy1+p1**2*vy0**2 + p0**2*vx1**2-2*p0*p1*vx0*vx1+p1**2*vx0**2 D = (p0*vy1 - p1*vy0)**2 + (p0*vx1-p1*vx0)**2 a = -(dt*p0*vy1**2+(-dt*p1*vy0-dy*p0*p1)*vy1+dy*p1**2*vy0+dt*p0*vx1**2+(-dt*p1*vx0-dx*p0*p1)*vx1+dx*p1**2*vx0) / D b = -((dt*p0*vy0-dy*p0**2)*vy1-dt*p1*vy0**2+dy*p0*p1*vy0+(dt*p0*vx0-dx*p0**2)*vx1-dt*p1*vx0**2+dx*p0*p1*vx0) / D dist = Math.abs(dt*vx0*vy1-dx*p0*vy1-dt*vx1*vy0+dx*p1*vy0+dy*p0*vx1-dy*p1*vx0)/Math.sqrt(D) #nearest points with time before collision time ia = Math.floor(a)|0 ib = Math.floor(b)|0 npos0 = vecSum pos0, vecScale(delta0, ia) npos1 = vecSum pos1, vecScale(delta1, ib) tcoll = pos0[2] + delta0[2]*a tcoll1 = pos1[2] + delta1[2]*b #must be same as tcoll1 if Math.abs(tcoll-tcoll1) > 1e-6 then throw new Error "assert: tcoll" return { dist: dist #distance of the nearest approach npos0: npos0 npos1: npos1 #node point nearest to the collision (below) tcoll: tcoll #when nearest approach occurs } #In what rande DX can change, if minimal distanec between 2 patterns is less than dmax? # This fucntion gives the answer. # Calculation is in the maxima sheet: # solve( d2 = dd^2, dx ); dxRange = (dPos, v0, v1, dMax) -> #dPos, v0, v1 :: vector3 #dMax :: integer [_, dy, dt] = dPos #dx is ignored, because we will find its diapason [vx0, vy0, p0] = v0 [vx1, vy1, p1] = v1 #Solution from Maxima: # dx=-(dd*sqrt(p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2+p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2)-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0)/(p0*vy1-p1*vy0) # q = p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2+p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2 # # dx=(+-dd*sqrt(q)-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0)/(p1*vy0 - p0*vy1) num = p1*vy0 - p0*vy1 if num is 0 #throw new Error "Patterns are parallel and neveer touch" return [0, -1] dc = (-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0) / num #q = p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2 + p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2 q = (p0*vy1-p1*vy0)**2 + (p0*vx1-p1*vx0)**2 #after small simplification delta = Math.abs(Math.sqrt(q) * (dMax / num)) #return upper and lower limits, rounded to integers return [Math.floor(dc - delta)|0, Math.ceil(dc + delta)|0] #Same as dxRange, but for dy. Reuses dxRange dyRange = (dPos, v0, v1, dMax) -> swapxy = ([x,y,t]) -> [y,x,t] dxRange swapxy(dPos), swapxy(v0), swapxy(v1), dMax #Chooses one of dxRange, dyRange. freeIndexRange = (dPos, v0, v1, dMax, index) -> if index not in [0..1] then throw new Error "Unsupported index #{index}" [dxRange, dyRange][index](dPos, v0, v1, dMax) #Calculate time, when 2 spaceship approach to the specified distance. approachParameters = (pos0, delta0, pos1, delta1, approachDistance) -> [dx, dy, dt] = vecDiff pos0, pos1 [vx0, vy0, p0] = delta0 [vx1, vy1, p1] = delta1 #solve( [deltax^2 + deltay^2 = dd^2, deltat=0], [a,b] ); dd = approachDistance D = (p0**2*vy1**2-2*p0*p1*vy0*vy1+p1**2*vy0**2+p0**2*vx1**2-2*p0*p1*vx0*vx1+p1**2*vx0**2) #thanks maxima. The formula is not well optimized, but I don't care. Q2 = (-dt**2*vx0**2+2*dt*dx*p0*vx0+(dd**2-dx**2)*p0**2)*vy1**2+(((2*dt**2*vx0-2*dt*dx*p0)*vx1-2*dt*dx*p1*vx0+(2*dx**2-2*dd**2)*p0*p1)*vy0+(2*dx*dy*p0**2-2*dt*dy*p0*vx0)*vx1+2*dt*dy*p1*vx0**2-2*dx*dy*p0*p1*vx0)*vy1+(-dt**2*vx1**2+2*dt*dx*p1*vx1+(dd**2-dx**2)*p1**2)*vy0**2+(2*dt*dy*p0*vx1**2+(-2*dt*dy*p1*vx0-2*dx*dy*p0*p1)*vx1+2*dx*dy*p1**2*vx0)*vy0+(dd**2-dy**2)*p0**2*vx1**2+(2*dy**2-2*dd**2)*p0*p1*vx0*vx1+(dd**2-dy**2)*p1**2*vx0**2 if Q2 < 0 #Approach not possible, spaceships are not coming close enough return {approach: false} Q = Math.sqrt(Q2) a = -(p1*Q+dt*p0*vy1**2+(-dt*p1*vy0-dy*p0*p1)*vy1+dy*p1**2*vy0+dt*p0*vx1**2+(-dt*p1*vx0-dx*p0*p1)*vx1+dx*p1**2*vx0) / D b = -(p0*Q+(dt*p0*vy0-dy*p0**2)*vy1-dt*p1*vy0**2+dy*p0*p1*vy0+(dt*p0*vx0-dx*p0**2)*vx1-dt*p1*vx0**2+dx*p0*p1*vx0) / D tapp = pos0[2]+p0*a tapp1 = pos1[2]+p1*b if Math.abs(tapp1-tapp) >1e-6 then throw new Error "Assertion failed" ia = Math.floor(a)|0 ib = Math.floor(b)|0 npos0 = vecSum pos0, vecScale(delta0, ia) npos1 = vecSum pos1, vecScale(delta1, ib) return { approach: true npos0 : npos0 #nearest positions before approach npos1 : npos1 tapp : tapp } #Give n position: [x,y,t] and delta: [dx,dy,dt], # Return position with biggest time <= t (inclusive). firstPositionBefore = (pos, delta, time) -> # find integer i: # t + i*dt < time # # i*dt < time - t # i < (time-t)/dt i0 = (time - pos[2]) / delta[2] #not integer. #now find the nearest integer below i = (Math.floor i0) |0 #and return the position vecSum pos, vecScale delta, i #Given spaceship trajectory, returns first it position before the given moment of time (inclusive) firstPositionAfter = (pos, delta, time) -> i0 = (time - pos[2]) / delta[2] #not integer. i = (Math.ceil i0) |0 vecSum pos, vecScale delta, i #Normalize pattern and returns its rle. normalizedRle = (fld) -> ff = Cells.copy fld Cells.normalize ff Cells.to_rle ff evalToTime = (rule, fld, t0, tend) -> if t > tend then throw new Error "assert: bad time" for t in [t0 ... tend] by 1 fld = evaluateCellList rule, fld, mod2(t) return fld #put the pattern to the specified time and position, and return its state at time t patternAt = (rule, pattern, posAndTime, t) -> pattern = Cells.copy pattern [x0,y0,t0] = posAndTime Cells.offset pattern, x0, y0 evalToTime rule, pattern, t0, t # Collide 2 patterns: p1 and p2, # p1 at [0,0,0] and p2 at `offset`. # initialSeparation::int approximate initial distance to put patterns at. Should be large enought for patterns not to intersect # offset: [dx, dy, dt] - initial offset of the pattern p2 (p1 at 000) # collisionTreshold:: if patterns don't come closer than this distance, don't consider them colliding. # waitForCollision::int How many generations to wait after the approximate nearest approach, until the interaction would start. # # Returned value: object # collision::bool true if collision # patterns :: [p1, p2] two patterns # offsets :: [vec1, vec2] first position of each pattern before collision time # timeStart::int first generation, where interaction has started # products::[ ProductDesc ] list of collision products (patterns with their positions and classification doCollision = (rule, library, p1, v1, p2, v2, offset, initialSeparation = 30, collisionTreshold=20)-> waitForCollision = v1[2] + v2[2] #sum of periods params = collisionParameters [0,0,0], v1, offset, v2 ap = approachParameters [0,0,0], v1, offset, v2, initialSeparation collision = {collision:false} if not ap.approach #console.log "#### No approach, nearest approach: #{params.dist}" return collision if params.dist > collisionTreshold #console.log "#### Too far, nearest approach #{params.dist} > #{collisionTreshold}" return collision #console.log "#### CP: #{JSON.stringify params}" #console.log "#### AP: #{JSON.stringify ap}" #Create the initial field. Put 2 patterns: p1 and p2 at initial time #nwo promote them to the same time, using list evaluation time = Math.max ap.npos0[2], ap.npos1[2] fld1 = patternAt rule, p1, ap.npos0, time fld2 = patternAt rule, p2, ap.npos1, time #OK, collision prepared. Now simulate both spaceships separately and # together, waiting while interaction occurs timeGiveUp = params.tcoll + waitForCollision #when to stop waiting for some interaction coll = simulateUntilCollision rule, [fld1, fld2], time, timeGiveUp fld1 = fld2 = null #They are not needed anymore if not coll.collided #console.log "#### No interaction detected until T=#{timeGiveUp}. Give up." return collision #console.log "#### colliding:" #console.log "#### 1) #{normalizedRle p1} at [0, 0, 0]" #console.log "#### 2) #{normalizedRle p2} at #{JSON.stringify offset}" #console.log "#### collision at T=#{coll.time} (give up at #{timeGiveUp})" collision.timeStart = coll.time collision.patterns = [p1, p2] collision.offsets = [ firstPositionBefore([0,0,0], v1, coll.time-1), firstPositionBefore(offset, v2, coll.time-1), ] collision.collision = true {products, verifyTime, verifyField} = finishCollision rule, library, coll.field, coll.time collision.products = products #findEmergeTime = (rule, products, minimalTime) -> collision.timeEnd = findEmergeTime rule, collision.products, collision.timeStart, verifyField, verifyTime #Update positions of products for product in collision.products product.pos = firstPositionAfter product.pos, product.delta, collision.timeEnd+1 #normalize relative to the first spaceship translateCollision collision, vecScale(collision.offsets[0], -1) #Offser collision information record by the given amount, in time and space translateCollision = (collision, dpos) -> [dx, dy, dt] = dpos for o, i in collision.offsets collision.offsets[i] = vecSum o, dpos collision.timeStart += dt collision.timeEnd += dt for product in collision.products product.pos = vecSum product.pos, dpos return collision #Simulate several patterns until they collide. # Return first oment of time, when patterns started interacting. simulateUntilCollision = (rule, patterns, time, timeGiveUp) -> if patterns.length < 2 then return {collided: false} # 1 pattern can't collide. fld = [].concat patterns ... #concatenate all patterns while time < timeGiveUp phase = mod2 time #evaluate each pattern separately #console.log "### patterns: #{JSON.stringify patterns}" patterns = (evaluateCellList(rule, p, phase) for p in patterns) #console.log "### after eval: #{JSON.stringify patterns}" #And together fld = evaluateCellList rule, fld, phase time += 1 #check if they are different mergedPatterns = [].concat patterns... Cells.sortXY fld Cells.sortXY mergedPatterns if not Cells.areEqual fld, mergedPatterns #console.log "#### Collision detected! T=#{time}, #{normalizedRle fld}" return { collided: true time: time field: fld } return{ collided: false } ### Given the rule and the list of collition products (with their positions) # find a moment of time when they emerged. # verifyField, verifyTime: knwon state of the field, for verification. ### findEmergeTime = (rule, products, minimalTime, verifyField, verifyTime) -> invRule = rule.reverse() #Time position of the latest fragment maxTime = Math.max (p.pos[2] for p in products)... if verifyTime? and maxTime < verifyTime throw new Error "Something is strange: maximal time of fragments smaller than verification time" #Prepare all fragments, at time maxTime patterns = for product in products #console.log "#### Product: #{JSON.stringify product}" #first, calculate first space-time point before the maxTime initialPos = firstPositionBefore product.pos, product.delta, maxTime #Put the pattern at this point pattern = Cells.transform product.pattern, product.transform, false patternAt rule, pattern, initialPos, maxTime if verifyTime? allPatterns = [].concat(patterns...) patternEvolution invRule, allPatterns, 1-maxTime, (p, t)-> if t is (1 - verifyTime) #console.log "#### verifying. At time #{1-t} " #console.log "#### Expected: #{normalizedRle verifyField}" #console.log "#### Got : #{normalizedRle p}" Cells.sortXY p Cells.sortXY verifyField if not Cells.areEqual verifyField, p throw new Error "Verification failed: reconstructed backward collision did not match expected" return false else return true #console.log "#### Generated #{patterns.length} patterns at time #{maxTime}:" #console.log "#### #{normalizedRle [].concat(patterns...)}" #Now simulate it inverse in time invCollision = simulateUntilCollision invRule, patterns, -maxTime+1, -minimalTime if not invCollision.collided throw new Error "Something is wrong: patterns did not collided in inverse time" return 1-invCollision.time #simulate patern until it decomposes into several simple patterns # Return list of collision products finishCollision = (rule, library, field, time) -> #console.log "#### Collision RLE: #{normalizedRle field}" growthLimit = field.length*3 + 8 #when to try to separate pattern while true field = evaluateCellList rule, field, mod2(time) time += 1 [x0, y0, x1,y1] = Cells.bounds field size = Math.max (x1-x0), (y1-y0) #console.log "#### T:#{time}, s:#{size}, R:#{normalizedRle field}" if size > growthLimit #console.log "#### At time #{time}, pattern grew to #{size}: #{normalizedRle field}" verifyTime = time verifyField = field break #now try to split result into several patterns parts = separatePatternParts field #console.log "#### Detected #{parts.length} parts" if parts.length is 1 #TODO: increase growth limit? #console.log "#### only one part, try more time" return finishCollision rule, library, field, time results = [] for part, i in parts #now analyze this part res = analyzeFragment rule, library, part, time for r in res results.push r return{ products: results verifyTime: verifyTime verifyField: field } analyzeFragment = (rule, library, pattern, time, options={})-> analysys = determinePeriod rule, pattern, time, options if analysys.cycle #console.log "#### Pattern analysys: #{JSON.stringify analysys}" res = library.classifyPattern pattern, time, analysys.delta... [res] else console.log "#### Pattern not decomposed completely: #{normalizedRle pattern} #{time}" finishCollision(rule, library, pattern, time).products #detect periodicity in pattern # Returns : # cycle::bool - is cycle found # error::str - if not cycle, says error details. Otherwise - udefined. # delta::[dx, dy, dt] - velocity and period, if cycle is found. determinePeriod = (rule, pattern, time, options={})-> pattern = Cells.copy pattern Cells.sortXY pattern max_iters = options.max_iters ? 2048 max_population = options.max_population ? 1024 max_size = options.max_size ? 1024 #wait for the cycle result = {cycle: false} patternEvolution rule, pattern, time, (curPattern, t) -> dt = t-time if dt is 0 then return true Cells.sortXY curPattern eq = Cells.shiftEqual pattern, curPattern, mod2 dt if eq result.cycle = true eq.push dt result.delta = eq return false if curPattern.length > max_population result.error = "pattern grew too big" return false bounds = Cells.bounds curPattern if Math.max( bounds[2]-bounds[0], bounds[3]-bounds[1]) > max_size result.error = "pattern dimensions grew too big" return false return true #continue evaluation return result snap_below = (x,generation) -> x - mod2(x + generation) #move pattern to 0, offsetToOrigin = (pattern, generation) -> [x0,y0] = Cells.topLeft pattern x0 = snap_below x0, generation y0 = snap_below y0, generation Cells.offset pattern, -x0, -y0 return [x0, y0] #Continuousely evaluate the pattern # Only returns pattern in ruleset phase 0. patternEvolution = (rule, pattern, time, callback)-> #pattern = Cells.copy pattern stable_rules = [rule] vacuum_period = stable_rules.length #ruleset size curPattern = pattern while true phase = mod2 time sub_rule_idx = mod time, vacuum_period if sub_rule_idx is 0 break unless callback curPattern, time curPattern = evaluateCellList stable_rules[sub_rule_idx], curPattern, phase time += 1 return class Library constructor: (@rule) -> @rle2pattern = {} #Assumes that pattern is in its canonical form addPattern: (pattern, data) -> rle = Cells.to_rle pattern if @rle2pattern.hasOwnProperty rle throw new Error "Pattern already present: #{rle}" @rle2pattern[rle] = data addRle: (rle, data) -> pattern = Cells.from_rle rle analysys = determinePeriod @rule, pattern, 0 if not analysys.cycle then throw new Error "Pattern #{rle} is not periodic!" #console.log "#### add anal: #{JSON.stringify analysys}" [dx,dy,p]=delta=analysys.delta unless (dx>0 and dy>=0) or (dx is 0 and dy is 0) throw new Error "Pattern #{rle} moves in wrong direction: #{dx},#{dy}" @addPattern pattern, data ? {delta: delta} classifyPattern: (pattern, time, dx, dy, period) -> #determine canonical ofrm ofthe pattern, present in the library; # return its offset #first: rotate the pattern caninically, if it is moving if dx isnt 0 or dy isnt 0 [dx1, dy1, tfm] = Cells._find_normalizing_rotation dx, dy pattern1 = Cells.transform pattern, tfm, false #no need to normalize result = @_classifyNormalizedPattern pattern1, time, dx1, dy1, period result.transform = inverseTfm tfm else #it is not a spaceship - no way to find a normal rotation. Check all 4 rotations. for tfm in Cells._rotations pattern1 = Cells.transform pattern, tfm, false result = @_classifyNormalizedPattern pattern1, time, 0, 0, period result.transform = inverseTfm tfm if result.found break #reverse-transform position [x,y,t] = result.pos #console.log "#### Original pos: #{JSON.stringify result.pos}" [x,y] = Cells.transformVector [x,y], result.transform #no normalize! #console.log "#### after inverse rotate: #{JSON.stringify [x,y,t]}" result.pos = [x,y,t] result.delta = [dx,dy,period] return result _classifyNormalizedPattern: (pattern, time, dx, dy, period) -> #console.log "#### Classifying: #{JSON.stringify pattern} at #{time}" result = {found:false} self = this patternEvolution @rule, pattern, time, (p, t)-> p = Cells.copy p [dx, dy] = offsetToOrigin p, t Cells.sortXY p rle = Cells.to_rle p #console.log "#### T:#{t}, rle:#{rle}" if rle of self.rle2pattern #console.log "#### found! #{rle}" result.pos = [dx, dy, t] result.rle = rle result.pattern = p result.found=true result.info = self.rle2pattern[rle] return false return (t-time) < period if not result.found p = Cells.copy pattern [dx, dy] = offsetToOrigin p, time Cells.sortXY p result.pos = [dx, dy, time] result.rle = Cells.to_rle p result.pattern = p result.found = false result.transform = [1,0,0,1] return result #load library from the simple JSON file. # Library format is simplified: "rle": data, where data is arbitrary object load: (file) -> fs = require "fs" libData = JSON.parse fs.readFileSync file, "utf8" #re-parse library data to ensure its correctness n = 0 for rle, data of libData @addPattern Cells.from_rle(rle), data n += 1 console.log "#### Loaded #{n} patterns from library #{file}" return # geometrically separate pattern into several disconnected parts # returns: list of sub-patterns separatePatternParts = (pattern, range=4) -> mpattern = {} #set of visited coordinates key = (x,y) -> <KEY> has_cell = (x,y) -> mpattern.hasOwnProperty key x, y erase = (x,y) -> delete mpattern[ key x, y ] #convert pattern to map-based repersentation for xy in pattern mpattern[key xy...] = xy cells = [] #return true, if max size reached. do_pick_at = (x,y)-> erase x, y cells.push [x,y] for dy in [-range..range] by 1 y1 = y+dy for dx in [-range..range] by 1 continue if dy is 0 and dx is 0 x1 = x+dx if has_cell x1, y1 do_pick_at x1, y1 return parts = [] while true hadPattern = false for _k, xy of mpattern hadPattern = true #found at least one non-picked cell do_pick_at xy ... break if hadPattern parts.push cells cells = [] else break return parts #in margolus neighborhood, not all offsets produce the same pattern isValidOffset = ([dx, dy, dt]) -> ((dx+dt)%2 is 0) and ((dy+dt)%2 is 0) ############################ #Mostly for debug: display cllision indormation showCollision = (collision)-> console.log "##########################################################" for key, value of collision switch key when "collision" null when "products" for p, i in value console.log "#### -> #{i+1}: #{JSON.stringify p}" when "patterns" [p1,p2] = collision.patterns console.log "#### patterns: #{Cells.to_rle p1}, #{Cells.to_rle p2}" else console.log "#### #{key}: #{JSON.stringify value}" #### colliding with offset [0,0,0] #### CP: {"dist":0,"npos0":[0,0,0],"npos1":[0,0,0],"tcoll":0} #### AP: {"approach":true,"npos0":[-30,0,-180],"npos1":[0,0,-180],"tapp":-180} #### Collision RLE: $1379bo22$2o2$2o ### Calculate the space of all principially different relative positions of 2 patterns # Returns: # elementaryCell: list of 3-vectors of relative positions # freeIndex: index of the coordinate, that changes freely. 0 or 1 for valid patterns ### determinePatternRelativePositionsSpace = (v1, v2) -> [freeIndex, freeOrt] = opposingOrt v1, v2 #console.log "Free offset direction: #{freeOrt}, free index is #{freeIndex}" pv1 = removeComponent v1, freeIndex pv2 = removeComponent v2, freeIndex #console.log "Projected to null-space of free ort:" #console.log " PV1=#{pv1}, PV2=#{pv2}" #s = area2d pv1, pv2 #console.log "Area of non-free section: #{s}" ecell = (restoreComponent(v,freeIndex) for v in elementaryCell2d(pv1, pv2)) if ecell.length isnt Math.abs area2d pv1, pv2 throw new Error "elementary cell size is wrong" return{ elementaryCell: ecell freeIndex: freeIndex } ### Call the callback for all collisions between these 2 patterns ### allCollisions = (rule, library, pattern1, pattern2, onCollision) -> v2 = (determinePeriod rule, pattern2, 0).delta v1 = (determinePeriod rule, pattern1, 0).delta console.log "Two velocities: #{v1}, #{v2}" {elementaryCell, freeIndex} = determinePatternRelativePositionsSpace v1, v2 #now we are ready to perform collisions # free index changes unboundedly, other variables change inside the elementary cell minimalTouchDistance = (pattern1.length + pattern2.length + 1)*3 #console.log "#### Minimal touch distance is #{minimalTouchDistance}" for offset in elementaryCell #dPos, v0, v1, dMax, index offsetRange = freeIndexRange offset, v1, v2, minimalTouchDistance, freeIndex #console.log "#### FOr offset #{JSON.stringify offset}, index range is #{JSON.stringify offsetRange}" for xFree in [offsetRange[0] .. offsetRange[1]] by 1 offset = offset[..] offset[freeIndex] = xFree if isValidOffset offset collision = doCollision rule, library, pattern1, v1, pattern2, v2, offset, minimalTouchDistance*2, minimalTouchDistance if collision.collision onCollision collision return runCollider = -> #single rotate - for test rule = from_list_elem [0,2,8,3,1,5,6,7,4,9,10,11,12,13,14,15] library = new Library rule library.load "./singlerot-simple.lib.json" #2-block pattern2 = Cells.from_rle "$2o2$2o" pattern1 = Cells.from_rle "o" allCollisions rule, library, pattern1, pattern2, (collision) -> showCollision collision makeCollisionCatalog = (rule, library, pattern1, pattern2) -> catalog = [] allCollisions rule, library, pattern1, pattern2, (collision) -> #showCollision collision catalog.push collision return catalog # Main fgunctons, that reads command line parameters and generates collision catalog mainCatalog = -> stdio = require "stdio" opts = stdio.getopt { output: key: 'o' args: 1 description: "Output file. Default is collisions-[p1]-[p2]-rule.json" rule: key:'r' args: 1 description: "Rule (16 integers). Default is SingleRotation" libs: key:"L" args: 1 description: "List of libraries to load. Use : to separate files" }, "pattern1 pattern2" ################# Parsing options ####################### unless opts.args? and opts.args.length in [2..2] process.stderr.write "Not enough arguments\n" process.exit 1 [rle1, rle2] = opts.args pattern1 = Cells.from_rle rle1 pattern2 = Cells.from_rle rle2 console.log "#### RLEs: #{rle1}, #{rle2}" console.log "Colliding 2 patterns:" console.log pattern2string pattern1 console.log "--------" console.log pattern2string pattern2 rule = if opts.rule? parseElementary opts.rule else from_list_elem [0,2,8,3,1,5,6,7,4,9,10,11,12,13,14,15] unless rule.is_vacuum_stable() throw new Error "Rule is not vacuum-stable. Not supported currently." unless rule.is_invertible() throw new Error "Rule is not invertible. Not supported currently." outputFile = if opts.output? opts.output else "collisions-#{normalizedRle pattern1}-#{normalizedRle pattern2}-#{rule.stringify()}.json" libFiles = if opts.libs? opts.libs.split ":" else [] ############### Running the collisions ################### library = new Library rule for libFile in libFiles library.load libFile czs = makeCollisionCatalog rule, library, pattern1, pattern2 console.log "Found #{czs.length} collisions, stored in #{outputFile}" fs = require "fs" czsData = rule: rule.to_list() patterns: [pattern1, pattern2] collisions: czs fs.writeFileSync outputFile, JSON.stringify(czsData), {encoding:"utf8"} pattern2string = (pattern, signs = ['.', '#']) -> [x0, y0, x1, y1] = Cells.bounds pattern x0 -= mod2 x0 y0 -= mod2 y0 x1 += 1 y1 += 1 x1 += mod2 x1 y1 += mod2 y1 w = x1 - x0 h = y1 - y0 fld = ((signs[0] for i in [0...w]) for j in [0...h]) for [x,y] in pattern fld[y-y0][x-x0] = signs[1] return (row.join("") for row in fld).join("\n") #runCollider() mainCatalog()
true
#!/usr/bin/env coffee "use strict" # Particle collider. # Make collision table fs = require "fs" {Cells, inverseTfm, evaluateCellList, getDualTransform, splitPattern} = require "../scripts-src/cells" {from_list_elem, parseElementary} = require "../scripts-src/rules" stdio = require "stdio" {mod,mod2} = require "../scripts-src/math_util" #GIven 2 3-vectors, return 3-ort, that forms full basis with both vectors opposingOrt = (v1, v2) -> for i in [0..2] ort = [0,0,0] ort[i] = 1 if isCompleteBasis v1, v2, ort return [i, ort] throw new Error "Two vectors are collinear" #Scalar product of 2 vectors dot = (a,b) -> s = 0 for ai, i in a s += ai*b[i] return s #project 3-vector vec to the null-space of ort #projectToNullSpace = (ort, vec) -> # if dot(ort,ort) isnt 1 # throw new Error "Not an ort!" # p = dot ort, vec # # return (vec[i] - ort[i]*p for i in [0...3] ) #Remove component from a vector removeComponent =( vec, index) -> result = [] for xi, i in vec if i isnt index result.push xi return result restoreComponent = (vec, index) -> #insert 0 into index i v = vec[..] v.splice index, 0, 0 return v isCompleteBasis = (v1, v2, v3) -> #determinant of a matrix of 3 vectors. copipe from maxima det = v1[0]*(v2[1]*v3[2]-v3[1]*v2[2])-v1[1]*(v2[0]*v3[2]-v3[0]*v2[2])+(v2[0]*v3[1]-v3[0]*v2[1])*v1[2] return det isnt 0 #Area of a tetragon, built on 2 vectors. May be negative. area2d = ([x1,y1],[x2,y2]) -> x1*y2 - x2*y1 vecSum = (v1, v2) -> (v1i+v2[i] for v1i, i in v1) vecDiff = (v1, v2) -> (v1i-v2[i] for v1i, i in v1) vecScale = (v1, k) -> (v1i*k for v1i in v1) #Returns list of coordinates of points in elementary cell # both vectors must be 2d, nonzero, non-collinear elementaryCell2d = (v1, v2) -> #vertices [x1,y1] = v1 [x2,y2] = v2 if area2d(v1,v2) is 0 throw new Error "vectors are collinear!" #orient vectors if x1 < 0 x1 = -x1 y1 = -y1 if x2 < 0 x2 = -x2 y2 = -y2 # x intervals: # 0, min(x1,x2), max(x1,x2), x1+x2 xs = [0, x1, x2, x1+x2] xmin = Math.min xs ... xmax = Math.max xs ... ys = [0, y1, y2, y1+y2] ymin = Math.min ys ... ymax = Math.max ys ... d = x2*y1-x1*y2 #determinant of the equation s = if d < 0 then -1 else 1 points = [] for x in [xmin .. xmax] by 1 for y in [ymin .. ymax] by 1 #check that the point belongs to the rhombus #[t1 = (x2*y-x*y2)/d, # t2 = -(x1*y-x*y1)/d] #condition is: t1,2 in [0, 1) if ( 0 <= (x2*y-x*y2)*s < d*s ) and ( 0 <= -(x1*y-x*y1)*s < d*s ) points.push [x,y] return points #Calculate parameters of the collision: # collision time, nearest node points, collision distance. # pos : position [x, y, t] # delta : velocity and period [dx, dy, dt] collisionParameters = (pos0, delta0, pos1, delta1) -> #pos and delta are 3-vectors: (x,y,t) # #deltax : dx+a*vx0-b*vx1; #deltay : dy+a*vy0-b*vy1; #deltat : dt+a*p0-b*p1; # Dropbox.Math.spaceship-collision [dx, dy, dt] = vecDiff pos0, pos1 [vx0, vy0, p0] = delta0 [vx1, vy1, p1] = delta1 # D = p0**2*vy1**2-2*p0*p1*vy0*vy1+p1**2*vy0**2 + p0**2*vx1**2-2*p0*p1*vx0*vx1+p1**2*vx0**2 D = (p0*vy1 - p1*vy0)**2 + (p0*vx1-p1*vx0)**2 a = -(dt*p0*vy1**2+(-dt*p1*vy0-dy*p0*p1)*vy1+dy*p1**2*vy0+dt*p0*vx1**2+(-dt*p1*vx0-dx*p0*p1)*vx1+dx*p1**2*vx0) / D b = -((dt*p0*vy0-dy*p0**2)*vy1-dt*p1*vy0**2+dy*p0*p1*vy0+(dt*p0*vx0-dx*p0**2)*vx1-dt*p1*vx0**2+dx*p0*p1*vx0) / D dist = Math.abs(dt*vx0*vy1-dx*p0*vy1-dt*vx1*vy0+dx*p1*vy0+dy*p0*vx1-dy*p1*vx0)/Math.sqrt(D) #nearest points with time before collision time ia = Math.floor(a)|0 ib = Math.floor(b)|0 npos0 = vecSum pos0, vecScale(delta0, ia) npos1 = vecSum pos1, vecScale(delta1, ib) tcoll = pos0[2] + delta0[2]*a tcoll1 = pos1[2] + delta1[2]*b #must be same as tcoll1 if Math.abs(tcoll-tcoll1) > 1e-6 then throw new Error "assert: tcoll" return { dist: dist #distance of the nearest approach npos0: npos0 npos1: npos1 #node point nearest to the collision (below) tcoll: tcoll #when nearest approach occurs } #In what rande DX can change, if minimal distanec between 2 patterns is less than dmax? # This fucntion gives the answer. # Calculation is in the maxima sheet: # solve( d2 = dd^2, dx ); dxRange = (dPos, v0, v1, dMax) -> #dPos, v0, v1 :: vector3 #dMax :: integer [_, dy, dt] = dPos #dx is ignored, because we will find its diapason [vx0, vy0, p0] = v0 [vx1, vy1, p1] = v1 #Solution from Maxima: # dx=-(dd*sqrt(p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2+p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2)-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0)/(p0*vy1-p1*vy0) # q = p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2+p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2 # # dx=(+-dd*sqrt(q)-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0)/(p1*vy0 - p0*vy1) num = p1*vy0 - p0*vy1 if num is 0 #throw new Error "Patterns are parallel and neveer touch" return [0, -1] dc = (-dt*vx0*vy1+dt*vx1*vy0-dy*p0*vx1+dy*p1*vx0) / num #q = p0^2*vy1^2-2*p0*p1*vy0*vy1+p1^2*vy0^2 + p0^2*vx1^2-2*p0*p1*vx0*vx1+p1^2*vx0^2 q = (p0*vy1-p1*vy0)**2 + (p0*vx1-p1*vx0)**2 #after small simplification delta = Math.abs(Math.sqrt(q) * (dMax / num)) #return upper and lower limits, rounded to integers return [Math.floor(dc - delta)|0, Math.ceil(dc + delta)|0] #Same as dxRange, but for dy. Reuses dxRange dyRange = (dPos, v0, v1, dMax) -> swapxy = ([x,y,t]) -> [y,x,t] dxRange swapxy(dPos), swapxy(v0), swapxy(v1), dMax #Chooses one of dxRange, dyRange. freeIndexRange = (dPos, v0, v1, dMax, index) -> if index not in [0..1] then throw new Error "Unsupported index #{index}" [dxRange, dyRange][index](dPos, v0, v1, dMax) #Calculate time, when 2 spaceship approach to the specified distance. approachParameters = (pos0, delta0, pos1, delta1, approachDistance) -> [dx, dy, dt] = vecDiff pos0, pos1 [vx0, vy0, p0] = delta0 [vx1, vy1, p1] = delta1 #solve( [deltax^2 + deltay^2 = dd^2, deltat=0], [a,b] ); dd = approachDistance D = (p0**2*vy1**2-2*p0*p1*vy0*vy1+p1**2*vy0**2+p0**2*vx1**2-2*p0*p1*vx0*vx1+p1**2*vx0**2) #thanks maxima. The formula is not well optimized, but I don't care. Q2 = (-dt**2*vx0**2+2*dt*dx*p0*vx0+(dd**2-dx**2)*p0**2)*vy1**2+(((2*dt**2*vx0-2*dt*dx*p0)*vx1-2*dt*dx*p1*vx0+(2*dx**2-2*dd**2)*p0*p1)*vy0+(2*dx*dy*p0**2-2*dt*dy*p0*vx0)*vx1+2*dt*dy*p1*vx0**2-2*dx*dy*p0*p1*vx0)*vy1+(-dt**2*vx1**2+2*dt*dx*p1*vx1+(dd**2-dx**2)*p1**2)*vy0**2+(2*dt*dy*p0*vx1**2+(-2*dt*dy*p1*vx0-2*dx*dy*p0*p1)*vx1+2*dx*dy*p1**2*vx0)*vy0+(dd**2-dy**2)*p0**2*vx1**2+(2*dy**2-2*dd**2)*p0*p1*vx0*vx1+(dd**2-dy**2)*p1**2*vx0**2 if Q2 < 0 #Approach not possible, spaceships are not coming close enough return {approach: false} Q = Math.sqrt(Q2) a = -(p1*Q+dt*p0*vy1**2+(-dt*p1*vy0-dy*p0*p1)*vy1+dy*p1**2*vy0+dt*p0*vx1**2+(-dt*p1*vx0-dx*p0*p1)*vx1+dx*p1**2*vx0) / D b = -(p0*Q+(dt*p0*vy0-dy*p0**2)*vy1-dt*p1*vy0**2+dy*p0*p1*vy0+(dt*p0*vx0-dx*p0**2)*vx1-dt*p1*vx0**2+dx*p0*p1*vx0) / D tapp = pos0[2]+p0*a tapp1 = pos1[2]+p1*b if Math.abs(tapp1-tapp) >1e-6 then throw new Error "Assertion failed" ia = Math.floor(a)|0 ib = Math.floor(b)|0 npos0 = vecSum pos0, vecScale(delta0, ia) npos1 = vecSum pos1, vecScale(delta1, ib) return { approach: true npos0 : npos0 #nearest positions before approach npos1 : npos1 tapp : tapp } #Give n position: [x,y,t] and delta: [dx,dy,dt], # Return position with biggest time <= t (inclusive). firstPositionBefore = (pos, delta, time) -> # find integer i: # t + i*dt < time # # i*dt < time - t # i < (time-t)/dt i0 = (time - pos[2]) / delta[2] #not integer. #now find the nearest integer below i = (Math.floor i0) |0 #and return the position vecSum pos, vecScale delta, i #Given spaceship trajectory, returns first it position before the given moment of time (inclusive) firstPositionAfter = (pos, delta, time) -> i0 = (time - pos[2]) / delta[2] #not integer. i = (Math.ceil i0) |0 vecSum pos, vecScale delta, i #Normalize pattern and returns its rle. normalizedRle = (fld) -> ff = Cells.copy fld Cells.normalize ff Cells.to_rle ff evalToTime = (rule, fld, t0, tend) -> if t > tend then throw new Error "assert: bad time" for t in [t0 ... tend] by 1 fld = evaluateCellList rule, fld, mod2(t) return fld #put the pattern to the specified time and position, and return its state at time t patternAt = (rule, pattern, posAndTime, t) -> pattern = Cells.copy pattern [x0,y0,t0] = posAndTime Cells.offset pattern, x0, y0 evalToTime rule, pattern, t0, t # Collide 2 patterns: p1 and p2, # p1 at [0,0,0] and p2 at `offset`. # initialSeparation::int approximate initial distance to put patterns at. Should be large enought for patterns not to intersect # offset: [dx, dy, dt] - initial offset of the pattern p2 (p1 at 000) # collisionTreshold:: if patterns don't come closer than this distance, don't consider them colliding. # waitForCollision::int How many generations to wait after the approximate nearest approach, until the interaction would start. # # Returned value: object # collision::bool true if collision # patterns :: [p1, p2] two patterns # offsets :: [vec1, vec2] first position of each pattern before collision time # timeStart::int first generation, where interaction has started # products::[ ProductDesc ] list of collision products (patterns with their positions and classification doCollision = (rule, library, p1, v1, p2, v2, offset, initialSeparation = 30, collisionTreshold=20)-> waitForCollision = v1[2] + v2[2] #sum of periods params = collisionParameters [0,0,0], v1, offset, v2 ap = approachParameters [0,0,0], v1, offset, v2, initialSeparation collision = {collision:false} if not ap.approach #console.log "#### No approach, nearest approach: #{params.dist}" return collision if params.dist > collisionTreshold #console.log "#### Too far, nearest approach #{params.dist} > #{collisionTreshold}" return collision #console.log "#### CP: #{JSON.stringify params}" #console.log "#### AP: #{JSON.stringify ap}" #Create the initial field. Put 2 patterns: p1 and p2 at initial time #nwo promote them to the same time, using list evaluation time = Math.max ap.npos0[2], ap.npos1[2] fld1 = patternAt rule, p1, ap.npos0, time fld2 = patternAt rule, p2, ap.npos1, time #OK, collision prepared. Now simulate both spaceships separately and # together, waiting while interaction occurs timeGiveUp = params.tcoll + waitForCollision #when to stop waiting for some interaction coll = simulateUntilCollision rule, [fld1, fld2], time, timeGiveUp fld1 = fld2 = null #They are not needed anymore if not coll.collided #console.log "#### No interaction detected until T=#{timeGiveUp}. Give up." return collision #console.log "#### colliding:" #console.log "#### 1) #{normalizedRle p1} at [0, 0, 0]" #console.log "#### 2) #{normalizedRle p2} at #{JSON.stringify offset}" #console.log "#### collision at T=#{coll.time} (give up at #{timeGiveUp})" collision.timeStart = coll.time collision.patterns = [p1, p2] collision.offsets = [ firstPositionBefore([0,0,0], v1, coll.time-1), firstPositionBefore(offset, v2, coll.time-1), ] collision.collision = true {products, verifyTime, verifyField} = finishCollision rule, library, coll.field, coll.time collision.products = products #findEmergeTime = (rule, products, minimalTime) -> collision.timeEnd = findEmergeTime rule, collision.products, collision.timeStart, verifyField, verifyTime #Update positions of products for product in collision.products product.pos = firstPositionAfter product.pos, product.delta, collision.timeEnd+1 #normalize relative to the first spaceship translateCollision collision, vecScale(collision.offsets[0], -1) #Offser collision information record by the given amount, in time and space translateCollision = (collision, dpos) -> [dx, dy, dt] = dpos for o, i in collision.offsets collision.offsets[i] = vecSum o, dpos collision.timeStart += dt collision.timeEnd += dt for product in collision.products product.pos = vecSum product.pos, dpos return collision #Simulate several patterns until they collide. # Return first oment of time, when patterns started interacting. simulateUntilCollision = (rule, patterns, time, timeGiveUp) -> if patterns.length < 2 then return {collided: false} # 1 pattern can't collide. fld = [].concat patterns ... #concatenate all patterns while time < timeGiveUp phase = mod2 time #evaluate each pattern separately #console.log "### patterns: #{JSON.stringify patterns}" patterns = (evaluateCellList(rule, p, phase) for p in patterns) #console.log "### after eval: #{JSON.stringify patterns}" #And together fld = evaluateCellList rule, fld, phase time += 1 #check if they are different mergedPatterns = [].concat patterns... Cells.sortXY fld Cells.sortXY mergedPatterns if not Cells.areEqual fld, mergedPatterns #console.log "#### Collision detected! T=#{time}, #{normalizedRle fld}" return { collided: true time: time field: fld } return{ collided: false } ### Given the rule and the list of collition products (with their positions) # find a moment of time when they emerged. # verifyField, verifyTime: knwon state of the field, for verification. ### findEmergeTime = (rule, products, minimalTime, verifyField, verifyTime) -> invRule = rule.reverse() #Time position of the latest fragment maxTime = Math.max (p.pos[2] for p in products)... if verifyTime? and maxTime < verifyTime throw new Error "Something is strange: maximal time of fragments smaller than verification time" #Prepare all fragments, at time maxTime patterns = for product in products #console.log "#### Product: #{JSON.stringify product}" #first, calculate first space-time point before the maxTime initialPos = firstPositionBefore product.pos, product.delta, maxTime #Put the pattern at this point pattern = Cells.transform product.pattern, product.transform, false patternAt rule, pattern, initialPos, maxTime if verifyTime? allPatterns = [].concat(patterns...) patternEvolution invRule, allPatterns, 1-maxTime, (p, t)-> if t is (1 - verifyTime) #console.log "#### verifying. At time #{1-t} " #console.log "#### Expected: #{normalizedRle verifyField}" #console.log "#### Got : #{normalizedRle p}" Cells.sortXY p Cells.sortXY verifyField if not Cells.areEqual verifyField, p throw new Error "Verification failed: reconstructed backward collision did not match expected" return false else return true #console.log "#### Generated #{patterns.length} patterns at time #{maxTime}:" #console.log "#### #{normalizedRle [].concat(patterns...)}" #Now simulate it inverse in time invCollision = simulateUntilCollision invRule, patterns, -maxTime+1, -minimalTime if not invCollision.collided throw new Error "Something is wrong: patterns did not collided in inverse time" return 1-invCollision.time #simulate patern until it decomposes into several simple patterns # Return list of collision products finishCollision = (rule, library, field, time) -> #console.log "#### Collision RLE: #{normalizedRle field}" growthLimit = field.length*3 + 8 #when to try to separate pattern while true field = evaluateCellList rule, field, mod2(time) time += 1 [x0, y0, x1,y1] = Cells.bounds field size = Math.max (x1-x0), (y1-y0) #console.log "#### T:#{time}, s:#{size}, R:#{normalizedRle field}" if size > growthLimit #console.log "#### At time #{time}, pattern grew to #{size}: #{normalizedRle field}" verifyTime = time verifyField = field break #now try to split result into several patterns parts = separatePatternParts field #console.log "#### Detected #{parts.length} parts" if parts.length is 1 #TODO: increase growth limit? #console.log "#### only one part, try more time" return finishCollision rule, library, field, time results = [] for part, i in parts #now analyze this part res = analyzeFragment rule, library, part, time for r in res results.push r return{ products: results verifyTime: verifyTime verifyField: field } analyzeFragment = (rule, library, pattern, time, options={})-> analysys = determinePeriod rule, pattern, time, options if analysys.cycle #console.log "#### Pattern analysys: #{JSON.stringify analysys}" res = library.classifyPattern pattern, time, analysys.delta... [res] else console.log "#### Pattern not decomposed completely: #{normalizedRle pattern} #{time}" finishCollision(rule, library, pattern, time).products #detect periodicity in pattern # Returns : # cycle::bool - is cycle found # error::str - if not cycle, says error details. Otherwise - udefined. # delta::[dx, dy, dt] - velocity and period, if cycle is found. determinePeriod = (rule, pattern, time, options={})-> pattern = Cells.copy pattern Cells.sortXY pattern max_iters = options.max_iters ? 2048 max_population = options.max_population ? 1024 max_size = options.max_size ? 1024 #wait for the cycle result = {cycle: false} patternEvolution rule, pattern, time, (curPattern, t) -> dt = t-time if dt is 0 then return true Cells.sortXY curPattern eq = Cells.shiftEqual pattern, curPattern, mod2 dt if eq result.cycle = true eq.push dt result.delta = eq return false if curPattern.length > max_population result.error = "pattern grew too big" return false bounds = Cells.bounds curPattern if Math.max( bounds[2]-bounds[0], bounds[3]-bounds[1]) > max_size result.error = "pattern dimensions grew too big" return false return true #continue evaluation return result snap_below = (x,generation) -> x - mod2(x + generation) #move pattern to 0, offsetToOrigin = (pattern, generation) -> [x0,y0] = Cells.topLeft pattern x0 = snap_below x0, generation y0 = snap_below y0, generation Cells.offset pattern, -x0, -y0 return [x0, y0] #Continuousely evaluate the pattern # Only returns pattern in ruleset phase 0. patternEvolution = (rule, pattern, time, callback)-> #pattern = Cells.copy pattern stable_rules = [rule] vacuum_period = stable_rules.length #ruleset size curPattern = pattern while true phase = mod2 time sub_rule_idx = mod time, vacuum_period if sub_rule_idx is 0 break unless callback curPattern, time curPattern = evaluateCellList stable_rules[sub_rule_idx], curPattern, phase time += 1 return class Library constructor: (@rule) -> @rle2pattern = {} #Assumes that pattern is in its canonical form addPattern: (pattern, data) -> rle = Cells.to_rle pattern if @rle2pattern.hasOwnProperty rle throw new Error "Pattern already present: #{rle}" @rle2pattern[rle] = data addRle: (rle, data) -> pattern = Cells.from_rle rle analysys = determinePeriod @rule, pattern, 0 if not analysys.cycle then throw new Error "Pattern #{rle} is not periodic!" #console.log "#### add anal: #{JSON.stringify analysys}" [dx,dy,p]=delta=analysys.delta unless (dx>0 and dy>=0) or (dx is 0 and dy is 0) throw new Error "Pattern #{rle} moves in wrong direction: #{dx},#{dy}" @addPattern pattern, data ? {delta: delta} classifyPattern: (pattern, time, dx, dy, period) -> #determine canonical ofrm ofthe pattern, present in the library; # return its offset #first: rotate the pattern caninically, if it is moving if dx isnt 0 or dy isnt 0 [dx1, dy1, tfm] = Cells._find_normalizing_rotation dx, dy pattern1 = Cells.transform pattern, tfm, false #no need to normalize result = @_classifyNormalizedPattern pattern1, time, dx1, dy1, period result.transform = inverseTfm tfm else #it is not a spaceship - no way to find a normal rotation. Check all 4 rotations. for tfm in Cells._rotations pattern1 = Cells.transform pattern, tfm, false result = @_classifyNormalizedPattern pattern1, time, 0, 0, period result.transform = inverseTfm tfm if result.found break #reverse-transform position [x,y,t] = result.pos #console.log "#### Original pos: #{JSON.stringify result.pos}" [x,y] = Cells.transformVector [x,y], result.transform #no normalize! #console.log "#### after inverse rotate: #{JSON.stringify [x,y,t]}" result.pos = [x,y,t] result.delta = [dx,dy,period] return result _classifyNormalizedPattern: (pattern, time, dx, dy, period) -> #console.log "#### Classifying: #{JSON.stringify pattern} at #{time}" result = {found:false} self = this patternEvolution @rule, pattern, time, (p, t)-> p = Cells.copy p [dx, dy] = offsetToOrigin p, t Cells.sortXY p rle = Cells.to_rle p #console.log "#### T:#{t}, rle:#{rle}" if rle of self.rle2pattern #console.log "#### found! #{rle}" result.pos = [dx, dy, t] result.rle = rle result.pattern = p result.found=true result.info = self.rle2pattern[rle] return false return (t-time) < period if not result.found p = Cells.copy pattern [dx, dy] = offsetToOrigin p, time Cells.sortXY p result.pos = [dx, dy, time] result.rle = Cells.to_rle p result.pattern = p result.found = false result.transform = [1,0,0,1] return result #load library from the simple JSON file. # Library format is simplified: "rle": data, where data is arbitrary object load: (file) -> fs = require "fs" libData = JSON.parse fs.readFileSync file, "utf8" #re-parse library data to ensure its correctness n = 0 for rle, data of libData @addPattern Cells.from_rle(rle), data n += 1 console.log "#### Loaded #{n} patterns from library #{file}" return # geometrically separate pattern into several disconnected parts # returns: list of sub-patterns separatePatternParts = (pattern, range=4) -> mpattern = {} #set of visited coordinates key = (x,y) -> PI:KEY:<KEY>END_PI has_cell = (x,y) -> mpattern.hasOwnProperty key x, y erase = (x,y) -> delete mpattern[ key x, y ] #convert pattern to map-based repersentation for xy in pattern mpattern[key xy...] = xy cells = [] #return true, if max size reached. do_pick_at = (x,y)-> erase x, y cells.push [x,y] for dy in [-range..range] by 1 y1 = y+dy for dx in [-range..range] by 1 continue if dy is 0 and dx is 0 x1 = x+dx if has_cell x1, y1 do_pick_at x1, y1 return parts = [] while true hadPattern = false for _k, xy of mpattern hadPattern = true #found at least one non-picked cell do_pick_at xy ... break if hadPattern parts.push cells cells = [] else break return parts #in margolus neighborhood, not all offsets produce the same pattern isValidOffset = ([dx, dy, dt]) -> ((dx+dt)%2 is 0) and ((dy+dt)%2 is 0) ############################ #Mostly for debug: display cllision indormation showCollision = (collision)-> console.log "##########################################################" for key, value of collision switch key when "collision" null when "products" for p, i in value console.log "#### -> #{i+1}: #{JSON.stringify p}" when "patterns" [p1,p2] = collision.patterns console.log "#### patterns: #{Cells.to_rle p1}, #{Cells.to_rle p2}" else console.log "#### #{key}: #{JSON.stringify value}" #### colliding with offset [0,0,0] #### CP: {"dist":0,"npos0":[0,0,0],"npos1":[0,0,0],"tcoll":0} #### AP: {"approach":true,"npos0":[-30,0,-180],"npos1":[0,0,-180],"tapp":-180} #### Collision RLE: $1379bo22$2o2$2o ### Calculate the space of all principially different relative positions of 2 patterns # Returns: # elementaryCell: list of 3-vectors of relative positions # freeIndex: index of the coordinate, that changes freely. 0 or 1 for valid patterns ### determinePatternRelativePositionsSpace = (v1, v2) -> [freeIndex, freeOrt] = opposingOrt v1, v2 #console.log "Free offset direction: #{freeOrt}, free index is #{freeIndex}" pv1 = removeComponent v1, freeIndex pv2 = removeComponent v2, freeIndex #console.log "Projected to null-space of free ort:" #console.log " PV1=#{pv1}, PV2=#{pv2}" #s = area2d pv1, pv2 #console.log "Area of non-free section: #{s}" ecell = (restoreComponent(v,freeIndex) for v in elementaryCell2d(pv1, pv2)) if ecell.length isnt Math.abs area2d pv1, pv2 throw new Error "elementary cell size is wrong" return{ elementaryCell: ecell freeIndex: freeIndex } ### Call the callback for all collisions between these 2 patterns ### allCollisions = (rule, library, pattern1, pattern2, onCollision) -> v2 = (determinePeriod rule, pattern2, 0).delta v1 = (determinePeriod rule, pattern1, 0).delta console.log "Two velocities: #{v1}, #{v2}" {elementaryCell, freeIndex} = determinePatternRelativePositionsSpace v1, v2 #now we are ready to perform collisions # free index changes unboundedly, other variables change inside the elementary cell minimalTouchDistance = (pattern1.length + pattern2.length + 1)*3 #console.log "#### Minimal touch distance is #{minimalTouchDistance}" for offset in elementaryCell #dPos, v0, v1, dMax, index offsetRange = freeIndexRange offset, v1, v2, minimalTouchDistance, freeIndex #console.log "#### FOr offset #{JSON.stringify offset}, index range is #{JSON.stringify offsetRange}" for xFree in [offsetRange[0] .. offsetRange[1]] by 1 offset = offset[..] offset[freeIndex] = xFree if isValidOffset offset collision = doCollision rule, library, pattern1, v1, pattern2, v2, offset, minimalTouchDistance*2, minimalTouchDistance if collision.collision onCollision collision return runCollider = -> #single rotate - for test rule = from_list_elem [0,2,8,3,1,5,6,7,4,9,10,11,12,13,14,15] library = new Library rule library.load "./singlerot-simple.lib.json" #2-block pattern2 = Cells.from_rle "$2o2$2o" pattern1 = Cells.from_rle "o" allCollisions rule, library, pattern1, pattern2, (collision) -> showCollision collision makeCollisionCatalog = (rule, library, pattern1, pattern2) -> catalog = [] allCollisions rule, library, pattern1, pattern2, (collision) -> #showCollision collision catalog.push collision return catalog # Main fgunctons, that reads command line parameters and generates collision catalog mainCatalog = -> stdio = require "stdio" opts = stdio.getopt { output: key: 'o' args: 1 description: "Output file. Default is collisions-[p1]-[p2]-rule.json" rule: key:'r' args: 1 description: "Rule (16 integers). Default is SingleRotation" libs: key:"L" args: 1 description: "List of libraries to load. Use : to separate files" }, "pattern1 pattern2" ################# Parsing options ####################### unless opts.args? and opts.args.length in [2..2] process.stderr.write "Not enough arguments\n" process.exit 1 [rle1, rle2] = opts.args pattern1 = Cells.from_rle rle1 pattern2 = Cells.from_rle rle2 console.log "#### RLEs: #{rle1}, #{rle2}" console.log "Colliding 2 patterns:" console.log pattern2string pattern1 console.log "--------" console.log pattern2string pattern2 rule = if opts.rule? parseElementary opts.rule else from_list_elem [0,2,8,3,1,5,6,7,4,9,10,11,12,13,14,15] unless rule.is_vacuum_stable() throw new Error "Rule is not vacuum-stable. Not supported currently." unless rule.is_invertible() throw new Error "Rule is not invertible. Not supported currently." outputFile = if opts.output? opts.output else "collisions-#{normalizedRle pattern1}-#{normalizedRle pattern2}-#{rule.stringify()}.json" libFiles = if opts.libs? opts.libs.split ":" else [] ############### Running the collisions ################### library = new Library rule for libFile in libFiles library.load libFile czs = makeCollisionCatalog rule, library, pattern1, pattern2 console.log "Found #{czs.length} collisions, stored in #{outputFile}" fs = require "fs" czsData = rule: rule.to_list() patterns: [pattern1, pattern2] collisions: czs fs.writeFileSync outputFile, JSON.stringify(czsData), {encoding:"utf8"} pattern2string = (pattern, signs = ['.', '#']) -> [x0, y0, x1, y1] = Cells.bounds pattern x0 -= mod2 x0 y0 -= mod2 y0 x1 += 1 y1 += 1 x1 += mod2 x1 y1 += mod2 y1 w = x1 - x0 h = y1 - y0 fld = ((signs[0] for i in [0...w]) for j in [0...h]) for [x,y] in pattern fld[y-y0][x-x0] = signs[1] return (row.join("") for row in fld).join("\n") #runCollider() mainCatalog()
[ { "context": "###\n QuoJS 2.1\n (c) 2011, 2012 Javi Jiménez Villar (@soyjavi)\n http://quojs.tapquo.com\n###\n\n(($$) -", "end": 52, "score": 0.9998698234558105, "start": 33, "tag": "NAME", "value": "Javi Jiménez Villar" }, { "context": "#\n QuoJS 2.1\n (c) 2011, 2012 Javi Jiménez Villar (@soyjavi)\n http://quojs.tapquo.com\n###\n\n(($$) ->\n\n $$.", "end": 62, "score": 0.9995682835578918, "start": 53, "tag": "USERNAME", "value": "(@soyjavi" } ]
src/QuoJS/src/quo.element.coffee
biojazzard/kirbout
2
### QuoJS 2.1 (c) 2011, 2012 Javi Jiménez Villar (@soyjavi) http://quojs.tapquo.com ### (($$) -> $$.fn.attr = (name, value) -> if $$.toType(name) is "string" and value is undefined this[0].getAttribute name else @each -> @setAttribute name, value $$.fn.data = (name, value) -> @attr "data-" + name, value $$.fn.val = (value) -> if $$.toType(value) is "string" @each -> @value = value else (if @length > 0 then this[0].value else null) $$.fn.show = -> @style "display", "block" $$.fn.hide = -> @style "display", "none" $$.fn.height = -> offset = @offset() offset.height $$.fn.width = -> offset = @offset() offset.width $$.fn.offset = -> bounding = this[0].getBoundingClientRect() left: bounding.left + window.pageXOffset top: bounding.top + window.pageYOffset width: bounding.width height: bounding.height $$.fn.remove = -> @each -> @parentNode.removeChild this if @parentNode? return ) Quo
203848
### QuoJS 2.1 (c) 2011, 2012 <NAME> (@soyjavi) http://quojs.tapquo.com ### (($$) -> $$.fn.attr = (name, value) -> if $$.toType(name) is "string" and value is undefined this[0].getAttribute name else @each -> @setAttribute name, value $$.fn.data = (name, value) -> @attr "data-" + name, value $$.fn.val = (value) -> if $$.toType(value) is "string" @each -> @value = value else (if @length > 0 then this[0].value else null) $$.fn.show = -> @style "display", "block" $$.fn.hide = -> @style "display", "none" $$.fn.height = -> offset = @offset() offset.height $$.fn.width = -> offset = @offset() offset.width $$.fn.offset = -> bounding = this[0].getBoundingClientRect() left: bounding.left + window.pageXOffset top: bounding.top + window.pageYOffset width: bounding.width height: bounding.height $$.fn.remove = -> @each -> @parentNode.removeChild this if @parentNode? return ) Quo
true
### QuoJS 2.1 (c) 2011, 2012 PI:NAME:<NAME>END_PI (@soyjavi) http://quojs.tapquo.com ### (($$) -> $$.fn.attr = (name, value) -> if $$.toType(name) is "string" and value is undefined this[0].getAttribute name else @each -> @setAttribute name, value $$.fn.data = (name, value) -> @attr "data-" + name, value $$.fn.val = (value) -> if $$.toType(value) is "string" @each -> @value = value else (if @length > 0 then this[0].value else null) $$.fn.show = -> @style "display", "block" $$.fn.hide = -> @style "display", "none" $$.fn.height = -> offset = @offset() offset.height $$.fn.width = -> offset = @offset() offset.width $$.fn.offset = -> bounding = this[0].getBoundingClientRect() left: bounding.left + window.pageXOffset top: bounding.top + window.pageYOffset width: bounding.width height: bounding.height $$.fn.remove = -> @each -> @parentNode.removeChild this if @parentNode? return ) Quo
[ { "context": "ll,\"Aapeli\",\"Elmo ja Elmer\",\"Ruut\",\"Lea ja Leea\",\"Harri\",\"Aukusti, Aku\",\"Hilppa ja Titta\",\"Veikko, Veli j", "end": 87, "score": 0.8743336796760559, "start": 82, "tag": "NAME", "value": "Harri" }, { "context": "mari ja Ilmo\",\"Toni ja Anttoni\",\"Laura\",\"Heikki ja Henrik\",\"Henna ja Henni\",\"Aune ja Oona\",\"Visa\",\"Eine, Ei", "end": 280, "score": 0.7228386998176575, "start": 274, "tag": "NAME", "value": "Henrik" }, { "context": "mo\",\"Toni ja Anttoni\",\"Laura\",\"Heikki ja Henrik\",\"Henna ja Henni\",\"Aune ja Oona\",\"Visa\",\"Eine, Eini ja En", "end": 288, "score": 0.8290072679519653, "start": 283, "tag": "NAME", "value": "Henna" }, { "context": "i ja Anttoni\",\"Laura\",\"Heikki ja Henrik\",\"Henna ja Henni\",\"Aune ja Oona\",\"Visa\",\"Eine, Eini ja Enni\",\"Senj", "end": 297, "score": 0.7979479432106018, "start": 292, "tag": "NAME", "value": "Henni" }, { "context": "ri\",\"Irja\",\"Alli\"],\n\n [\"Riitta\",\"Aamu\",\"Valo\",\"Armi\",\"Asser\",\"Terhi, Teija ja Tiia\",\"Riku ja Rikhard\"", "end": 470, "score": 0.6216833591461182, "start": 466, "tag": "NAME", "value": "Armi" }, { "context": "ja\",\"Alli\"],\n\n [\"Riitta\",\"Aamu\",\"Valo\",\"Armi\",\"Asser\",\"Terhi, Teija ja Tiia\",\"Riku ja Rikhard\",\"Lain", "end": 476, "score": 0.551880419254303, "start": 473, "tag": "NAME", "value": "Ass" }, { "context": "va\",\"Kauko\",\"Ari, Arsi ja Atro\",\"Laila ja Leila\",\"Tarmo\",\"Tarja ja Taru\",\"Vilppu\",\"Auvo\",\"Aurora, Aura ", "end": 881, "score": 0.5986247062683105, "start": 878, "tag": "NAME", "value": "Tar" }, { "context": "akim ja Kim\",\"Pentti\",\"Vihtori\",\"Akseli\",\"Kaapo ja Gabriel\",\"Aija\",\"Manu ja Immanuel\",\n \"Sauli ja Sau", "end": 1142, "score": 0.8536331653594971, "start": 1139, "tag": "NAME", "value": "Gab" }, { "context": "\",\"Aija\",\"Manu ja Immanuel\",\n \"Sauli ja Saul\",\"Armas\",\"Joonas, Jouni ja Joni\",\"Usko ja Tage\",\"Irma ja ", "end": 1201, "score": 0.7371399402618408, "start": 1196, "tag": "NAME", "value": "Armas" }, { "context": "hvo\",\"Suoma ja Suometar\",\"Elias ja Eelis\",\"Tero\",\"Verna\",\"Julius ja Julia\",\"Tellervo\",\"Taito\",\n \"L", "end": 1405, "score": 0.7083012461662292, "start": 1404, "tag": "NAME", "value": "V" }, { "context": "oma ja Suometar\",\"Elias ja Eelis\",\"Tero\",\"Verna\",\"Julius ja Julia\",\"Tellervo\",\"Taito\",\n \"Linda ja Tuomi", "end": 1418, "score": 0.890639066696167, "start": 1412, "tag": "NAME", "value": "Julius" }, { "context": "ometar\",\"Elias ja Eelis\",\"Tero\",\"Verna\",\"Julius ja Julia\",\"Tellervo\",\"Taito\",\n \"Linda ja Tuomi\",\"Jalo j", "end": 1427, "score": 0.9968808889389038, "start": 1422, "tag": "NAME", "value": "Julia" }, { "context": "Elias ja Eelis\",\"Tero\",\"Verna\",\"Julius ja Julia\",\"Tellervo\",\"Taito\",\n \"Linda ja Tuomi\",\"Jalo ja Patrik\"", "end": 1436, "score": 0.6493923664093018, "start": 1430, "tag": "NAME", "value": "Teller" }, { "context": ",\"Tellervo\",\"Taito\",\n \"Linda ja Tuomi\",\"Jalo ja Patrik\",\"Otto\",\"Valto ja Valdemar\",\"Päivi ja Pilvi\",\"", "end": 1482, "score": 0.8810945749282837, "start": 1479, "tag": "NAME", "value": "Pat" }, { "context": "\",\"Taito\",\n \"Linda ja Tuomi\",\"Jalo ja Patrik\",\"Otto\",\"Valto ja Valdemar\",\"Päivi ja Pilvi\",\"Lauha\",\"", "end": 1490, "score": 0.697604238986969, "start": 1488, "tag": "NAME", "value": "Ot" }, { "context": "o\",\n \"Linda ja Tuomi\",\"Jalo ja Patrik\",\"Otto\",\"Valto ja Valdemar\",\"Päivi ja Pilvi\",\"Lauha\",\"Anssi ja", "end": 1498, "score": 0.5443505644798279, "start": 1495, "tag": "NAME", "value": "Val" }, { "context": "\"Linda ja Tuomi\",\"Jalo ja Patrik\",\"Otto\",\"Valto ja Valdemar\",\"Päivi ja Pilvi\",\"Lauha\",\"Anssi ja Anselmi\"", "end": 1507, "score": 0.7248390913009644, "start": 1504, "tag": "NAME", "value": "Val" }, { "context": "Markku, Markus ja Marko\",\n \"Terttu ja Teresa\",\"Merja\",\"Ilpo ja Ilppo\",\"Teijo\",\"Mirja, Mirva, Mira ja", "end": 1661, "score": 0.8337084650993347, "start": 1658, "tag": "NAME", "value": "Mer" }, { "context": "ja Roosa\",\"Maini\",\"Ylermi\",\"Helmi ja Kastehelmi\",\"Heino\",\"Timo\",\"Aino, Aina ja Aini\",\"Osmo\",\"Lotta\",\"K", "end": 1828, "score": 0.704220712184906, "start": 1826, "tag": "NAME", "value": "He" }, { "context": "\"Into\",\"Ahti ja Ahto\",\"Paula, Liina ja Pauliina\",\"Aatto, Aatu ja Aadolf\",\"Johannes, Juhani ja Juha\",\"", "end": 2472, "score": 0.559539794921875, "start": 2471, "tag": "NAME", "value": "A" }, { "context": "a Ahto\",\"Paula, Liina ja Pauliina\",\"Aatto, Aatu ja Aadolf\",\"Johannes, Juhani ja Juha\",\"Uuno\",\"Jorma, Jar", "end": 2489, "score": 0.5500727891921997, "start": 2486, "tag": "NAME", "value": "Aad" }, { "context": " Pekka, Petri ja Petra\",\"Päiviö ja Päivö\"],\n [\"Aaro ja Aaron\",\"Maria, Mari, Maija, Meeri ja Maaria\",\"", "end": 2645, "score": 0.8186900615692139, "start": 2641, "tag": "NAME", "value": "Aaro" }, { "context": " Petri ja Petra\",\"Päiviö ja Päivö\"],\n [\"Aaro ja Aaron\",\"Maria, Mari, Maija, Meeri ja Maaria\",\"Arvo\",\"Ul", "end": 2654, "score": 0.8842349052429199, "start": 2649, "tag": "NAME", "value": "Aaron" }, { "context": " Petra\",\"Päiviö ja Päivö\"],\n [\"Aaro ja Aaron\",\"Maria, Mari, Maija, Meeri ja Maaria\",\"Arvo\",\"Ulla ja Up", "end": 2662, "score": 0.7327789068222046, "start": 2657, "tag": "NAME", "value": "Maria" }, { "context": " ja Aaron\",\"Maria, Mari, Maija, Meeri ja Maaria\",\"Arvo\",\"Ulla ja Upu\",\"Unto ja Untamo\",\"Esa ja Esaias\",\"", "end": 2699, "score": 0.8226526975631714, "start": 2695, "tag": "NAME", "value": "Arvo" }, { "context": "a Turkka\",\"Ilta ja Jasmin\",\"Saima ja Saimi\",\n \"Elli, Noora ja Nelli\",\"Hermanni, Herkko\",\"Ilari, Lar", "end": 2824, "score": 0.6568340063095093, "start": 2822, "tag": "NAME", "value": "El" }, { "context": "in\",\"Saima ja Saimi\",\n \"Elli, Noora ja Nelli\",\"Hermanni, Herkko\",\"Ilari, Lari ja Joel\",\"Aliisa\",\"Rauni j", "end": 2852, "score": 0.6575584411621094, "start": 2845, "tag": "NAME", "value": "Hermann" }, { "context": "Salli ja Salla\",\"Marketta, Maarit ja Reeta\",\n \"Johanna, Hanna ja Jenni\",\"Leena, Leeni ja Lenita\",\"Oili j", "end": 3016, "score": 0.8760660290718079, "start": 3009, "tag": "NAME", "value": "Johanna" }, { "context": " Salla\",\"Marketta, Maarit ja Reeta\",\n \"Johanna, Hanna ja Jenni\",\"Leena, Leeni ja Lenita\",\"Oili ja Olga\"", "end": 3023, "score": 0.882082462310791, "start": 3018, "tag": "NAME", "value": "Hanna" }, { "context": "Marketta, Maarit ja Reeta\",\n \"Johanna, Hanna ja Jenni\",\"Leena, Leeni ja Lenita\",\"Oili ja Olga\",\"Kirsti,", "end": 3032, "score": 0.6374313235282898, "start": 3027, "tag": "NAME", "value": "Jenni" }, { "context": " Maarit ja Reeta\",\n \"Johanna, Hanna ja Jenni\",\"Leena, Leeni ja Lenita\",\"Oili ja Olga\",\"Kirsti, Tiin", "end": 3037, "score": 0.6834537982940674, "start": 3035, "tag": "NAME", "value": "Le" }, { "context": "a Jenni\",\"Leena, Leeni ja Lenita\",\"Oili ja Olga\",\"Kirsti, Tiina, Kirsi ja Kristiina\",\"Jaakko ja Jaakoppi\"", "end": 3080, "score": 0.8848908543586731, "start": 3075, "tag": "NAME", "value": "Kirst" }, { "context": "Leena, Leeni ja Lenita\",\"Oili ja Olga\",\"Kirsti, Tiina, Kirsi ja Kristiina\",\"Jaakko ja Jaakoppi\",\"Martta", "end": 3088, "score": 0.7359725832939148, "start": 3085, "tag": "NAME", "value": "ina" }, { "context": "a, Leeni ja Lenita\",\"Oili ja Olga\",\"Kirsti, Tiina, Kirsi ja Kristiina\",\"Jaakko ja Jaakoppi\",\"Martta\",\"", "end": 3091, "score": 0.5682159662246704, "start": 3090, "tag": "NAME", "value": "K" }, { "context": "ja Lenita\",\"Oili ja Olga\",\"Kirsti, Tiina, Kirsi ja Kristiina\",\"Jaakko ja Jaakoppi\",\"Martta\",\"Heidi\",\"Atso\"", "end": 3104, "score": 0.7484309673309326, "start": 3099, "tag": "NAME", "value": "Krist" }, { "context": " Tiina, Kirsi ja Kristiina\",\"Jaakko ja Jaakoppi\",\"Martta\",\"Heidi\",\"Atso\",\"Olavi, Olli, Uolevi ja Uoti\",\"As", "end": 3138, "score": 0.7278155088424683, "start": 3132, "tag": "NAME", "value": "Martta" }, { "context": "na\",\"Jaakko ja Jaakoppi\",\"Martta\",\"Heidi\",\"Atso\",\"Olavi, Olli, Uolevi ja Uoti\",\"Asta\",\n \"Helena ja ", "end": 3158, "score": 0.5062903165817261, "start": 3156, "tag": "NAME", "value": "Ol" }, { "context": "\"Atso\",\"Olavi, Olli, Uolevi ja Uoti\",\"Asta\",\n \"Helena ja Elena\"],\n [\"Maire\",\"Kimmo\",\"Linnea, Nea ", "end": 3201, "score": 0.5681074857711792, "start": 3198, "tag": "NAME", "value": "Hel" }, { "context": "vi, Olli, Uolevi ja Uoti\",\"Asta\",\n \"Helena ja Elena\"],\n [\"Maire\",\"Kimmo\",\"Linnea, Nea ja Vanamo\",", "end": 3212, "score": 0.5227389335632324, "start": 3209, "tag": "NAME", "value": "len" }, { "context": "vi ja Uoti\",\"Asta\",\n \"Helena ja Elena\"],\n [\"Maire\",\"Kimmo\",\"Linnea, Nea ja Vanamo\",\"Veera\",\"Salme j", "end": 3228, "score": 0.893035888671875, "start": 3223, "tag": "NAME", "value": "Maire" }, { "context": "ti\",\"Asta\",\n \"Helena ja Elena\"],\n [\"Maire\",\"Kimmo\",\"Linnea, Nea ja Vanamo\",\"Veera\",\"Salme ja Sanelm", "end": 3236, "score": 0.7680702209472656, "start": 3231, "tag": "NAME", "value": "Kimmo" }, { "context": "a\",\n \"Helena ja Elena\"],\n [\"Maire\",\"Kimmo\",\"Linnea, Nea ja Vanamo\",\"Veera\",\"Salme ja Sanelma\",\"Toimi", "end": 3245, "score": 0.8465551733970642, "start": 3239, "tag": "NAME", "value": "Linnea" }, { "context": "a ja Elena\"],\n [\"Maire\",\"Kimmo\",\"Linnea, Nea ja Vanamo\",\"Veera\",\"Salme ja Sanelma\",\"Toimi ja Keimo\",\"Lah", "end": 3260, "score": 0.5528743863105774, "start": 3254, "tag": "NAME", "value": "Vanamo" }, { "context": "a Lassi\",\"Sanna, Susanna ja Sanni\",\"Klaara\",\n \"Jesse\",\"Onerva ja Kanerva\",\"Marjatta, Marja ja Jaan", "end": 3420, "score": 0.5377756953239441, "start": 3419, "tag": "NAME", "value": "J" }, { "context": "\",\"Onerva ja Kanerva\",\"Marjatta, Marja ja Jaana\",\"Aulis\",\"Verneri\",\"Leevi\",\"Mauno ja Maunu\",\"Samuli, Sami", "end": 3479, "score": 0.7895745635032654, "start": 3474, "tag": "NAME", "value": "Aulis" }, { "context": "a ja Kanerva\",\"Marjatta, Marja ja Jaana\",\"Aulis\",\"Verneri\",\"Leevi\",\"Mauno ja Maunu\",\"Samuli, Sami, Samuel ", "end": 3488, "score": 0.7714263200759888, "start": 3482, "tag": "NAME", "value": "Verner" }, { "context": ",\"Perttu\",\n \"Loviisa\",\"Ilma, Ilmi ja Ilmatar\",\"Rauli\",\"Tauno\",\"Iines, Iina ja Inari\",\"Eemil ja Eeme", "end": 3649, "score": 0.8337339758872986, "start": 3647, "tag": "NAME", "value": "Ra" }, { "context": "\",\n \"Loviisa\",\"Ilma, Ilmi ja Ilmatar\",\"Rauli\",\"Tauno\",\"Iines, Iina ja Inari\",\"Eemil ja Eemeli\",\"Arv", "end": 3657, "score": 0.6058800220489502, "start": 3655, "tag": "NAME", "value": "Ta" }, { "context": "Loviisa\",\"Ilma, Ilmi ja Ilmatar\",\"Rauli\",\"Tauno\",\"Iines, Iina ja Inari\",\"Eemil ja Eemeli\",\"Arvi\"],\n ", "end": 3664, "score": 0.5912212133407593, "start": 3663, "tag": "NAME", "value": "I" }, { "context": "irkka\",\"Sinikka ja Sini\",\"Soili, Soile ja Soila\",\"Ansa\",\"Mainio\",\"Asko\",\"Arho ja Arhippa\",\"Taimi\",\"Eev", "end": 3771, "score": 0.6208400726318359, "start": 3769, "tag": "NAME", "value": "An" }, { "context": "\"Sinikka ja Sini\",\"Soili, Soile ja Soila\",\"Ansa\",\"Mainio\",\"Asko\",\"Arho ja Arhippa\",\"Taimi\",\"Eevert ja Is", "end": 3780, "score": 0.7188870310783386, "start": 3776, "tag": "NAME", "value": "Main" }, { "context": "ja Sini\",\"Soili, Soile ja Soila\",\"Ansa\",\"Mainio\",\"Asko\",\"Arho ja Arhippa\",\"Taimi\",\"Eevert ja Isto\",\"Ka", "end": 3787, "score": 0.8092692494392395, "start": 3785, "tag": "NAME", "value": "As" }, { "context": "ko, Mika, Mikael, Miika\",\"Sorja ja Sirja\"],\n [\"Rauno, Rainer, Raine ja Raino\",\"Valio\",\"Raimo\",\"Saila j", "end": 4173, "score": 0.8463892936706543, "start": 4168, "tag": "NAME", "value": "Rauno" }, { "context": "ka, Mikael, Miika\",\"Sorja ja Sirja\"],\n [\"Rauno, Rainer, Raine ja Raino\",\"Valio\",\"Raimo\",\"Saila ja Saija\"", "end": 4181, "score": 0.884143054485321, "start": 4175, "tag": "NAME", "value": "Rainer" }, { "context": "el, Miika\",\"Sorja ja Sirja\"],\n [\"Rauno, Rainer, Raine ja Raino\",\"Valio\",\"Raimo\",\"Saila ja Saija\",\"I", "end": 4184, "score": 0.5020775198936462, "start": 4183, "tag": "NAME", "value": "R" }, { "context": "\",\"Sorja ja Sirja\"],\n [\"Rauno, Rainer, Raine ja Raino\",\"Valio\",\"Raimo\",\"Saila ja Saija\",\"Inkeri ja Ink", "end": 4196, "score": 0.5556167364120483, "start": 4192, "tag": "NAME", "value": "Rain" }, { "context": "ja Sirja\"],\n [\"Rauno, Rainer, Raine ja Raino\",\"Valio\",\"Raimo\",\"Saila ja Saija\",\"Inkeri ja Inka\",\"Mintt", "end": 4205, "score": 0.9031111001968384, "start": 4200, "tag": "NAME", "value": "Valio" }, { "context": "\",\"Ursula\",\n \"Anja, Anita, Anniina ja Anitta\",\"Severi\",\"Asmo\",\"Sointu\",\"Amanda ja Niina, Manta\",\"He", "end": 4564, "score": 0.5299976468086243, "start": 4562, "tag": "NAME", "value": "Se" }, { "context": "Severi\",\"Asmo\",\"Sointu\",\"Amanda ja Niina, Manta\",\"Helli, Hellä, Hellin ja Helle\",\"Simo\",\"Alfred ja Urma", "end": 4615, "score": 0.53000408411026, "start": 4612, "tag": "NAME", "value": "Hel" }, { "context": "ja Urmas\",\"Eila\",\"Artturi, Arto ja Arttu\"],\n [\"Pyry ja Lyly\",\"Topi ja Topias\",\"Terho\",\"Hertta\",\"Reima", "end": 4712, "score": 0.6387995481491089, "start": 4708, "tag": "NAME", "value": "Pyry" }, { "context": "s\",\"Eila\",\"Artturi, Arto ja Arttu\"],\n [\"Pyry ja Lyly\",\"Topi ja Topias\",\"Terho\",\"Hertta\",\"Reima\",\"Ku", "end": 4717, "score": 0.5200628042221069, "start": 4716, "tag": "NAME", "value": "L" }, { "context": "ja Arttu\"],\n [\"Pyry ja Lyly\",\"Topi ja Topias\",\"Terho\",\"Hertta\",\"Reima\",\"Kustaa Aadolf\",\"Taisto\",\"Aat", "end": 4743, "score": 0.6568832993507385, "start": 4740, "tag": "NAME", "value": "Ter" }, { "context": "\"],\n [\"Pyry ja Lyly\",\"Topi ja Topias\",\"Terho\",\"Hertta\",\"Reima\",\"Kustaa Aadolf\",\"Taisto\",\"Aatos\",\"Teuvo\"", "end": 4754, "score": 0.6986660957336426, "start": 4748, "tag": "NAME", "value": "Hertta" }, { "context": " Lyly\",\"Topi ja Topias\",\"Terho\",\"Hertta\",\"Reima\",\"Kustaa Aadolf\",\"Taisto\",\"Aatos\",\"Teuvo\",\"Martti\",\"P", "end": 4766, "score": 0.5912169814109802, "start": 4765, "tag": "NAME", "value": "K" }, { "context": "Topi ja Topias\",\"Terho\",\"Hertta\",\"Reima\",\"Kustaa Aadolf\",\"Taisto\",\"Aatos\",\"Teuvo\",\"Martti\",\"Panu\",\"Vir", "end": 4775, "score": 0.5992940068244934, "start": 4773, "tag": "NAME", "value": "ad" }, { "context": "ja Janina\",\n \"Aarne ja Aarno, Aarni\",\"Eino ja Einar\",\"Tenho ja Jousia\",\"Liisa, Eliisa, Elisa ja Elisa", "end": 4925, "score": 0.5380721092224121, "start": 4921, "tag": "NAME", "value": "inar" }, { "context": "kki ja Sivi\",\n \"Katri, Kaisa, Kaija ja Katja\",\"Sisko\",\"Hilkka\",\"Heini\",\"Aimo\",\"Antti, Antero ja Atte", "end": 5096, "score": 0.5488119125366211, "start": 5093, "tag": "NAME", "value": "Sis" }, { "context": "ivi\",\n \"Katri, Kaisa, Kaija ja Katja\",\"Sisko\",\"Hilkka\",\"Heini\",\"Aimo\",\"Antti, Antero ja Atte\"],\n [\"O", "end": 5107, "score": 0.6765437722206116, "start": 5101, "tag": "NAME", "value": "Hilkka" }, { "context": " \"Katri, Kaisa, Kaija ja Katja\",\"Sisko\",\"Hilkka\",\"Heini\",\"Aimo\",\"Antti, Antero ja Atte\"],\n [\"Oskari\",\"", "end": 5115, "score": 0.7498193383216858, "start": 5110, "tag": "NAME", "value": "Heini" }, { "context": " Kaisa, Kaija ja Katja\",\"Sisko\",\"Hilkka\",\"Heini\",\"Aimo\",\"Antti, Antero ja Atte\"],\n [\"Oskari\",\"Anelma ", "end": 5122, "score": 0.7341777086257935, "start": 5118, "tag": "NAME", "value": "Aimo" }, { "context": "li, Tatu ja Daniel\",\n \"Tuovi\",\"Seija\",\"Jouko\",\"Heimo\",\"Auli ja Aulikki\",\"Raakel\",\"Aapo, Aappo ja Ra", "end": 5377, "score": 0.5820959210395813, "start": 5375, "tag": "NAME", "value": "He" }, { "context": "Tuovi\",\"Seija\",\"Jouko\",\"Heimo\",\"Auli ja Aulikki\",\"Raakel\",\"Aapo, Aappo ja Rami\",\"Iikka, Iiro, Iisakki ", "end": 5403, "score": 0.8852635622024536, "start": 5401, "tag": "NAME", "value": "Ra" }, { "context": "eija\",\"Jouko\",\"Heimo\",\"Auli ja Aulikki\",\"Raakel\",\"Aapo, Aappo ja Rami\",\"Iikka, Iiro, Iisakki ja Isko\"", "end": 5411, "score": 0.7803170084953308, "start": 5410, "tag": "NAME", "value": "A" }, { "context": "\"Heimo\",\"Auli ja Aulikki\",\"Raakel\",\"Aapo, Aappo ja Rami\",\"Iikka, Iiro, Iisakki ja Isko\",\"Benjamin ja K", "end": 5426, "score": 0.5291218161582947, "start": 5425, "tag": "NAME", "value": "R" }, { "context": "o, Aappo ja Rami\",\"Iikka, Iiro, Iisakki ja Isko\",\"Benjamin ja Kerkko\",\"Tuomas, Tuomo ja Tommi\",\"Raafael\",\"Se", "end": 5471, "score": 0.9160068035125732, "start": 5463, "tag": "NAME", "value": "Benjamin" }, { "context": "i\",\"Iikka, Iiro, Iisakki ja Isko\",\"Benjamin ja Kerkko\",\"Tuomas, Tuomo ja Tommi\",\"Raafael\",\"Senni\",\n ", "end": 5479, "score": 0.704706609249115, "start": 5478, "tag": "NAME", "value": "k" }, { "context": "kka, Iiro, Iisakki ja Isko\",\"Benjamin ja Kerkko\",\"Tuomas, Tuomo ja Tommi\",\"Raafael\",\"Senni\",\n \"Aatami, ", "end": 5490, "score": 0.8046213388442993, "start": 5484, "tag": "NAME", "value": "Tuomas" }, { "context": "ki ja Isko\",\"Benjamin ja Kerkko\",\"Tuomas, Tuomo ja Tommi\",\"Raafael\",\"Senni\",\n \"Aatami, Eeva, Eevi ja Ev", "end": 5506, "score": 0.6691064834594727, "start": 5501, "tag": "NAME", "value": "Tommi" }, { "context": "o\",\"Benjamin ja Kerkko\",\"Tuomas, Tuomo ja Tommi\",\"Raafael\",\"Senni\",\n \"Aatami, Eeva, Eevi ja Eveliina\",nu", "end": 5516, "score": 0.9632647633552551, "start": 5509, "tag": "NAME", "value": "Raafael" }, { "context": "in ja Kerkko\",\"Tuomas, Tuomo ja Tommi\",\"Raafael\",\"Senni\",\n \"Aatami, Eeva, Eevi ja Eveliina\",null,\"Tapa", "end": 5524, "score": 0.6004043817520142, "start": 5519, "tag": "NAME", "value": "Senni" }, { "context": ",\"Tuomas, Tuomo ja Tommi\",\"Raafael\",\"Senni\",\n \"Aatami, Eeva, Eevi ja Eveliina\",null,\"Tapani ja Tep", "end": 5533, "score": 0.6204560399055481, "start": 5532, "tag": "NAME", "value": "A" }, { "context": ", Eeva, Eevi ja Eveliina\",null,\"Tapani ja Teppo\",\"Hannu ja Hannes\",\"Piia\",\"Rauha\",\"Daavid, Taavetti ja T", "end": 5592, "score": 0.8151229619979858, "start": 5588, "tag": "NAME", "value": "Hann" }, { "context": "vi ja Eveliina\",null,\"Tapani ja Teppo\",\"Hannu ja Hannes\",\"Piia\",\"Rauha\",\"Daavid, Taavetti ja Taavi\",\"Sylv", "end": 5603, "score": 0.7969545125961304, "start": 5598, "tag": "NAME", "value": "annes" }, { "context": "eliina\",null,\"Tapani ja Teppo\",\"Hannu ja Hannes\",\"Piia\",\"Rauha\",\"Daavid, Taavetti ja Taavi\",\"Sylvester j", "end": 5610, "score": 0.9790107011795044, "start": 5606, "tag": "NAME", "value": "Piia" }, { "context": ",null,\"Tapani ja Teppo\",\"Hannu ja Hannes\",\"Piia\",\"Rauha\",\"Daavid, Taavetti ja Taavi\",\"Sylvester ja Silvo\"", "end": 5618, "score": 0.9225689768791199, "start": 5613, "tag": "NAME", "value": "Rauha" }, { "context": "apani ja Teppo\",\"Hannu ja Hannes\",\"Piia\",\"Rauha\",\"Daavid, Taavetti ja Taavi\",\"Sylvester ja Silvo\"]\n ]", "end": 5623, "score": 0.8455916047096252, "start": 5621, "tag": "NAME", "value": "Da" } ]
homedisplay/display/static/js/namedays.coffee
ojarva/home-info-display
1
Namedays = -> data = [ [null,"Aapeli","Elmo ja Elmer","Ruut","Lea ja Leea","Harri","Aukusti, Aku","Hilppa ja Titta","Veikko, Veli ja Veijo","Nyyrikki","Kari ja Karri","Toini","Nuutti","Sakari ja Saku","Solja", "Ilmari ja Ilmo","Toni ja Anttoni","Laura","Heikki ja Henrik","Henna ja Henni","Aune ja Oona","Visa","Eine, Eini ja Enni","Senja","Paavo ja Pauli","Joonatan","Viljo","Kaarlo ja Kalle", "Valtteri","Irja","Alli"], ["Riitta","Aamu","Valo","Armi","Asser","Terhi, Teija ja Tiia","Riku ja Rikhard","Laina","Raija ja Raisa","Elina ja Elna","Talvikki","Elma ja Elmi","Sulo ja Sulho","Voitto","Sipi ja Sippo","Kai", "Väinö ja Väinämö","Kaino","Eija","Heli ja Helinä","Keijo","Tuulikki ja Tuuli","Aslak","Matti ja Mattias","Tuija ja Tuire","Nestori","Torsti","Onni"], ["Alpo, Alvi, Alpi","Virve ja Virva","Kauko","Ari, Arsi ja Atro","Laila ja Leila","Tarmo","Tarja ja Taru","Vilppu","Auvo","Aurora, Aura ja Auri","Kalervo","Reijo ja Reko","Erno ja Tarvo", "Matilda ja Tilda","Risto","Ilkka","Kerttu ja Kerttuli","Eetu ja Edvard","Jooseppi ja Juuso","Aki, Joakim ja Kim","Pentti","Vihtori","Akseli","Kaapo ja Gabriel","Aija","Manu ja Immanuel", "Sauli ja Saul","Armas","Joonas, Jouni ja Joni","Usko ja Tage","Irma ja Irmeli"], ["Raita ja Pulmu","Pellervo","Sampo","Ukko","Irene ja Irina","Vilho ja Ville","Allan ja Ahvo","Suoma ja Suometar","Elias ja Eelis","Tero","Verna","Julius ja Julia","Tellervo","Taito", "Linda ja Tuomi","Jalo ja Patrik","Otto","Valto ja Valdemar","Päivi ja Pilvi","Lauha","Anssi ja Anselmi","Alina","Yrjö, Jyrki ja Jyri","Pertti ja Albert","Markku, Markus ja Marko", "Terttu ja Teresa","Merja","Ilpo ja Ilppo","Teijo","Mirja, Mirva, Mira ja Miia"], ["Vappu ja Valpuri","Vuokko ja Viivi","Outi","Ruusu ja Roosa","Maini","Ylermi","Helmi ja Kastehelmi","Heino","Timo","Aino, Aina ja Aini","Osmo","Lotta","Kukka ja Floora","Tuula", "Sofia ja Sonja","Esteri ja Essi","Maila ja Maili","Erkki ja Eero","Emilia, Milja ja Emma","Lilja ja Karoliina","Kosti ja Kosta","Hemminki ja Hemmo","Lyydia ja Lyyli","Tuukka ja Touko", "Urpo","Minna ja Vilma","Ritva","Alma","Oiva ja Oivi","Pasi","Helka ja Helga"], ["Teemu ja Nikodemus","Venla","Orvokki","Toivo","Sulevi","Kustaa ja Kyösti","Suvi","Salomo ja Salomon","Ensio","Seppo","Impi ja Immi","Esko","Raili ja Raila","Kielo","Vieno ja Viena", "Päivi ja Päivikki ja Päivä","Urho","Tapio","Siiri","Into","Ahti ja Ahto","Paula, Liina ja Pauliina","Aatto, Aatu ja Aadolf","Johannes, Juhani ja Juha","Uuno","Jorma, Jarmo ja Jarkko", "Elviira ja Elvi","Leo","Pietari, Pekka, Petri ja Petra","Päiviö ja Päivö"], ["Aaro ja Aaron","Maria, Mari, Maija, Meeri ja Maaria","Arvo","Ulla ja Upu","Unto ja Untamo","Esa ja Esaias","Klaus ja Launo","Turo ja Turkka","Ilta ja Jasmin","Saima ja Saimi", "Elli, Noora ja Nelli","Hermanni, Herkko","Ilari, Lari ja Joel","Aliisa","Rauni ja Rauna","Reino","Ossi ja Ossian","Riikka","Saara, Sari, Salli ja Salla","Marketta, Maarit ja Reeta", "Johanna, Hanna ja Jenni","Leena, Leeni ja Lenita","Oili ja Olga","Kirsti, Tiina, Kirsi ja Kristiina","Jaakko ja Jaakoppi","Martta","Heidi","Atso","Olavi, Olli, Uolevi ja Uoti","Asta", "Helena ja Elena"], ["Maire","Kimmo","Linnea, Nea ja Vanamo","Veera","Salme ja Sanelma","Toimi ja Keimo","Lahja","Sylvi, Sylvia ja Silva","Erja ja Eira","Lauri, Lasse ja Lassi","Sanna, Susanna ja Sanni","Klaara", "Jesse","Onerva ja Kanerva","Marjatta, Marja ja Jaana","Aulis","Verneri","Leevi","Mauno ja Maunu","Samuli, Sami, Samuel ja Samu","Soini ja Veini","Iivari ja Iivo","Varma ja Signe","Perttu", "Loviisa","Ilma, Ilmi ja Ilmatar","Rauli","Tauno","Iines, Iina ja Inari","Eemil ja Eemeli","Arvi"], ["Pirkka","Sinikka ja Sini","Soili, Soile ja Soila","Ansa","Mainio","Asko","Arho ja Arhippa","Taimi","Eevert ja Isto","Kalevi ja Kaleva","Santeri, Ali, Ale ja Aleksanteri","Valma ja Vilja ", "Orvo","Iida","Sirpa","Hellevi, Hillevi, Hille ja Hilla","Aili ja Aila","Tyyne, Tytti ja Tyyni","Reija","Varpu ja Vaula","Mervi","Mauri","Mielikki","Alvar ja Auno","Kullervo","Kuisma","Vesa", "Arja","Mikko, Mika, Mikael, Miika","Sorja ja Sirja"], ["Rauno, Rainer, Raine ja Raino","Valio","Raimo","Saila ja Saija","Inkeri ja Inka","Minttu ja Pinja","Pirkko, Pirjo, Piritta ja Pirita","Hilja","Ilona","Aleksi ja Aleksis","Otso ja Ohto", "Aarre ja Aarto","Taina, Tanja ja Taija","Elsa, Else ja Elsi","Helvi ja Heta","Sirkka ja Sirkku","Saini ja Saana","Satu ja Säde","Uljas","Kauno ja Kasperi","Ursula", "Anja, Anita, Anniina ja Anitta","Severi","Asmo","Sointu","Amanda ja Niina, Manta","Helli, Hellä, Hellin ja Helle","Simo","Alfred ja Urmas","Eila","Artturi, Arto ja Arttu"], ["Pyry ja Lyly","Topi ja Topias","Terho","Hertta","Reima","Kustaa Aadolf","Taisto","Aatos","Teuvo","Martti","Panu","Virpi","Ano ja Kristian","Iiris","Janika, Janita ja Janina", "Aarne ja Aarno, Aarni","Eino ja Einar","Tenho ja Jousia","Liisa, Eliisa, Elisa ja Elisabet","Jalmari ja Jari","Hilma","Silja ja Selja","Ismo","Lempi, Lemmikki ja Sivi", "Katri, Kaisa, Kaija ja Katja","Sisko","Hilkka","Heini","Aimo","Antti, Antero ja Atte"], ["Oskari","Anelma ja Unelma","Vellamo ja Meri","Airi ja Aira","Selma","Niilo, Niko ja Niklas","Sampsa","Kyllikki ja Kylli","Anna, Anne, Anni, Anu ja Annikki","Jutta","Taneli, Tatu ja Daniel", "Tuovi","Seija","Jouko","Heimo","Auli ja Aulikki","Raakel","Aapo, Aappo ja Rami","Iikka, Iiro, Iisakki ja Isko","Benjamin ja Kerkko","Tuomas, Tuomo ja Tommi","Raafael","Senni", "Aatami, Eeva, Eevi ja Eveliina",null,"Tapani ja Teppo","Hannu ja Hannes","Piia","Rauha","Daavid, Taavetti ja Taavi","Sylvester ja Silvo"] ] clearItems = -> jq("#namedays-modal ul li").remove() addItems = -> clearItems() now = clock.getMoment() current_index = 0 items_in_current = 1000 for [0..365] day = now.date() - 1 month = now.month() if items_in_current > 45 current_elem = jq("#namedays-modal ul").slice current_index, current_index + 1 items_in_current = 0 current_index++ if data[month].length == day # 29th of Feb else current_elem.append "<li>#{data[month][day]} " + now.format("DD.MM (dd)") + "</li>" items_in_current += 1 now.add 1, "day" update = -> debug.log "Updating namedays" addItems() d = clock.getMoment() nameday = data[d.month()][d.date() - 1] jq("#today .list-namedays ul li").remove() jq("#today .list-namedays ul").append "<li><i class='fa-li fa fa-calendar'></i> #{nameday}</li>" startInterval = -> update() ge_refresh.register "namedays", update ge_intervals.register "namedays", "daily", update stopInterval = -> ge_refresh.deRegister "namedays" ge_intervals.deRegister "namedays", "daily" @update = update @startInterval = startInterval @stopInterval = stopInterval return @ jq => @name_days = new Namedays() @name_days.startInterval() jq(".list-namedays").on "click", -> content_switch.switchContent "#namedays-modal" jq("#namedays-modal .close").on "click", -> content_switch.switchContent "#main-content"
209900
Namedays = -> data = [ [null,"Aapeli","Elmo ja Elmer","Ruut","Lea ja Leea","<NAME>","Aukusti, Aku","Hilppa ja Titta","Veikko, Veli ja Veijo","Nyyrikki","Kari ja Karri","Toini","Nuutti","Sakari ja Saku","Solja", "Ilmari ja Ilmo","Toni ja Anttoni","Laura","Heikki ja <NAME>","<NAME> ja <NAME>","Aune ja Oona","Visa","Eine, Eini ja Enni","Senja","Paavo ja Pauli","Joonatan","Viljo","Kaarlo ja Kalle", "Valtteri","Irja","Alli"], ["Riitta","Aamu","Valo","<NAME>","<NAME>er","Terhi, Teija ja Tiia","Riku ja Rikhard","Laina","Raija ja Raisa","Elina ja Elna","Talvikki","Elma ja Elmi","Sulo ja Sulho","Voitto","Sipi ja Sippo","Kai", "Väinö ja Väinämö","Kaino","Eija","Heli ja Helinä","Keijo","Tuulikki ja Tuuli","Aslak","Matti ja Mattias","Tuija ja Tuire","Nestori","Torsti","Onni"], ["Alpo, Alvi, Alpi","Virve ja Virva","Kauko","Ari, Arsi ja Atro","Laila ja Leila","<NAME>mo","Tarja ja Taru","Vilppu","Auvo","Aurora, Aura ja Auri","Kalervo","Reijo ja Reko","Erno ja Tarvo", "Matilda ja Tilda","Risto","Ilkka","Kerttu ja Kerttuli","Eetu ja Edvard","Jooseppi ja Juuso","Aki, Joakim ja Kim","Pentti","Vihtori","Akseli","Kaapo ja <NAME>riel","Aija","Manu ja Immanuel", "Sauli ja Saul","<NAME>","Joonas, Jouni ja Joni","Usko ja Tage","Irma ja Irmeli"], ["Raita ja Pulmu","Pellervo","Sampo","Ukko","Irene ja Irina","Vilho ja Ville","Allan ja Ahvo","Suoma ja Suometar","Elias ja Eelis","Tero","<NAME>erna","<NAME> ja <NAME>","<NAME>vo","Taito", "Linda ja Tuomi","Jalo ja <NAME>rik","<NAME>to","<NAME>to ja <NAME>demar","Päivi ja Pilvi","Lauha","Anssi ja Anselmi","Alina","Yrjö, Jyrki ja Jyri","Pertti ja Albert","Markku, Markus ja Marko", "Terttu ja Teresa","<NAME>ja","Ilpo ja Ilppo","Teijo","Mirja, Mirva, Mira ja Miia"], ["Vappu ja Valpuri","Vuokko ja Viivi","Outi","Ruusu ja Roosa","Maini","Ylermi","Helmi ja Kastehelmi","<NAME>ino","Timo","Aino, Aina ja Aini","Osmo","Lotta","Kukka ja Floora","Tuula", "Sofia ja Sonja","Esteri ja Essi","Maila ja Maili","Erkki ja Eero","Emilia, Milja ja Emma","Lilja ja Karoliina","Kosti ja Kosta","Hemminki ja Hemmo","Lyydia ja Lyyli","Tuukka ja Touko", "Urpo","Minna ja Vilma","Ritva","Alma","Oiva ja Oivi","Pasi","Helka ja Helga"], ["Teemu ja Nikodemus","Venla","Orvokki","Toivo","Sulevi","Kustaa ja Kyösti","Suvi","Salomo ja Salomon","Ensio","Seppo","Impi ja Immi","Esko","Raili ja Raila","Kielo","Vieno ja Viena", "Päivi ja Päivikki ja Päivä","Urho","Tapio","Siiri","Into","Ahti ja Ahto","Paula, Liina ja Pauliina","<NAME>atto, Aatu ja <NAME>olf","Johannes, Juhani ja Juha","Uuno","Jorma, Jarmo ja Jarkko", "Elviira ja Elvi","Leo","Pietari, Pekka, Petri ja Petra","Päiviö ja Päivö"], ["<NAME> ja <NAME>","<NAME>, Mari, Maija, Meeri ja Maaria","<NAME>","Ulla ja Upu","Unto ja Untamo","Esa ja Esaias","Klaus ja Launo","Turo ja Turkka","Ilta ja Jasmin","Saima ja Saimi", "<NAME>li, Noora ja Nelli","<NAME>i, Herkko","Ilari, Lari ja Joel","Aliisa","Rauni ja Rauna","Reino","Ossi ja Ossian","Riikka","Saara, Sari, Salli ja Salla","Marketta, Maarit ja Reeta", "<NAME>, <NAME> ja <NAME>","<NAME>ena, Leeni ja Lenita","Oili ja Olga","<NAME>i, Ti<NAME>, <NAME>irsi ja <NAME>iina","Jaakko ja Jaakoppi","<NAME>","Heidi","Atso","<NAME>avi, Olli, Uolevi ja Uoti","Asta", "<NAME>ena ja E<NAME>a"], ["<NAME>","<NAME>","<NAME>, Nea ja <NAME>","Veera","Salme ja Sanelma","Toimi ja Keimo","Lahja","Sylvi, Sylvia ja Silva","Erja ja Eira","Lauri, Lasse ja Lassi","Sanna, Susanna ja Sanni","Klaara", "<NAME>esse","Onerva ja Kanerva","Marjatta, Marja ja Jaana","<NAME>","<NAME>i","Leevi","Mauno ja Maunu","Samuli, Sami, Samuel ja Samu","Soini ja Veini","Iivari ja Iivo","Varma ja Signe","Perttu", "Loviisa","Ilma, Ilmi ja Ilmatar","<NAME>uli","<NAME>uno","<NAME>ines, Iina ja Inari","Eemil ja Eemeli","Arvi"], ["Pirkka","Sinikka ja Sini","Soili, Soile ja Soila","<NAME>sa","<NAME>io","<NAME>ko","Arho ja Arhippa","Taimi","Eevert ja Isto","Kalevi ja Kaleva","Santeri, Ali, Ale ja Aleksanteri","Valma ja Vilja ", "Orvo","Iida","Sirpa","Hellevi, Hillevi, Hille ja Hilla","Aili ja Aila","Tyyne, Tytti ja Tyyni","Reija","Varpu ja Vaula","Mervi","Mauri","Mielikki","Alvar ja Auno","Kullervo","Kuisma","Vesa", "Arja","Mikko, Mika, Mikael, Miika","Sorja ja Sirja"], ["<NAME>, <NAME>, <NAME>aine ja <NAME>o","<NAME>","Raimo","Saila ja Saija","Inkeri ja Inka","Minttu ja Pinja","Pirkko, Pirjo, Piritta ja Pirita","Hilja","Ilona","Aleksi ja Aleksis","Otso ja Ohto", "Aarre ja Aarto","Taina, Tanja ja Taija","Elsa, Else ja Elsi","Helvi ja Heta","Sirkka ja Sirkku","Saini ja Saana","Satu ja Säde","Uljas","Kauno ja Kasperi","Ursula", "Anja, Anita, Anniina ja Anitta","<NAME>veri","Asmo","Sointu","Amanda ja Niina, Manta","<NAME>li, Hellä, Hellin ja Helle","Simo","Alfred ja Urmas","Eila","Artturi, Arto ja Arttu"], ["<NAME> ja <NAME>yly","Topi ja Topias","<NAME>ho","<NAME>","Reima","<NAME>ustaa A<NAME>olf","Taisto","Aatos","Teuvo","Martti","Panu","Virpi","Ano ja Kristian","Iiris","Janika, Janita ja Janina", "Aarne ja Aarno, Aarni","Eino ja E<NAME>","Tenho ja Jousia","Liisa, Eliisa, Elisa ja Elisabet","Jalmari ja Jari","Hilma","Silja ja Selja","Ismo","Lempi, Lemmikki ja Sivi", "Katri, Kaisa, Kaija ja Katja","<NAME>ko","<NAME>","<NAME>","<NAME>","Antti, Antero ja Atte"], ["Oskari","Anelma ja Unelma","Vellamo ja Meri","Airi ja Aira","Selma","Niilo, Niko ja Niklas","Sampsa","Kyllikki ja Kylli","Anna, Anne, Anni, Anu ja Annikki","Jutta","Taneli, Tatu ja Daniel", "Tuovi","Seija","Jouko","<NAME>imo","Auli ja Aulikki","<NAME>akel","<NAME>apo, Aappo ja <NAME>ami","Iikka, Iiro, Iisakki ja Isko","<NAME> ja Ker<NAME>ko","<NAME>, Tuomo ja <NAME>","<NAME>","<NAME>", "<NAME>atami, Eeva, Eevi ja Eveliina",null,"Tapani ja Teppo","<NAME>u ja H<NAME>","<NAME>","<NAME>","<NAME>avid, Taavetti ja Taavi","Sylvester ja Silvo"] ] clearItems = -> jq("#namedays-modal ul li").remove() addItems = -> clearItems() now = clock.getMoment() current_index = 0 items_in_current = 1000 for [0..365] day = now.date() - 1 month = now.month() if items_in_current > 45 current_elem = jq("#namedays-modal ul").slice current_index, current_index + 1 items_in_current = 0 current_index++ if data[month].length == day # 29th of Feb else current_elem.append "<li>#{data[month][day]} " + now.format("DD.MM (dd)") + "</li>" items_in_current += 1 now.add 1, "day" update = -> debug.log "Updating namedays" addItems() d = clock.getMoment() nameday = data[d.month()][d.date() - 1] jq("#today .list-namedays ul li").remove() jq("#today .list-namedays ul").append "<li><i class='fa-li fa fa-calendar'></i> #{nameday}</li>" startInterval = -> update() ge_refresh.register "namedays", update ge_intervals.register "namedays", "daily", update stopInterval = -> ge_refresh.deRegister "namedays" ge_intervals.deRegister "namedays", "daily" @update = update @startInterval = startInterval @stopInterval = stopInterval return @ jq => @name_days = new Namedays() @name_days.startInterval() jq(".list-namedays").on "click", -> content_switch.switchContent "#namedays-modal" jq("#namedays-modal .close").on "click", -> content_switch.switchContent "#main-content"
true
Namedays = -> data = [ [null,"Aapeli","Elmo ja Elmer","Ruut","Lea ja Leea","PI:NAME:<NAME>END_PI","Aukusti, Aku","Hilppa ja Titta","Veikko, Veli ja Veijo","Nyyrikki","Kari ja Karri","Toini","Nuutti","Sakari ja Saku","Solja", "Ilmari ja Ilmo","Toni ja Anttoni","Laura","Heikki ja PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI ja PI:NAME:<NAME>END_PI","Aune ja Oona","Visa","Eine, Eini ja Enni","Senja","Paavo ja Pauli","Joonatan","Viljo","Kaarlo ja Kalle", "Valtteri","Irja","Alli"], ["Riitta","Aamu","Valo","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIer","Terhi, Teija ja Tiia","Riku ja Rikhard","Laina","Raija ja Raisa","Elina ja Elna","Talvikki","Elma ja Elmi","Sulo ja Sulho","Voitto","Sipi ja Sippo","Kai", "Väinö ja Väinämö","Kaino","Eija","Heli ja Helinä","Keijo","Tuulikki ja Tuuli","Aslak","Matti ja Mattias","Tuija ja Tuire","Nestori","Torsti","Onni"], ["Alpo, Alvi, Alpi","Virve ja Virva","Kauko","Ari, Arsi ja Atro","Laila ja Leila","PI:NAME:<NAME>END_PImo","Tarja ja Taru","Vilppu","Auvo","Aurora, Aura ja Auri","Kalervo","Reijo ja Reko","Erno ja Tarvo", "Matilda ja Tilda","Risto","Ilkka","Kerttu ja Kerttuli","Eetu ja Edvard","Jooseppi ja Juuso","Aki, Joakim ja Kim","Pentti","Vihtori","Akseli","Kaapo ja PI:NAME:<NAME>END_PIriel","Aija","Manu ja Immanuel", "Sauli ja Saul","PI:NAME:<NAME>END_PI","Joonas, Jouni ja Joni","Usko ja Tage","Irma ja Irmeli"], ["Raita ja Pulmu","Pellervo","Sampo","Ukko","Irene ja Irina","Vilho ja Ville","Allan ja Ahvo","Suoma ja Suometar","Elias ja Eelis","Tero","PI:NAME:<NAME>END_PIerna","PI:NAME:<NAME>END_PI ja PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIvo","Taito", "Linda ja Tuomi","Jalo ja PI:NAME:<NAME>END_PIrik","PI:NAME:<NAME>END_PIto","PI:NAME:<NAME>END_PIto ja PI:NAME:<NAME>END_PIdemar","Päivi ja Pilvi","Lauha","Anssi ja Anselmi","Alina","Yrjö, Jyrki ja Jyri","Pertti ja Albert","Markku, Markus ja Marko", "Terttu ja Teresa","PI:NAME:<NAME>END_PIja","Ilpo ja Ilppo","Teijo","Mirja, Mirva, Mira ja Miia"], ["Vappu ja Valpuri","Vuokko ja Viivi","Outi","Ruusu ja Roosa","Maini","Ylermi","Helmi ja Kastehelmi","PI:NAME:<NAME>END_PIino","Timo","Aino, Aina ja Aini","Osmo","Lotta","Kukka ja Floora","Tuula", "Sofia ja Sonja","Esteri ja Essi","Maila ja Maili","Erkki ja Eero","Emilia, Milja ja Emma","Lilja ja Karoliina","Kosti ja Kosta","Hemminki ja Hemmo","Lyydia ja Lyyli","Tuukka ja Touko", "Urpo","Minna ja Vilma","Ritva","Alma","Oiva ja Oivi","Pasi","Helka ja Helga"], ["Teemu ja Nikodemus","Venla","Orvokki","Toivo","Sulevi","Kustaa ja Kyösti","Suvi","Salomo ja Salomon","Ensio","Seppo","Impi ja Immi","Esko","Raili ja Raila","Kielo","Vieno ja Viena", "Päivi ja Päivikki ja Päivä","Urho","Tapio","Siiri","Into","Ahti ja Ahto","Paula, Liina ja Pauliina","PI:NAME:<NAME>END_PIatto, Aatu ja PI:NAME:<NAME>END_PIolf","Johannes, Juhani ja Juha","Uuno","Jorma, Jarmo ja Jarkko", "Elviira ja Elvi","Leo","Pietari, Pekka, Petri ja Petra","Päiviö ja Päivö"], ["PI:NAME:<NAME>END_PI ja PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI, Mari, Maija, Meeri ja Maaria","PI:NAME:<NAME>END_PI","Ulla ja Upu","Unto ja Untamo","Esa ja Esaias","Klaus ja Launo","Turo ja Turkka","Ilta ja Jasmin","Saima ja Saimi", "PI:NAME:<NAME>END_PIli, Noora ja Nelli","PI:NAME:<NAME>END_PIi, Herkko","Ilari, Lari ja Joel","Aliisa","Rauni ja Rauna","Reino","Ossi ja Ossian","Riikka","Saara, Sari, Salli ja Salla","Marketta, Maarit ja Reeta", "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ja PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIena, Leeni ja Lenita","Oili ja Olga","PI:NAME:<NAME>END_PIi, TiPI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PIirsi ja PI:NAME:<NAME>END_PIiina","Jaakko ja Jaakoppi","PI:NAME:<NAME>END_PI","Heidi","Atso","PI:NAME:<NAME>END_PIavi, Olli, Uolevi ja Uoti","Asta", "PI:NAME:<NAME>END_PIena ja EPI:NAME:<NAME>END_PIa"], ["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI, Nea ja PI:NAME:<NAME>END_PI","Veera","Salme ja Sanelma","Toimi ja Keimo","Lahja","Sylvi, Sylvia ja Silva","Erja ja Eira","Lauri, Lasse ja Lassi","Sanna, Susanna ja Sanni","Klaara", "PI:NAME:<NAME>END_PIesse","Onerva ja Kanerva","Marjatta, Marja ja Jaana","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIi","Leevi","Mauno ja Maunu","Samuli, Sami, Samuel ja Samu","Soini ja Veini","Iivari ja Iivo","Varma ja Signe","Perttu", "Loviisa","Ilma, Ilmi ja Ilmatar","PI:NAME:<NAME>END_PIuli","PI:NAME:<NAME>END_PIuno","PI:NAME:<NAME>END_PIines, Iina ja Inari","Eemil ja Eemeli","Arvi"], ["Pirkka","Sinikka ja Sini","Soili, Soile ja Soila","PI:NAME:<NAME>END_PIsa","PI:NAME:<NAME>END_PIio","PI:NAME:<NAME>END_PIko","Arho ja Arhippa","Taimi","Eevert ja Isto","Kalevi ja Kaleva","Santeri, Ali, Ale ja Aleksanteri","Valma ja Vilja ", "Orvo","Iida","Sirpa","Hellevi, Hillevi, Hille ja Hilla","Aili ja Aila","Tyyne, Tytti ja Tyyni","Reija","Varpu ja Vaula","Mervi","Mauri","Mielikki","Alvar ja Auno","Kullervo","Kuisma","Vesa", "Arja","Mikko, Mika, Mikael, Miika","Sorja ja Sirja"], ["PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PIaine ja PI:NAME:<NAME>END_PIo","PI:NAME:<NAME>END_PI","Raimo","Saila ja Saija","Inkeri ja Inka","Minttu ja Pinja","Pirkko, Pirjo, Piritta ja Pirita","Hilja","Ilona","Aleksi ja Aleksis","Otso ja Ohto", "Aarre ja Aarto","Taina, Tanja ja Taija","Elsa, Else ja Elsi","Helvi ja Heta","Sirkka ja Sirkku","Saini ja Saana","Satu ja Säde","Uljas","Kauno ja Kasperi","Ursula", "Anja, Anita, Anniina ja Anitta","PI:NAME:<NAME>END_PIveri","Asmo","Sointu","Amanda ja Niina, Manta","PI:NAME:<NAME>END_PIli, Hellä, Hellin ja Helle","Simo","Alfred ja Urmas","Eila","Artturi, Arto ja Arttu"], ["PI:NAME:<NAME>END_PI ja PI:NAME:<NAME>END_PIyly","Topi ja Topias","PI:NAME:<NAME>END_PIho","PI:NAME:<NAME>END_PI","Reima","PI:NAME:<NAME>END_PIustaa API:NAME:<NAME>END_PIolf","Taisto","Aatos","Teuvo","Martti","Panu","Virpi","Ano ja Kristian","Iiris","Janika, Janita ja Janina", "Aarne ja Aarno, Aarni","Eino ja EPI:NAME:<NAME>END_PI","Tenho ja Jousia","Liisa, Eliisa, Elisa ja Elisabet","Jalmari ja Jari","Hilma","Silja ja Selja","Ismo","Lempi, Lemmikki ja Sivi", "Katri, Kaisa, Kaija ja Katja","PI:NAME:<NAME>END_PIko","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Antti, Antero ja Atte"], ["Oskari","Anelma ja Unelma","Vellamo ja Meri","Airi ja Aira","Selma","Niilo, Niko ja Niklas","Sampsa","Kyllikki ja Kylli","Anna, Anne, Anni, Anu ja Annikki","Jutta","Taneli, Tatu ja Daniel", "Tuovi","Seija","Jouko","PI:NAME:<NAME>END_PIimo","Auli ja Aulikki","PI:NAME:<NAME>END_PIakel","PI:NAME:<NAME>END_PIapo, Aappo ja PI:NAME:<NAME>END_PIami","Iikka, Iiro, Iisakki ja Isko","PI:NAME:<NAME>END_PI ja KerPI:NAME:<NAME>END_PIko","PI:NAME:<NAME>END_PI, Tuomo ja PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PIatami, Eeva, Eevi ja Eveliina",null,"Tapani ja Teppo","PI:NAME:<NAME>END_PIu ja HPI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIavid, Taavetti ja Taavi","Sylvester ja Silvo"] ] clearItems = -> jq("#namedays-modal ul li").remove() addItems = -> clearItems() now = clock.getMoment() current_index = 0 items_in_current = 1000 for [0..365] day = now.date() - 1 month = now.month() if items_in_current > 45 current_elem = jq("#namedays-modal ul").slice current_index, current_index + 1 items_in_current = 0 current_index++ if data[month].length == day # 29th of Feb else current_elem.append "<li>#{data[month][day]} " + now.format("DD.MM (dd)") + "</li>" items_in_current += 1 now.add 1, "day" update = -> debug.log "Updating namedays" addItems() d = clock.getMoment() nameday = data[d.month()][d.date() - 1] jq("#today .list-namedays ul li").remove() jq("#today .list-namedays ul").append "<li><i class='fa-li fa fa-calendar'></i> #{nameday}</li>" startInterval = -> update() ge_refresh.register "namedays", update ge_intervals.register "namedays", "daily", update stopInterval = -> ge_refresh.deRegister "namedays" ge_intervals.deRegister "namedays", "daily" @update = update @startInterval = startInterval @stopInterval = stopInterval return @ jq => @name_days = new Namedays() @name_days.startInterval() jq(".list-namedays").on "click", -> content_switch.switchContent "#namedays-modal" jq("#namedays-modal .close").on "click", -> content_switch.switchContent "#main-content"
[ { "context": "er for Zen Photon Garden.\n#\n# Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org>\n#\n# Permission is hereby g", "end": 557, "score": 0.9998797178268433, "start": 536, "tag": "NAME", "value": "Micah Elizabeth Scott" }, { "context": ".\n#\n# Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org>\n#\n# Permission is hereby granted, free of char", "end": 577, "score": 0.9999319314956665, "start": 559, "tag": "EMAIL", "value": "micah@scanlime.org" }, { "context": " path.basename filename, '.json'\n obj.key = jobName + '/' + obj.hash\n\n # Examine the frames we", "end": 5132, "score": 0.6432123184204102, "start": 5125, "tag": "KEY", "value": "jobName" }, { "context": " OutputKey: obj.key + '-' + pad(i, 4) + '.png'\n OutputQueueUrl: obj.resultQu", "end": 6564, "score": 0.6965252161026001, "start": 6559, "tag": "KEY", "value": "'.png" } ]
example /hqz/queue-submit.coffee
amane312/photon_generator
0
#!/usr/bin/env coffee # # Job Submitter. Uploads the JSON scene description for a job # and enqueues a work item for each frame. # # AWS configuration comes from the environment: # # AWS_ACCESS_KEY_ID # AWS_SECRET_ACCESS_KEY # AWS_REGION # HQZ_BUCKET # # Required Node modules: # # npm install aws-sdk coffee-script async clarinet # ###################################################################### # # This file is part of HQZ, the batch renderer for Zen Photon Garden. # # Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # AWS = require 'aws-sdk' async = require 'async' util = require 'util' fs = require 'fs' crypto = require 'crypto' zlib = require 'zlib' path = require 'path' sqs = new AWS.SQS({ apiVersion: '2012-11-05' }).client s3 = new AWS.S3({ apiVersion: '2006-03-01' }).client kRenderQueue = "zenphoton-hqz-render-queue" kResultQueue = "zenphoton-hqz-results" kBucketName = process.env.HQZ_BUCKET kChunkSizeLimit = 8 * 1024 * 1024 kConcurrentUploads = 6 kIndent = " " pad = (str, length) -> str = '' + str str = '0' + str while str.length < length return str bufferConcat = (list) -> # Just like Buffer.concat(), but compatible with older versions of node.js size = 0 for buf in list size += buf.length result = new Buffer size offset = 0 for buf in list buf.copy(result, offset) offset += buf.length return result if process.argv.length != 3 console.log "usage: queue-submit JOBNAME.json" process.exit 1 filename = process.argv[2] console.log "Reading #{filename}..." async.waterfall [ # Parallel initialization tasks (cb) -> async.parallel renderQueue: (cb) -> sqs.createQueue QueueName: kRenderQueue cb resultQueue: (cb) -> sqs.createQueue QueueName: kResultQueue cb # Truncated sha1 hash of input file hash: (cb) -> hash = crypto.createHash 'sha1' s = fs.createReadStream filename s.on 'data', (chunk) -> hash.update chunk s.on 'end', () -> h = hash.digest 'hex' console.log " sha1 #{h}" cb null, h.slice(0, 8) # Info about frames: Total number of frames, and a list of file # offsets used for reading groups of frames later. frames: (cb) -> frameOffsets = [ 0 ] offset = 0 tail = true s = fs.createReadStream filename s.on 'data', (d) -> parts = d.toString().split('\n') # If we found any newlines, record the index of the character # following the newline. This is the end of the previous frame, # or the beginning of the next. for i in [0 .. parts.length - 2] by 1 offset += parts[i].length + 1 frameOffsets.push offset last = parts[parts.length - 1] offset += last.length tail = (last == '') s.on 'end', (e) -> frames = frameOffsets.length frames-- if tail if frames.length == 1 console.log "#{kIndent}found a single frame" else console.log "#{kIndent}found animation with #{frames} frames" # frameOffsets always has a beginning and end for each frame. frameOffsets.push offset cb null, count: frames offsets: frameOffsets cb (obj, cb) -> # Create a unique identifier for this job jobName = path.basename filename, '.json' obj.key = jobName + '/' + obj.hash # Examine the frames we have to render. Generate a list of work items # and split our scene up into one or more chunks. Each chunk will have a whole # number of frames in it, and be of a bounded size. obj.work = [] obj.chunks = [] for i in [0 .. obj.frames.count - 1] # Make a new chunk if necessary chunk = obj.chunks[ obj.chunks.length - 1 ] if !chunk or chunk.dataSize > kChunkSizeLimit chunk = dataSize: 0 name: obj.key + '-' + pad(obj.chunks.length, 4) + '.json.gz' firstFrame: i lastFrame: i obj.chunks.push chunk # Add this frame to a chunk chunk.lastFrame = i chunk.dataSize += obj.frames.offsets[i + 1] - obj.frames.offsets[i] # Work item obj.work.push Id: 'item-' + i MessageBody: JSON.stringify # Metadata for queue-watcher JobKey: obj.key JobIndex: i # queue-runner parameters SceneBucket: kBucketName SceneKey: chunk.name SceneIndex: i - chunk.firstFrame OutputBucket: kBucketName OutputKey: obj.key + '-' + pad(i, 4) + '.png' OutputQueueUrl: obj.resultQueue.QueueUrl # Compress and upload all chunks uploadCounter = 0 uploadChunks = (chunk, cb) -> # Is this chunk already on S3? s3.headObject Bucket: kBucketName Key: chunk.name (error, data) -> return cb error if error and error.code != 'NotFound' # Increment the counter right before use, so counts appear in-order in the log logPrefix = () -> uploadCounter++ "#{kIndent}[#{uploadCounter} / #{obj.chunks.length}] chunk #{chunk.name}" if not error console.log "#{logPrefix()} already uploaded" return cb() # Read and gzip just this section of the file s = fs.createReadStream filename, start: obj.frames.offsets[ chunk.firstFrame ] end: obj.frames.offsets[ chunk.lastFrame + 1 ] - 1 # Store the chunks in an in-memory buffer gz = zlib.createGzip() chunks = [] s.pipe gz gz.on 'data', (chunk) -> chunks.push chunk gz.on 'end', () -> data = bufferConcat chunks s3.putObject Bucket: kBucketName ContentType: 'application/json' Key: chunk.name Body: data (error) -> console.log "#{logPrefix()} uploaded #{data.length} bytes" if !error cb error if obj.chunks.length > 1 console.log "Uploading scene data in #{obj.chunks.length} chunks..." else console.log "Uploading scene data..." async.eachLimit obj.chunks, kConcurrentUploads, uploadChunks, (error) -> return cb error if error cb null, obj # Enqueue work items (obj, cb) -> async.whilst( () -> obj.work.length > 0 (cb) -> console.log "Enqueueing work items, #{obj.work.length} remaining" batch = Math.min(10, obj.work.length) thisBatch = obj.work.slice(0, batch) obj.work = obj.work.slice(batch) sqs.sendMessageBatch QueueUrl: obj.renderQueue.QueueUrl Entries: thisBatch cb cb ) ], (error) -> return console.log util.inspect error if error console.log "Job submitted"
38204
#!/usr/bin/env coffee # # Job Submitter. Uploads the JSON scene description for a job # and enqueues a work item for each frame. # # AWS configuration comes from the environment: # # AWS_ACCESS_KEY_ID # AWS_SECRET_ACCESS_KEY # AWS_REGION # HQZ_BUCKET # # Required Node modules: # # npm install aws-sdk coffee-script async clarinet # ###################################################################### # # This file is part of HQZ, the batch renderer for Zen Photon Garden. # # Copyright (c) 2013 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. # AWS = require 'aws-sdk' async = require 'async' util = require 'util' fs = require 'fs' crypto = require 'crypto' zlib = require 'zlib' path = require 'path' sqs = new AWS.SQS({ apiVersion: '2012-11-05' }).client s3 = new AWS.S3({ apiVersion: '2006-03-01' }).client kRenderQueue = "zenphoton-hqz-render-queue" kResultQueue = "zenphoton-hqz-results" kBucketName = process.env.HQZ_BUCKET kChunkSizeLimit = 8 * 1024 * 1024 kConcurrentUploads = 6 kIndent = " " pad = (str, length) -> str = '' + str str = '0' + str while str.length < length return str bufferConcat = (list) -> # Just like Buffer.concat(), but compatible with older versions of node.js size = 0 for buf in list size += buf.length result = new Buffer size offset = 0 for buf in list buf.copy(result, offset) offset += buf.length return result if process.argv.length != 3 console.log "usage: queue-submit JOBNAME.json" process.exit 1 filename = process.argv[2] console.log "Reading #{filename}..." async.waterfall [ # Parallel initialization tasks (cb) -> async.parallel renderQueue: (cb) -> sqs.createQueue QueueName: kRenderQueue cb resultQueue: (cb) -> sqs.createQueue QueueName: kResultQueue cb # Truncated sha1 hash of input file hash: (cb) -> hash = crypto.createHash 'sha1' s = fs.createReadStream filename s.on 'data', (chunk) -> hash.update chunk s.on 'end', () -> h = hash.digest 'hex' console.log " sha1 #{h}" cb null, h.slice(0, 8) # Info about frames: Total number of frames, and a list of file # offsets used for reading groups of frames later. frames: (cb) -> frameOffsets = [ 0 ] offset = 0 tail = true s = fs.createReadStream filename s.on 'data', (d) -> parts = d.toString().split('\n') # If we found any newlines, record the index of the character # following the newline. This is the end of the previous frame, # or the beginning of the next. for i in [0 .. parts.length - 2] by 1 offset += parts[i].length + 1 frameOffsets.push offset last = parts[parts.length - 1] offset += last.length tail = (last == '') s.on 'end', (e) -> frames = frameOffsets.length frames-- if tail if frames.length == 1 console.log "#{kIndent}found a single frame" else console.log "#{kIndent}found animation with #{frames} frames" # frameOffsets always has a beginning and end for each frame. frameOffsets.push offset cb null, count: frames offsets: frameOffsets cb (obj, cb) -> # Create a unique identifier for this job jobName = path.basename filename, '.json' obj.key = <KEY> + '/' + obj.hash # Examine the frames we have to render. Generate a list of work items # and split our scene up into one or more chunks. Each chunk will have a whole # number of frames in it, and be of a bounded size. obj.work = [] obj.chunks = [] for i in [0 .. obj.frames.count - 1] # Make a new chunk if necessary chunk = obj.chunks[ obj.chunks.length - 1 ] if !chunk or chunk.dataSize > kChunkSizeLimit chunk = dataSize: 0 name: obj.key + '-' + pad(obj.chunks.length, 4) + '.json.gz' firstFrame: i lastFrame: i obj.chunks.push chunk # Add this frame to a chunk chunk.lastFrame = i chunk.dataSize += obj.frames.offsets[i + 1] - obj.frames.offsets[i] # Work item obj.work.push Id: 'item-' + i MessageBody: JSON.stringify # Metadata for queue-watcher JobKey: obj.key JobIndex: i # queue-runner parameters SceneBucket: kBucketName SceneKey: chunk.name SceneIndex: i - chunk.firstFrame OutputBucket: kBucketName OutputKey: obj.key + '-' + pad(i, 4) + <KEY>' OutputQueueUrl: obj.resultQueue.QueueUrl # Compress and upload all chunks uploadCounter = 0 uploadChunks = (chunk, cb) -> # Is this chunk already on S3? s3.headObject Bucket: kBucketName Key: chunk.name (error, data) -> return cb error if error and error.code != 'NotFound' # Increment the counter right before use, so counts appear in-order in the log logPrefix = () -> uploadCounter++ "#{kIndent}[#{uploadCounter} / #{obj.chunks.length}] chunk #{chunk.name}" if not error console.log "#{logPrefix()} already uploaded" return cb() # Read and gzip just this section of the file s = fs.createReadStream filename, start: obj.frames.offsets[ chunk.firstFrame ] end: obj.frames.offsets[ chunk.lastFrame + 1 ] - 1 # Store the chunks in an in-memory buffer gz = zlib.createGzip() chunks = [] s.pipe gz gz.on 'data', (chunk) -> chunks.push chunk gz.on 'end', () -> data = bufferConcat chunks s3.putObject Bucket: kBucketName ContentType: 'application/json' Key: chunk.name Body: data (error) -> console.log "#{logPrefix()} uploaded #{data.length} bytes" if !error cb error if obj.chunks.length > 1 console.log "Uploading scene data in #{obj.chunks.length} chunks..." else console.log "Uploading scene data..." async.eachLimit obj.chunks, kConcurrentUploads, uploadChunks, (error) -> return cb error if error cb null, obj # Enqueue work items (obj, cb) -> async.whilst( () -> obj.work.length > 0 (cb) -> console.log "Enqueueing work items, #{obj.work.length} remaining" batch = Math.min(10, obj.work.length) thisBatch = obj.work.slice(0, batch) obj.work = obj.work.slice(batch) sqs.sendMessageBatch QueueUrl: obj.renderQueue.QueueUrl Entries: thisBatch cb cb ) ], (error) -> return console.log util.inspect error if error console.log "Job submitted"
true
#!/usr/bin/env coffee # # Job Submitter. Uploads the JSON scene description for a job # and enqueues a work item for each frame. # # AWS configuration comes from the environment: # # AWS_ACCESS_KEY_ID # AWS_SECRET_ACCESS_KEY # AWS_REGION # HQZ_BUCKET # # Required Node modules: # # npm install aws-sdk coffee-script async clarinet # ###################################################################### # # This file is part of HQZ, the batch renderer for Zen Photon Garden. # # Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. # AWS = require 'aws-sdk' async = require 'async' util = require 'util' fs = require 'fs' crypto = require 'crypto' zlib = require 'zlib' path = require 'path' sqs = new AWS.SQS({ apiVersion: '2012-11-05' }).client s3 = new AWS.S3({ apiVersion: '2006-03-01' }).client kRenderQueue = "zenphoton-hqz-render-queue" kResultQueue = "zenphoton-hqz-results" kBucketName = process.env.HQZ_BUCKET kChunkSizeLimit = 8 * 1024 * 1024 kConcurrentUploads = 6 kIndent = " " pad = (str, length) -> str = '' + str str = '0' + str while str.length < length return str bufferConcat = (list) -> # Just like Buffer.concat(), but compatible with older versions of node.js size = 0 for buf in list size += buf.length result = new Buffer size offset = 0 for buf in list buf.copy(result, offset) offset += buf.length return result if process.argv.length != 3 console.log "usage: queue-submit JOBNAME.json" process.exit 1 filename = process.argv[2] console.log "Reading #{filename}..." async.waterfall [ # Parallel initialization tasks (cb) -> async.parallel renderQueue: (cb) -> sqs.createQueue QueueName: kRenderQueue cb resultQueue: (cb) -> sqs.createQueue QueueName: kResultQueue cb # Truncated sha1 hash of input file hash: (cb) -> hash = crypto.createHash 'sha1' s = fs.createReadStream filename s.on 'data', (chunk) -> hash.update chunk s.on 'end', () -> h = hash.digest 'hex' console.log " sha1 #{h}" cb null, h.slice(0, 8) # Info about frames: Total number of frames, and a list of file # offsets used for reading groups of frames later. frames: (cb) -> frameOffsets = [ 0 ] offset = 0 tail = true s = fs.createReadStream filename s.on 'data', (d) -> parts = d.toString().split('\n') # If we found any newlines, record the index of the character # following the newline. This is the end of the previous frame, # or the beginning of the next. for i in [0 .. parts.length - 2] by 1 offset += parts[i].length + 1 frameOffsets.push offset last = parts[parts.length - 1] offset += last.length tail = (last == '') s.on 'end', (e) -> frames = frameOffsets.length frames-- if tail if frames.length == 1 console.log "#{kIndent}found a single frame" else console.log "#{kIndent}found animation with #{frames} frames" # frameOffsets always has a beginning and end for each frame. frameOffsets.push offset cb null, count: frames offsets: frameOffsets cb (obj, cb) -> # Create a unique identifier for this job jobName = path.basename filename, '.json' obj.key = PI:KEY:<KEY>END_PI + '/' + obj.hash # Examine the frames we have to render. Generate a list of work items # and split our scene up into one or more chunks. Each chunk will have a whole # number of frames in it, and be of a bounded size. obj.work = [] obj.chunks = [] for i in [0 .. obj.frames.count - 1] # Make a new chunk if necessary chunk = obj.chunks[ obj.chunks.length - 1 ] if !chunk or chunk.dataSize > kChunkSizeLimit chunk = dataSize: 0 name: obj.key + '-' + pad(obj.chunks.length, 4) + '.json.gz' firstFrame: i lastFrame: i obj.chunks.push chunk # Add this frame to a chunk chunk.lastFrame = i chunk.dataSize += obj.frames.offsets[i + 1] - obj.frames.offsets[i] # Work item obj.work.push Id: 'item-' + i MessageBody: JSON.stringify # Metadata for queue-watcher JobKey: obj.key JobIndex: i # queue-runner parameters SceneBucket: kBucketName SceneKey: chunk.name SceneIndex: i - chunk.firstFrame OutputBucket: kBucketName OutputKey: obj.key + '-' + pad(i, 4) + PI:KEY:<KEY>END_PI' OutputQueueUrl: obj.resultQueue.QueueUrl # Compress and upload all chunks uploadCounter = 0 uploadChunks = (chunk, cb) -> # Is this chunk already on S3? s3.headObject Bucket: kBucketName Key: chunk.name (error, data) -> return cb error if error and error.code != 'NotFound' # Increment the counter right before use, so counts appear in-order in the log logPrefix = () -> uploadCounter++ "#{kIndent}[#{uploadCounter} / #{obj.chunks.length}] chunk #{chunk.name}" if not error console.log "#{logPrefix()} already uploaded" return cb() # Read and gzip just this section of the file s = fs.createReadStream filename, start: obj.frames.offsets[ chunk.firstFrame ] end: obj.frames.offsets[ chunk.lastFrame + 1 ] - 1 # Store the chunks in an in-memory buffer gz = zlib.createGzip() chunks = [] s.pipe gz gz.on 'data', (chunk) -> chunks.push chunk gz.on 'end', () -> data = bufferConcat chunks s3.putObject Bucket: kBucketName ContentType: 'application/json' Key: chunk.name Body: data (error) -> console.log "#{logPrefix()} uploaded #{data.length} bytes" if !error cb error if obj.chunks.length > 1 console.log "Uploading scene data in #{obj.chunks.length} chunks..." else console.log "Uploading scene data..." async.eachLimit obj.chunks, kConcurrentUploads, uploadChunks, (error) -> return cb error if error cb null, obj # Enqueue work items (obj, cb) -> async.whilst( () -> obj.work.length > 0 (cb) -> console.log "Enqueueing work items, #{obj.work.length} remaining" batch = Math.min(10, obj.work.length) thisBatch = obj.work.slice(0, batch) obj.work = obj.work.slice(batch) sqs.sendMessageBatch QueueUrl: obj.renderQueue.QueueUrl Entries: thisBatch cb cb ) ], (error) -> return console.log util.inspect error if error console.log "Job submitted"
[ { "context": " false\n @tagsFlood : null \n\n @GA_ACCOUNT : '37524215-3'\n\n @start : =>\n window._gaq = window._g", "end": 108, "score": 0.990747332572937, "start": 98, "tag": "KEY", "value": "37524215-3" } ]
project/develop/coffee/utils/Analytics.coffee
GyanaPrasannaa/oz-experiment
0
class Analytics @tags : null @started : false @tagsFlood : null @GA_ACCOUNT : '37524215-3' @start : => window._gaq = window._gaq or [['_setAccount',"UA-#{@GA_ACCOUNT}"],['_trackPageview']] @tags = JSON.parse window.oz.baseAssets.get('trackingTags').result @tagsFlood = JSON.parse window.oz.baseAssets.get('trackingTagsFloodlight').result @started = true null @track : (param, floodlight) => if !@started @start() if param tag = [] tag.push '_trackEvent' v = @tags[param] if v? for i in [0...v.length] tag.push v[i] # TODO: uncomment these lines #console.log "[Analytics]: " + tag window._gaq.push tag if floodlight @trackFloodlight floodlight null @trackFloodlight : (tag) => i = $('#floodlightTrack') i.remove() if i.length > 0 axel = Math.random() + "" a = axel * 10000000000000 cat = @tagsFlood[tag].cat iframe = $('<img id="floodlightTrack" />') iframe.attr src : "http://3944448.fls.doubleclick.net/activityi;src=3944448;type=googl379;cat=#{cat};ord=#{a}?" width : 1 height : 1 style : "visibility:hidden; position: absolute; top:0; left:0" $('body').prepend iframe null
100608
class Analytics @tags : null @started : false @tagsFlood : null @GA_ACCOUNT : '<KEY>' @start : => window._gaq = window._gaq or [['_setAccount',"UA-#{@GA_ACCOUNT}"],['_trackPageview']] @tags = JSON.parse window.oz.baseAssets.get('trackingTags').result @tagsFlood = JSON.parse window.oz.baseAssets.get('trackingTagsFloodlight').result @started = true null @track : (param, floodlight) => if !@started @start() if param tag = [] tag.push '_trackEvent' v = @tags[param] if v? for i in [0...v.length] tag.push v[i] # TODO: uncomment these lines #console.log "[Analytics]: " + tag window._gaq.push tag if floodlight @trackFloodlight floodlight null @trackFloodlight : (tag) => i = $('#floodlightTrack') i.remove() if i.length > 0 axel = Math.random() + "" a = axel * 10000000000000 cat = @tagsFlood[tag].cat iframe = $('<img id="floodlightTrack" />') iframe.attr src : "http://3944448.fls.doubleclick.net/activityi;src=3944448;type=googl379;cat=#{cat};ord=#{a}?" width : 1 height : 1 style : "visibility:hidden; position: absolute; top:0; left:0" $('body').prepend iframe null
true
class Analytics @tags : null @started : false @tagsFlood : null @GA_ACCOUNT : 'PI:KEY:<KEY>END_PI' @start : => window._gaq = window._gaq or [['_setAccount',"UA-#{@GA_ACCOUNT}"],['_trackPageview']] @tags = JSON.parse window.oz.baseAssets.get('trackingTags').result @tagsFlood = JSON.parse window.oz.baseAssets.get('trackingTagsFloodlight').result @started = true null @track : (param, floodlight) => if !@started @start() if param tag = [] tag.push '_trackEvent' v = @tags[param] if v? for i in [0...v.length] tag.push v[i] # TODO: uncomment these lines #console.log "[Analytics]: " + tag window._gaq.push tag if floodlight @trackFloodlight floodlight null @trackFloodlight : (tag) => i = $('#floodlightTrack') i.remove() if i.length > 0 axel = Math.random() + "" a = axel * 10000000000000 cat = @tagsFlood[tag].cat iframe = $('<img id="floodlightTrack" />') iframe.attr src : "http://3944448.fls.doubleclick.net/activityi;src=3944448;type=googl379;cat=#{cat};ord=#{a}?" width : 1 height : 1 style : "visibility:hidden; position: absolute; top:0; left:0" $('body').prepend iframe null
[ { "context": "ng underscores in variable declarations.\n# @author Matt DuVall <http://www.mattduvall.com>\n###\n\n'use strict'\n\n#-", "end": 102, "score": 0.999731183052063, "start": 91, "tag": "NAME", "value": "Matt DuVall" } ]
src/rules/no-underscore-dangle.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to flag trailing underscores in variable declarations. # @author Matt DuVall <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow dangling underscores in identifiers' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/no-underscore-dangle' schema: [ type: 'object' properties: allow: type: 'array' items: type: 'string' allowAfterThis: type: 'boolean' allowAfterSuper: type: 'boolean' enforceInMethodNames: type: 'boolean' additionalProperties: no ] create: (context) -> options = context.options[0] or {} ALLOWED_VARIABLES = if options.allow then options.allow else [] allowAfterThis = unless typeof options.allowAfterThis is 'undefined' options.allowAfterThis else no allowAfterSuper = unless typeof options.allowAfterSuper is 'undefined' options.allowAfterSuper else no enforceInMethodNames = unless typeof options.enforceInMethodNames is 'undefined' options.enforceInMethodNames else no #------------------------------------------------------------------------- # Helpers #------------------------------------------------------------------------- ###* # Check if identifier is present inside the allowed option # @param {string} identifier name of the node # @returns {boolean} true if its is present # @private ### isAllowed = (identifier) -> ALLOWED_VARIABLES.some (ident) -> ident is identifier ###* # Check if identifier has a underscore at the end # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is present # @private ### hasTrailingUnderscore = (identifier) -> len = identifier.length identifier isnt '_' and (identifier[0] is '_' or identifier[len - 1] is '_') ###* # Check if identifier is a special case member expression # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is a special case # @private ### isSpecialCaseIdentifierForMemberExpression = (identifier) -> identifier is '__proto__' ###* # Check if identifier is a special case variable expression # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is a special case # @private ### isSpecialCaseIdentifierInVariableExpression = (identifier) -> # Checks for the underscore library usage here identifier is '_' ###* # Check if function has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInFunctionDeclaration = (node) -> if node.id identifier = node.id.name if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } checkForTrailingUnderscoreInIdentifier = (node) -> return unless node.declaration identifier = node.name if ( hasTrailingUnderscore(identifier) and not isSpecialCaseIdentifierInVariableExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if variable expression has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInVariableExpression = (node) -> identifier = node.id.name if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not isSpecialCaseIdentifierInVariableExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if member expression has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInMemberExpression = (node) -> identifier = node.property.name isMemberOfThis = node.object.type is 'ThisExpression' isMemberOfSuper = node.object.type is 'Super' if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not (isMemberOfThis and allowAfterThis) and not (isMemberOfSuper and allowAfterSuper) and not isSpecialCaseIdentifierForMemberExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if method declaration or method property has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInMethod = (node) -> identifier = node.key.name isMethod = node.type is 'MethodDefinition' or (node.type is 'Property' and (node.method or node.value.type is 'FunctionExpression')) if ( typeof identifier isnt 'undefined' and enforceInMethodNames and isMethod and hasTrailingUnderscore identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- FunctionDeclaration: checkForTrailingUnderscoreInFunctionDeclaration VariableDeclarator: checkForTrailingUnderscoreInVariableExpression Identifier: checkForTrailingUnderscoreInIdentifier MemberExpression: checkForTrailingUnderscoreInMemberExpression MethodDefinition: checkForTrailingUnderscoreInMethod Property: checkForTrailingUnderscoreInMethod
222137
###* # @fileoverview Rule to flag trailing underscores in variable declarations. # @author <NAME> <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow dangling underscores in identifiers' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/no-underscore-dangle' schema: [ type: 'object' properties: allow: type: 'array' items: type: 'string' allowAfterThis: type: 'boolean' allowAfterSuper: type: 'boolean' enforceInMethodNames: type: 'boolean' additionalProperties: no ] create: (context) -> options = context.options[0] or {} ALLOWED_VARIABLES = if options.allow then options.allow else [] allowAfterThis = unless typeof options.allowAfterThis is 'undefined' options.allowAfterThis else no allowAfterSuper = unless typeof options.allowAfterSuper is 'undefined' options.allowAfterSuper else no enforceInMethodNames = unless typeof options.enforceInMethodNames is 'undefined' options.enforceInMethodNames else no #------------------------------------------------------------------------- # Helpers #------------------------------------------------------------------------- ###* # Check if identifier is present inside the allowed option # @param {string} identifier name of the node # @returns {boolean} true if its is present # @private ### isAllowed = (identifier) -> ALLOWED_VARIABLES.some (ident) -> ident is identifier ###* # Check if identifier has a underscore at the end # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is present # @private ### hasTrailingUnderscore = (identifier) -> len = identifier.length identifier isnt '_' and (identifier[0] is '_' or identifier[len - 1] is '_') ###* # Check if identifier is a special case member expression # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is a special case # @private ### isSpecialCaseIdentifierForMemberExpression = (identifier) -> identifier is '__proto__' ###* # Check if identifier is a special case variable expression # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is a special case # @private ### isSpecialCaseIdentifierInVariableExpression = (identifier) -> # Checks for the underscore library usage here identifier is '_' ###* # Check if function has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInFunctionDeclaration = (node) -> if node.id identifier = node.id.name if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } checkForTrailingUnderscoreInIdentifier = (node) -> return unless node.declaration identifier = node.name if ( hasTrailingUnderscore(identifier) and not isSpecialCaseIdentifierInVariableExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if variable expression has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInVariableExpression = (node) -> identifier = node.id.name if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not isSpecialCaseIdentifierInVariableExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if member expression has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInMemberExpression = (node) -> identifier = node.property.name isMemberOfThis = node.object.type is 'ThisExpression' isMemberOfSuper = node.object.type is 'Super' if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not (isMemberOfThis and allowAfterThis) and not (isMemberOfSuper and allowAfterSuper) and not isSpecialCaseIdentifierForMemberExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if method declaration or method property has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInMethod = (node) -> identifier = node.key.name isMethod = node.type is 'MethodDefinition' or (node.type is 'Property' and (node.method or node.value.type is 'FunctionExpression')) if ( typeof identifier isnt 'undefined' and enforceInMethodNames and isMethod and hasTrailingUnderscore identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- FunctionDeclaration: checkForTrailingUnderscoreInFunctionDeclaration VariableDeclarator: checkForTrailingUnderscoreInVariableExpression Identifier: checkForTrailingUnderscoreInIdentifier MemberExpression: checkForTrailingUnderscoreInMemberExpression MethodDefinition: checkForTrailingUnderscoreInMethod Property: checkForTrailingUnderscoreInMethod
true
###* # @fileoverview Rule to flag trailing underscores in variable declarations. # @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow dangling underscores in identifiers' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/no-underscore-dangle' schema: [ type: 'object' properties: allow: type: 'array' items: type: 'string' allowAfterThis: type: 'boolean' allowAfterSuper: type: 'boolean' enforceInMethodNames: type: 'boolean' additionalProperties: no ] create: (context) -> options = context.options[0] or {} ALLOWED_VARIABLES = if options.allow then options.allow else [] allowAfterThis = unless typeof options.allowAfterThis is 'undefined' options.allowAfterThis else no allowAfterSuper = unless typeof options.allowAfterSuper is 'undefined' options.allowAfterSuper else no enforceInMethodNames = unless typeof options.enforceInMethodNames is 'undefined' options.enforceInMethodNames else no #------------------------------------------------------------------------- # Helpers #------------------------------------------------------------------------- ###* # Check if identifier is present inside the allowed option # @param {string} identifier name of the node # @returns {boolean} true if its is present # @private ### isAllowed = (identifier) -> ALLOWED_VARIABLES.some (ident) -> ident is identifier ###* # Check if identifier has a underscore at the end # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is present # @private ### hasTrailingUnderscore = (identifier) -> len = identifier.length identifier isnt '_' and (identifier[0] is '_' or identifier[len - 1] is '_') ###* # Check if identifier is a special case member expression # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is a special case # @private ### isSpecialCaseIdentifierForMemberExpression = (identifier) -> identifier is '__proto__' ###* # Check if identifier is a special case variable expression # @param {ASTNode} identifier node to evaluate # @returns {boolean} true if its is a special case # @private ### isSpecialCaseIdentifierInVariableExpression = (identifier) -> # Checks for the underscore library usage here identifier is '_' ###* # Check if function has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInFunctionDeclaration = (node) -> if node.id identifier = node.id.name if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } checkForTrailingUnderscoreInIdentifier = (node) -> return unless node.declaration identifier = node.name if ( hasTrailingUnderscore(identifier) and not isSpecialCaseIdentifierInVariableExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if variable expression has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInVariableExpression = (node) -> identifier = node.id.name if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not isSpecialCaseIdentifierInVariableExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if member expression has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInMemberExpression = (node) -> identifier = node.property.name isMemberOfThis = node.object.type is 'ThisExpression' isMemberOfSuper = node.object.type is 'Super' if ( typeof identifier isnt 'undefined' and hasTrailingUnderscore(identifier) and not (isMemberOfThis and allowAfterThis) and not (isMemberOfSuper and allowAfterSuper) and not isSpecialCaseIdentifierForMemberExpression(identifier) and not isAllowed identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } ###* # Check if method declaration or method property has a underscore at the end # @param {ASTNode} node node to evaluate # @returns {void} # @private ### checkForTrailingUnderscoreInMethod = (node) -> identifier = node.key.name isMethod = node.type is 'MethodDefinition' or (node.type is 'Property' and (node.method or node.value.type is 'FunctionExpression')) if ( typeof identifier isnt 'undefined' and enforceInMethodNames and isMethod and hasTrailingUnderscore identifier ) context.report { node message: "Unexpected dangling '_' in '{{identifier}}'." data: { identifier } } #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- FunctionDeclaration: checkForTrailingUnderscoreInFunctionDeclaration VariableDeclarator: checkForTrailingUnderscoreInVariableExpression Identifier: checkForTrailingUnderscoreInIdentifier MemberExpression: checkForTrailingUnderscoreInMemberExpression MethodDefinition: checkForTrailingUnderscoreInMethod Property: checkForTrailingUnderscoreInMethod
[ { "context": "###\n(c) 2011 Jan Monschke\nv1.0\nGeoMock is licensed under the MIT license.\n#", "end": 25, "score": 0.9997203946113586, "start": 13, "tag": "NAME", "value": "Jan Monschke" } ]
geomock.coffee
MazeMap/GeoMock
1
### (c) 2011 Jan Monschke v1.0 GeoMock is licensed under the MIT license. ### do -> unless navigator? window.navigator = {} delete navigator.geolocation navigator.geolocation = delay : 1000 shouldFail : false failsAt : -1 errorMessage : "There was an error retrieving the position!" currentTimeout : -1 lastPosReturned : 0 _sanitizeLastReturned : -> if @lastPosReturned > @waypoints.length-1 @lastPosReturned = 0 _geoCall : (method, success, error) -> if @shouldFail and error? @currentTimeout = window[method].call null, => error @errorMessage , @delay else if success? @currentTimeout = window[method].call null, => success @waypoints[@lastPosReturned++] do @_sanitizeLastReturned , @delay getCurrentPosition : (success, error) -> @_geoCall "setTimeout", success, error watchPosition : (success, error) -> @_geoCall "setInterval", success, error @currentTimeout clearWatch : (id) -> clearInterval id waypoints : [ {coords : {latitude : 52.5168, longitude : 13.3889, accuracy: 1500 }}, {coords : {latitude : 52.5162, longitude : 13.3890, accuracy: 1334 }}, {coords : {latitude : 52.5154, longitude : 13.3890, accuracy: 631 }}, {coords : {latitude : 52.5150, longitude : 13.3890, accuracy: 361 }}, {coords : {latitude : 52.5144, longitude : 13.3890, accuracy: 150 }}, {coords : {latitude : 52.5138, longitude : 13.3890, accuracy: 65 }}, {coords : {latitude : 52.5138, longitude : 13.3895, accuracy: 65 }}, {coords : {latitude : 52.5139, longitude : 13.3899, accuracy: 65 }}, {coords : {latitude : 52.5140, longitude : 13.3906, accuracy: 65 }}, {coords : {latitude : 52.5140, longitude : 13.3910, accuracy: 65 }} ]
129911
### (c) 2011 <NAME> v1.0 GeoMock is licensed under the MIT license. ### do -> unless navigator? window.navigator = {} delete navigator.geolocation navigator.geolocation = delay : 1000 shouldFail : false failsAt : -1 errorMessage : "There was an error retrieving the position!" currentTimeout : -1 lastPosReturned : 0 _sanitizeLastReturned : -> if @lastPosReturned > @waypoints.length-1 @lastPosReturned = 0 _geoCall : (method, success, error) -> if @shouldFail and error? @currentTimeout = window[method].call null, => error @errorMessage , @delay else if success? @currentTimeout = window[method].call null, => success @waypoints[@lastPosReturned++] do @_sanitizeLastReturned , @delay getCurrentPosition : (success, error) -> @_geoCall "setTimeout", success, error watchPosition : (success, error) -> @_geoCall "setInterval", success, error @currentTimeout clearWatch : (id) -> clearInterval id waypoints : [ {coords : {latitude : 52.5168, longitude : 13.3889, accuracy: 1500 }}, {coords : {latitude : 52.5162, longitude : 13.3890, accuracy: 1334 }}, {coords : {latitude : 52.5154, longitude : 13.3890, accuracy: 631 }}, {coords : {latitude : 52.5150, longitude : 13.3890, accuracy: 361 }}, {coords : {latitude : 52.5144, longitude : 13.3890, accuracy: 150 }}, {coords : {latitude : 52.5138, longitude : 13.3890, accuracy: 65 }}, {coords : {latitude : 52.5138, longitude : 13.3895, accuracy: 65 }}, {coords : {latitude : 52.5139, longitude : 13.3899, accuracy: 65 }}, {coords : {latitude : 52.5140, longitude : 13.3906, accuracy: 65 }}, {coords : {latitude : 52.5140, longitude : 13.3910, accuracy: 65 }} ]
true
### (c) 2011 PI:NAME:<NAME>END_PI v1.0 GeoMock is licensed under the MIT license. ### do -> unless navigator? window.navigator = {} delete navigator.geolocation navigator.geolocation = delay : 1000 shouldFail : false failsAt : -1 errorMessage : "There was an error retrieving the position!" currentTimeout : -1 lastPosReturned : 0 _sanitizeLastReturned : -> if @lastPosReturned > @waypoints.length-1 @lastPosReturned = 0 _geoCall : (method, success, error) -> if @shouldFail and error? @currentTimeout = window[method].call null, => error @errorMessage , @delay else if success? @currentTimeout = window[method].call null, => success @waypoints[@lastPosReturned++] do @_sanitizeLastReturned , @delay getCurrentPosition : (success, error) -> @_geoCall "setTimeout", success, error watchPosition : (success, error) -> @_geoCall "setInterval", success, error @currentTimeout clearWatch : (id) -> clearInterval id waypoints : [ {coords : {latitude : 52.5168, longitude : 13.3889, accuracy: 1500 }}, {coords : {latitude : 52.5162, longitude : 13.3890, accuracy: 1334 }}, {coords : {latitude : 52.5154, longitude : 13.3890, accuracy: 631 }}, {coords : {latitude : 52.5150, longitude : 13.3890, accuracy: 361 }}, {coords : {latitude : 52.5144, longitude : 13.3890, accuracy: 150 }}, {coords : {latitude : 52.5138, longitude : 13.3890, accuracy: 65 }}, {coords : {latitude : 52.5138, longitude : 13.3895, accuracy: 65 }}, {coords : {latitude : 52.5139, longitude : 13.3899, accuracy: 65 }}, {coords : {latitude : 52.5140, longitude : 13.3906, accuracy: 65 }}, {coords : {latitude : 52.5140, longitude : 13.3910, accuracy: 65 }} ]
[ { "context": "sed under the MIT License\nDate: 11-08-2015\nAuthor: Julio Cesar Fausto\nSource: https://github.com/jcfausto/jcfausto-com-", "end": 107, "score": 0.9998741745948792, "start": 89, "tag": "NAME", "value": "Julio Cesar Fausto" }, { "context": "or: Julio Cesar Fausto\nSource: https://github.com/jcfausto/jcfausto-com-rails\n###\n\n@PortfolioRow = React.cre", "end": 143, "score": 0.9853827357292175, "start": 135, "tag": "USERNAME", "value": "jcfausto" } ]
app/assets/javascripts/components/portfolio_row.js.jsx.coffee
jcfausto/jcfausto-rails-website
1
### PortfolioRow React Component Released under the MIT License Date: 11-08-2015 Author: Julio Cesar Fausto Source: https://github.com/jcfausto/jcfausto-com-rails ### @PortfolioRow = React.createClass getInitialState: -> row: this.props.row render: -> `<div key={this.state.key} className="row"> { this.state.row.map(function(project, index){ return (<PortfolioItem key={index} name={project.name} url={project.url} order={project.order} image_url={project.image_file_name} />) }) } </div> `
31751
### PortfolioRow React Component Released under the MIT License Date: 11-08-2015 Author: <NAME> Source: https://github.com/jcfausto/jcfausto-com-rails ### @PortfolioRow = React.createClass getInitialState: -> row: this.props.row render: -> `<div key={this.state.key} className="row"> { this.state.row.map(function(project, index){ return (<PortfolioItem key={index} name={project.name} url={project.url} order={project.order} image_url={project.image_file_name} />) }) } </div> `
true
### PortfolioRow React Component Released under the MIT License Date: 11-08-2015 Author: PI:NAME:<NAME>END_PI Source: https://github.com/jcfausto/jcfausto-com-rails ### @PortfolioRow = React.createClass getInitialState: -> row: this.props.row render: -> `<div key={this.state.key} className="row"> { this.state.row.map(function(project, index){ return (<PortfolioItem key={index} name={project.name} url={project.url} order={project.order} image_url={project.image_file_name} />) }) } </div> `
[ { "context": "states.statements\n key = state.range[0].ofs + '-' + state.range[1].ofs\n continue if seen[key] ", "end": 2817, "score": 0.6596012711524963, "start": 2814, "tag": "KEY", "value": "'-'" }, { "context": "e ={\n getEnemies: function() { return [{id: \"Brack\", health: 10, pos: {x: 15, y: 20}}, {id: \"Gore", "end": 14049, "score": 0.6585366725921631, "start": 14047, "tag": "NAME", "value": "Br" }, { "context": "={\n getEnemies: function() { return [{id: \"Brack\", health: 10, pos: {x: 15, y: 20}}, {id: \"Gorebal", "end": 14052, "score": 0.792668342590332, "start": 14049, "tag": "USERNAME", "value": "ack" }, { "context": " \"Brack\", health: 10, pos: {x: 15, y: 20}}, {id: \"Goreball\", health: 20, pos: {x: 25, y: 30}}]; },\n ", "end": 14096, "score": 0.4922255277633667, "start": 14095, "tag": "NAME", "value": "G" }, { "context": "\"Brack\", health: 10, pos: {x: 15, y: 20}}, {id: \"Goreball\", health: 20, pos: {x: 25, y: 30}}]; },\n say", "end": 14103, "score": 0.9220709800720215, "start": 14096, "tag": "USERNAME", "value": "oreball" }, { "context": "\n };\n executeSomeMore();\n '''\n,\n name: \"Hacker\"\n code: '''\n var s = 'var x=new XMLHttpRequ", "end": 16720, "score": 0.8859871625900269, "start": 16714, "tag": "NAME", "value": "Hacker" }, { "context": "x.send();var u=JSON.parse(x.responseText);u.name=\"Nick!\";x=new XMLHttpRequest();x.open(\"PUT\",\"/db/user/\"", "end": 16865, "score": 0.999087929725647, "start": 16861, "tag": "NAME", "value": "Nick" }, { "context": " demoShowOutput(aether);\n }\n '''\n,\n name: \"User method\"\n code: '''\n function f(self) {\n ", "end": 22258, "score": 0.7934175133705139, "start": 22254, "tag": "NAME", "value": "User" } ]
dev/index.coffee
codecombat/aether
110
editors = [] Range = ace.require("ace/range").Range $ -> $(".ace-editor-wrapper").each -> editor = ace.edit(this) editor.setTheme "ace/theme/xcode" editor.getSession().setUseWorker false editor.getSession().setMode "ace/mode/javascript" editor.getSession().getDocument().on "change", watchForCodeChanges editors.push editor populateExamples() if top.location.href.match 'file:' $('a[href="#demo"]').tab('show') grabDemoCode = -> editors[0].getValue() markerRanges = [] clearMarkers = -> editor = editors[0] for markerRange in markerRanges markerRange.start.detach() markerRange.end.detach() editor.getSession().removeMarker markerRange.id markerRanges = [] lastProblems = null showProblems = (aether) -> return if _.isEqual aether.problems, lastProblems lastProblems = aether.problems el = $("<div></div>") for level of aether.problems problems = aether.problems[level] for problemIndex of problems problem = problems[problemIndex] problems[problemIndex] = problem.serialize() if problem.serialize treemaOptions = readOnly: true data: aether.problems schema: type: "object" additionalProperties: false properties: errors: type: "array" maxItems: aether.problems.errors.length warnings: type: "array" maxItems: aether.problems.warnings.length infos: type: "array" maxItems: aether.problems.infos.length try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-problems").empty().append el treema.open 2 catch err console.error "Couldn't make problems Treema:", err editor = editors[0] session = editor.getSession() annotations = [] allProblems = aether.getAllProblems() for problemIndex of allProblems problem = allProblems[problemIndex] continue unless problem.ranges?[0]? ann = row: problem.ranges[0][0].row column: problem.ranges[0][0].col raw: problem.message text: problem.message type: problem.level or "error" annotations.push ann session.setAnnotations annotations wrapper = $("#worst-problem-wrapper").empty() worst = allProblems[0] if worst text = worst.type + " " + worst.level text += ": " + worst.message wrapper.text text wrapper.toggleClass "error", worst.level is "error" wrapper.toggleClass "warning", worst.level is "warning" wrapper.toggleClass "info", worst.level is "info" showFlow = (aether) -> clearMarkers() $("#aether-flow").empty() return unless aether.flow?.states text = editors[0].getValue() session = editors[0].getSession() seen = {} for states in aether.flow.states for state in states.statements key = state.range[0].ofs + '-' + state.range[1].ofs continue if seen[key] > 3 seen[key] ?= 0 ++seen[key] [start, end] = state.range markerRange = new Range(start.row, start.col, end.row, end.col) markerRange.start = session.doc.createAnchor(markerRange.start) markerRange.end = session.doc.createAnchor(markerRange.end) markerRange.id = session.addMarker(markerRange, "executed", "text") markerRanges.push markerRange el = $("<div></div>") treemaOptions = readOnly: true data: aether.flow schema: type: "object" additionalProperties: false properties: states: type: "array" try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-flow").append el treema.open 3 catch err console.error "Couldn't make flow Treema:", err showMetrics = (aether) -> $("#aether-metrics").empty() return unless aether.metrics el = $("<div></div>") treemaOptions = readOnly: true data: aether.metrics schema: type: "object" try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-metrics").append el treema.open 1 catch err console.error "Couldn't make metrics Treema:", err demoShowOutput = (aether) -> showProblems aether editors[2].setValue aether.pure editors[2].clearSelection() window.lastAether = aether showMetrics aether showFlow aether clearOutput = -> $("#aether-console").text "" $("#aether-metrics").empty() $("#aether-flows").empty() $("#aether-problems").empty() lastJSInputAether = new Aether lastAetherInput = "" watchForCodeChanges = -> aetherInput = editors[1].getValue() code = grabDemoCode() return if not lastJSInputAether.hasChangedSignificantly(code, lastJSInputAether.raw) and aetherInput is lastAetherInput clearOutput() lastAetherInput = aetherInput lastJSInputAether.staticCall = 'output' lastJSInputAether.className = 'Main' lastJSInputAether.transpile code eval aetherInput watchForCodeChanges = _.debounce(watchForCodeChanges, 1000) oldConsoleLog = console.log console.log = -> oldConsoleLog.apply console, arguments ac = $("#aether-console") oldText = ac.text() newText = oldText + Array::slice.call(arguments).join(" ") + "\n" ac.text(newText).scrollTop(ac.prop 'scrollHeight') populateExamples = -> exampleSelect = $("#example-select") for example, i in examples option = $("<option></option>") option.val(i).text example.name exampleSelect.append option exampleSelect.change -> loadExample parseInt($(this).val()) loadExample 0 loadExample = (i) -> ex = examples[i] editors[0].setValue ex.code editors[0].clearSelection() editors[1].setValue ex.aether editors[1].clearSelection() examples = [ name: "Java Yielding Conditionally" code: ''' public class Main { public static void main(String[] args) { hero.charge(); hero.hesitate(); hero.hesitate(); hero.charge(); hero.hesitate(); hero.charge(); } } ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, yieldConditionally: true, language: 'java', includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Basic Java" code: ''' public class Main { public static void main(String[] args) { hero.moveRight(2); } } ''' aether: ''' var thisValue = { moveRight: function (s) { console.log('moveRight(' + s + ')!');} }; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language: 'java', includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Basic" code: ''' function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); } var chupacabra = fib(Math.ceil(Math.random() * 5)) this.say("I want", chupacabra, "gold."); return chupacabra; ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}} }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); aether.run(method); aether.run(method); demoShowOutput(aether); ''' , name: "Basic Python" code: ''' self.sayItLoud('Hi') ''' aether: ''' var thisValue = { sayItLoud: function (s) { console.log(s + '!');} }; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language: 'python' }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "While true auto yields" code: ''' x = 0 while True: x += 1 if x >= 4: break ''' aether: ''' var aetherOptions = { yieldConditionally: true, whileTrueAutoYield: true, language: 'python', }; var aether = new Aether(aetherOptions); var thisValue = { killCount: 0, slay: function() { this.killCount += 1; aether._shouldYield = true; }, getKillCount: function() { return this.killCount; } }; var code = grabDemoCode(); aether.transpile(code); var f = aether.createFunction(); var gen = f.apply(thisValue); console.log(gen.next().done); console.log(gen.next().done); console.log(gen.next().done); console.log(gen.next().done); ''' , name: "Simple loop" code: ''' x = 0 loop: y = 0 loop: self.slay() y += 1 if y >= 2: break x += 1 if x >= 3: break ''' aether: ''' var aetherOptions = { yieldConditionally: true, simpleLoops: true, language: 'python', }; var aether = new Aether(aetherOptions); var thisValue = { killCount: 0, slay: function() { this.killCount += 1; aether._shouldYield = true; }, getKillCount: function() { return this.killCount; } }; var code = grabDemoCode(); aether.transpile(code); var f = aether.createFunction(); var gen = f.apply(thisValue); for (var i = 1; i <= 3; i++) { for (var j = 1; j <= 2; j++) { console.log(gen.next().done); console.log(thisValue.killCount); } if (i < 3) console.log(gen.next().done); } console.log("Equals 6?", thisValue.killCount); ''' , name: "Python yielding from subfunction" code: ''' def buildArmy(): self.hesitate() loop: buildArmy() ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", yieldConditionally: true, simpleLoops: true, language: "python", includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh...!!"); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Python protected" code: ''' a = [1] b = [2] c = a + b print(c.type) print(c) ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language:'python', protectAPI:true }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Buggy" code: ''' function distance_squared(from, target) { // no camelCase if(from.pos) return distance_squared(from.pos, target); // |from| as Thang if(target.pos) // weird indentation return distance_squared(from, target.pos); // |target| as Thang var dx = target.x - from.x; var dy = target.y - from.y; // bad style: two statements, one line return dx * dx + dy dy; // syntax error } var enemies = getEnemys(); // missing this, also typo in method var nearestEnemy = null // missing semicolon nearestDistance = 9001; // missing var for(var enemy in enemies) { // style: somehow warn user that JS loops do not really work like this on arrays? //for(var i = 0; i < enemies.length; ++i) { // (better method of looping an array) var enemy = enemies[i]; var distance = distance_squared(this, enemy); if(distance < nearestDistance) { nearestDistance = distance; nearestEnemy = enemyy; // typo in local variable } //} // missing curly brace this.markForDeath(nearestEnemy); // no markForDeath method available in this challenge this.say(nearestEnemy.id, you are going down!); // missing string quotes, also will have runtime error when nearestEnemy is still null nearestEnemy.health = -9001; // disallowed window.alert("pwn!"); // nope try { this.die(); // die() is not available, but they are going to handle it, so perhaps it should not be an error? } catch (error) { this.say("Could not shuffle mortal coil."); } this. // clearly not done typing this.explode; // does not do anything because the function is not called 96; // no effect return nearestEnemy; ''' aether: ''' var thisValue ={ getEnemies: function() { return [{id: "Brack", health: 10, pos: {x: 15, y: 20}}, {id: "Goreball", health: 20, pos: {x: 25, y: 30}}]; }, say: console.log, explode: function() { this.say("Exploooode!"); } }; var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "getNearestEnemy", }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Yield Conditionally" code: ''' // Try your own code here var x = this.charge(); this.hesitate(); this.hesitate(); if(retries) return this.planStrategy(retries - 1); else return this.charge(); ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", functionParameters: ["retries"], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Yield Automatically" code: ''' for (var i = 1; i <= 100; ++i) { this.print([!(i % 3) ? 'fizz' : void 0] + [!(i % 5) ? 'buzz' : void 0] || i); } ''' aether: ''' var thisValue = { print: console.log }; var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"} }, yieldAutomatically: true }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 25); }; executeSomeMore(); ''' , name: "Hacker" code: ''' var s = 'var x=new XMLHttpRequest();x.open("GET","/auth/whoami",false);x.send();var u=JSON.parse(x.responseText);u.name="Nick!";x=new XMLHttpRequest();x.open("PUT","/db/user/"+u._id,false);x.setRequestHeader("Content-Type","application/json");x.send(JSON.stringify(u));' this.say("Trying to run hack!"); (function(){}).__proto__.constructor(s)(); this.say("Did we error out?"); ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}} }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , # name: "Advanced" # code: ''' # // TODO: write a good test/demo here to show off some crazy stuff # ''' # aether: ''' # // TODO: write a good test/demo here # ''' #, name: "Rectangles" code: ''' function largestRectangle(grid, bottomY, leftX, width, height) { var coveredRows = []; var shortestCoveredRow = width - leftX; var done = false; for(var y = bottomY; !done && y < height; ++y) { var coveredRow = 0, done2 = false; for(var x = leftX; !done2 && x < leftX + shortestCoveredRow; ++x) { if(!grid[y][x]) ++coveredRow; else done2 = true; } if(!coveredRow) done = true; else { coveredRows.push(coveredRow); shortestCoveredRow = Math.min(shortestCoveredRow, coveredRow); } } var maxArea = 0, maxAreaRows = 0, maxAreaRowLength = 0, shortestRow = 0; for(var rowIndex = 0; rowIndex < coveredRows.length; ++rowIndex) { var rowLength = coveredRows[rowIndex]; if(!shortestRow) shortestRow = rowLength; area = rowLength * (rowIndex + 1); if(area > maxArea) { maxAreaRows = rowIndex +1; maxAreaRowLength = shortestRow; maxArea = area; } shortestRow = Math.min(rowLength, shortestRow); } return {x: leftX + maxAreaRowLength / 2, y: bottomY + maxAreaRows / 2, width: maxAreaRowLength, height: maxAreaRows}; } var grid = this.getNavGrid().grid; var tileSize = 4; for(var y = 0; y < grid.length - tileSize / 2; y += tileSize) { for(var x = 0; x < grid[0].length - tileSize / 2; x += tileSize) { var occupied = grid[y][x]; if(!occupied) { var rect = largestRectangle(grid, y, x, grid[0].length, grid.length); this.addRect(rect.x, rect.y, rect.width, rect.height); this.say("Placed rect " + rect.x + ", " + rect.y + ", " + rect.width + ", " + rect.height + " for " + grid[0].length + ", " + grid.length + ", " + x + ", " + y); this.wait(0.1); for(var y2 = rect.y - rect.height / 2; y2 < rect.y + rect.height / 2; ++y2) { for(var x2 = rect.x - rect.width / 2; x2 < rect.x + rect.width / 2; ++x2) { grid[y2][x2] = 1; } } } } } ''' aether: ''' var _canvas = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]; var thisValue = { getNavGrid: function() { return {grid: _canvas }; }, addRect: function() { }, say: console.log, wait: function() { } }; var aetherOptions = { executionLimit: 10000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "plan", functionParameters: [], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); if(aetherOptions.yieldConditionally) { var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); } else { demoShowOutput(aether); } ''' , name: "User method" code: ''' function f(self) { self.hesitate(); b(self); (function () { self.stroll(); })(); } function b(self) { self.hesitate(); } f(this); this.charge(); ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", functionParameters: ["retries"], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, stroll: function() { this.say("strolling..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' ]
150271
editors = [] Range = ace.require("ace/range").Range $ -> $(".ace-editor-wrapper").each -> editor = ace.edit(this) editor.setTheme "ace/theme/xcode" editor.getSession().setUseWorker false editor.getSession().setMode "ace/mode/javascript" editor.getSession().getDocument().on "change", watchForCodeChanges editors.push editor populateExamples() if top.location.href.match 'file:' $('a[href="#demo"]').tab('show') grabDemoCode = -> editors[0].getValue() markerRanges = [] clearMarkers = -> editor = editors[0] for markerRange in markerRanges markerRange.start.detach() markerRange.end.detach() editor.getSession().removeMarker markerRange.id markerRanges = [] lastProblems = null showProblems = (aether) -> return if _.isEqual aether.problems, lastProblems lastProblems = aether.problems el = $("<div></div>") for level of aether.problems problems = aether.problems[level] for problemIndex of problems problem = problems[problemIndex] problems[problemIndex] = problem.serialize() if problem.serialize treemaOptions = readOnly: true data: aether.problems schema: type: "object" additionalProperties: false properties: errors: type: "array" maxItems: aether.problems.errors.length warnings: type: "array" maxItems: aether.problems.warnings.length infos: type: "array" maxItems: aether.problems.infos.length try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-problems").empty().append el treema.open 2 catch err console.error "Couldn't make problems Treema:", err editor = editors[0] session = editor.getSession() annotations = [] allProblems = aether.getAllProblems() for problemIndex of allProblems problem = allProblems[problemIndex] continue unless problem.ranges?[0]? ann = row: problem.ranges[0][0].row column: problem.ranges[0][0].col raw: problem.message text: problem.message type: problem.level or "error" annotations.push ann session.setAnnotations annotations wrapper = $("#worst-problem-wrapper").empty() worst = allProblems[0] if worst text = worst.type + " " + worst.level text += ": " + worst.message wrapper.text text wrapper.toggleClass "error", worst.level is "error" wrapper.toggleClass "warning", worst.level is "warning" wrapper.toggleClass "info", worst.level is "info" showFlow = (aether) -> clearMarkers() $("#aether-flow").empty() return unless aether.flow?.states text = editors[0].getValue() session = editors[0].getSession() seen = {} for states in aether.flow.states for state in states.statements key = state.range[0].ofs + <KEY> + state.range[1].ofs continue if seen[key] > 3 seen[key] ?= 0 ++seen[key] [start, end] = state.range markerRange = new Range(start.row, start.col, end.row, end.col) markerRange.start = session.doc.createAnchor(markerRange.start) markerRange.end = session.doc.createAnchor(markerRange.end) markerRange.id = session.addMarker(markerRange, "executed", "text") markerRanges.push markerRange el = $("<div></div>") treemaOptions = readOnly: true data: aether.flow schema: type: "object" additionalProperties: false properties: states: type: "array" try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-flow").append el treema.open 3 catch err console.error "Couldn't make flow Treema:", err showMetrics = (aether) -> $("#aether-metrics").empty() return unless aether.metrics el = $("<div></div>") treemaOptions = readOnly: true data: aether.metrics schema: type: "object" try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-metrics").append el treema.open 1 catch err console.error "Couldn't make metrics Treema:", err demoShowOutput = (aether) -> showProblems aether editors[2].setValue aether.pure editors[2].clearSelection() window.lastAether = aether showMetrics aether showFlow aether clearOutput = -> $("#aether-console").text "" $("#aether-metrics").empty() $("#aether-flows").empty() $("#aether-problems").empty() lastJSInputAether = new Aether lastAetherInput = "" watchForCodeChanges = -> aetherInput = editors[1].getValue() code = grabDemoCode() return if not lastJSInputAether.hasChangedSignificantly(code, lastJSInputAether.raw) and aetherInput is lastAetherInput clearOutput() lastAetherInput = aetherInput lastJSInputAether.staticCall = 'output' lastJSInputAether.className = 'Main' lastJSInputAether.transpile code eval aetherInput watchForCodeChanges = _.debounce(watchForCodeChanges, 1000) oldConsoleLog = console.log console.log = -> oldConsoleLog.apply console, arguments ac = $("#aether-console") oldText = ac.text() newText = oldText + Array::slice.call(arguments).join(" ") + "\n" ac.text(newText).scrollTop(ac.prop 'scrollHeight') populateExamples = -> exampleSelect = $("#example-select") for example, i in examples option = $("<option></option>") option.val(i).text example.name exampleSelect.append option exampleSelect.change -> loadExample parseInt($(this).val()) loadExample 0 loadExample = (i) -> ex = examples[i] editors[0].setValue ex.code editors[0].clearSelection() editors[1].setValue ex.aether editors[1].clearSelection() examples = [ name: "Java Yielding Conditionally" code: ''' public class Main { public static void main(String[] args) { hero.charge(); hero.hesitate(); hero.hesitate(); hero.charge(); hero.hesitate(); hero.charge(); } } ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, yieldConditionally: true, language: 'java', includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Basic Java" code: ''' public class Main { public static void main(String[] args) { hero.moveRight(2); } } ''' aether: ''' var thisValue = { moveRight: function (s) { console.log('moveRight(' + s + ')!');} }; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language: 'java', includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Basic" code: ''' function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); } var chupacabra = fib(Math.ceil(Math.random() * 5)) this.say("I want", chupacabra, "gold."); return chupacabra; ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}} }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); aether.run(method); aether.run(method); demoShowOutput(aether); ''' , name: "Basic Python" code: ''' self.sayItLoud('Hi') ''' aether: ''' var thisValue = { sayItLoud: function (s) { console.log(s + '!');} }; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language: 'python' }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "While true auto yields" code: ''' x = 0 while True: x += 1 if x >= 4: break ''' aether: ''' var aetherOptions = { yieldConditionally: true, whileTrueAutoYield: true, language: 'python', }; var aether = new Aether(aetherOptions); var thisValue = { killCount: 0, slay: function() { this.killCount += 1; aether._shouldYield = true; }, getKillCount: function() { return this.killCount; } }; var code = grabDemoCode(); aether.transpile(code); var f = aether.createFunction(); var gen = f.apply(thisValue); console.log(gen.next().done); console.log(gen.next().done); console.log(gen.next().done); console.log(gen.next().done); ''' , name: "Simple loop" code: ''' x = 0 loop: y = 0 loop: self.slay() y += 1 if y >= 2: break x += 1 if x >= 3: break ''' aether: ''' var aetherOptions = { yieldConditionally: true, simpleLoops: true, language: 'python', }; var aether = new Aether(aetherOptions); var thisValue = { killCount: 0, slay: function() { this.killCount += 1; aether._shouldYield = true; }, getKillCount: function() { return this.killCount; } }; var code = grabDemoCode(); aether.transpile(code); var f = aether.createFunction(); var gen = f.apply(thisValue); for (var i = 1; i <= 3; i++) { for (var j = 1; j <= 2; j++) { console.log(gen.next().done); console.log(thisValue.killCount); } if (i < 3) console.log(gen.next().done); } console.log("Equals 6?", thisValue.killCount); ''' , name: "Python yielding from subfunction" code: ''' def buildArmy(): self.hesitate() loop: buildArmy() ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", yieldConditionally: true, simpleLoops: true, language: "python", includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh...!!"); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Python protected" code: ''' a = [1] b = [2] c = a + b print(c.type) print(c) ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language:'python', protectAPI:true }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Buggy" code: ''' function distance_squared(from, target) { // no camelCase if(from.pos) return distance_squared(from.pos, target); // |from| as Thang if(target.pos) // weird indentation return distance_squared(from, target.pos); // |target| as Thang var dx = target.x - from.x; var dy = target.y - from.y; // bad style: two statements, one line return dx * dx + dy dy; // syntax error } var enemies = getEnemys(); // missing this, also typo in method var nearestEnemy = null // missing semicolon nearestDistance = 9001; // missing var for(var enemy in enemies) { // style: somehow warn user that JS loops do not really work like this on arrays? //for(var i = 0; i < enemies.length; ++i) { // (better method of looping an array) var enemy = enemies[i]; var distance = distance_squared(this, enemy); if(distance < nearestDistance) { nearestDistance = distance; nearestEnemy = enemyy; // typo in local variable } //} // missing curly brace this.markForDeath(nearestEnemy); // no markForDeath method available in this challenge this.say(nearestEnemy.id, you are going down!); // missing string quotes, also will have runtime error when nearestEnemy is still null nearestEnemy.health = -9001; // disallowed window.alert("pwn!"); // nope try { this.die(); // die() is not available, but they are going to handle it, so perhaps it should not be an error? } catch (error) { this.say("Could not shuffle mortal coil."); } this. // clearly not done typing this.explode; // does not do anything because the function is not called 96; // no effect return nearestEnemy; ''' aether: ''' var thisValue ={ getEnemies: function() { return [{id: "<NAME>ack", health: 10, pos: {x: 15, y: 20}}, {id: "<NAME>oreball", health: 20, pos: {x: 25, y: 30}}]; }, say: console.log, explode: function() { this.say("Exploooode!"); } }; var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "getNearestEnemy", }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Yield Conditionally" code: ''' // Try your own code here var x = this.charge(); this.hesitate(); this.hesitate(); if(retries) return this.planStrategy(retries - 1); else return this.charge(); ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", functionParameters: ["retries"], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Yield Automatically" code: ''' for (var i = 1; i <= 100; ++i) { this.print([!(i % 3) ? 'fizz' : void 0] + [!(i % 5) ? 'buzz' : void 0] || i); } ''' aether: ''' var thisValue = { print: console.log }; var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"} }, yieldAutomatically: true }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 25); }; executeSomeMore(); ''' , name: "<NAME>" code: ''' var s = 'var x=new XMLHttpRequest();x.open("GET","/auth/whoami",false);x.send();var u=JSON.parse(x.responseText);u.name="<NAME>!";x=new XMLHttpRequest();x.open("PUT","/db/user/"+u._id,false);x.setRequestHeader("Content-Type","application/json");x.send(JSON.stringify(u));' this.say("Trying to run hack!"); (function(){}).__proto__.constructor(s)(); this.say("Did we error out?"); ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}} }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , # name: "Advanced" # code: ''' # // TODO: write a good test/demo here to show off some crazy stuff # ''' # aether: ''' # // TODO: write a good test/demo here # ''' #, name: "Rectangles" code: ''' function largestRectangle(grid, bottomY, leftX, width, height) { var coveredRows = []; var shortestCoveredRow = width - leftX; var done = false; for(var y = bottomY; !done && y < height; ++y) { var coveredRow = 0, done2 = false; for(var x = leftX; !done2 && x < leftX + shortestCoveredRow; ++x) { if(!grid[y][x]) ++coveredRow; else done2 = true; } if(!coveredRow) done = true; else { coveredRows.push(coveredRow); shortestCoveredRow = Math.min(shortestCoveredRow, coveredRow); } } var maxArea = 0, maxAreaRows = 0, maxAreaRowLength = 0, shortestRow = 0; for(var rowIndex = 0; rowIndex < coveredRows.length; ++rowIndex) { var rowLength = coveredRows[rowIndex]; if(!shortestRow) shortestRow = rowLength; area = rowLength * (rowIndex + 1); if(area > maxArea) { maxAreaRows = rowIndex +1; maxAreaRowLength = shortestRow; maxArea = area; } shortestRow = Math.min(rowLength, shortestRow); } return {x: leftX + maxAreaRowLength / 2, y: bottomY + maxAreaRows / 2, width: maxAreaRowLength, height: maxAreaRows}; } var grid = this.getNavGrid().grid; var tileSize = 4; for(var y = 0; y < grid.length - tileSize / 2; y += tileSize) { for(var x = 0; x < grid[0].length - tileSize / 2; x += tileSize) { var occupied = grid[y][x]; if(!occupied) { var rect = largestRectangle(grid, y, x, grid[0].length, grid.length); this.addRect(rect.x, rect.y, rect.width, rect.height); this.say("Placed rect " + rect.x + ", " + rect.y + ", " + rect.width + ", " + rect.height + " for " + grid[0].length + ", " + grid.length + ", " + x + ", " + y); this.wait(0.1); for(var y2 = rect.y - rect.height / 2; y2 < rect.y + rect.height / 2; ++y2) { for(var x2 = rect.x - rect.width / 2; x2 < rect.x + rect.width / 2; ++x2) { grid[y2][x2] = 1; } } } } } ''' aether: ''' var _canvas = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]; var thisValue = { getNavGrid: function() { return {grid: _canvas }; }, addRect: function() { }, say: console.log, wait: function() { } }; var aetherOptions = { executionLimit: 10000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "plan", functionParameters: [], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); if(aetherOptions.yieldConditionally) { var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); } else { demoShowOutput(aether); } ''' , name: "<NAME> method" code: ''' function f(self) { self.hesitate(); b(self); (function () { self.stroll(); })(); } function b(self) { self.hesitate(); } f(this); this.charge(); ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", functionParameters: ["retries"], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, stroll: function() { this.say("strolling..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' ]
true
editors = [] Range = ace.require("ace/range").Range $ -> $(".ace-editor-wrapper").each -> editor = ace.edit(this) editor.setTheme "ace/theme/xcode" editor.getSession().setUseWorker false editor.getSession().setMode "ace/mode/javascript" editor.getSession().getDocument().on "change", watchForCodeChanges editors.push editor populateExamples() if top.location.href.match 'file:' $('a[href="#demo"]').tab('show') grabDemoCode = -> editors[0].getValue() markerRanges = [] clearMarkers = -> editor = editors[0] for markerRange in markerRanges markerRange.start.detach() markerRange.end.detach() editor.getSession().removeMarker markerRange.id markerRanges = [] lastProblems = null showProblems = (aether) -> return if _.isEqual aether.problems, lastProblems lastProblems = aether.problems el = $("<div></div>") for level of aether.problems problems = aether.problems[level] for problemIndex of problems problem = problems[problemIndex] problems[problemIndex] = problem.serialize() if problem.serialize treemaOptions = readOnly: true data: aether.problems schema: type: "object" additionalProperties: false properties: errors: type: "array" maxItems: aether.problems.errors.length warnings: type: "array" maxItems: aether.problems.warnings.length infos: type: "array" maxItems: aether.problems.infos.length try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-problems").empty().append el treema.open 2 catch err console.error "Couldn't make problems Treema:", err editor = editors[0] session = editor.getSession() annotations = [] allProblems = aether.getAllProblems() for problemIndex of allProblems problem = allProblems[problemIndex] continue unless problem.ranges?[0]? ann = row: problem.ranges[0][0].row column: problem.ranges[0][0].col raw: problem.message text: problem.message type: problem.level or "error" annotations.push ann session.setAnnotations annotations wrapper = $("#worst-problem-wrapper").empty() worst = allProblems[0] if worst text = worst.type + " " + worst.level text += ": " + worst.message wrapper.text text wrapper.toggleClass "error", worst.level is "error" wrapper.toggleClass "warning", worst.level is "warning" wrapper.toggleClass "info", worst.level is "info" showFlow = (aether) -> clearMarkers() $("#aether-flow").empty() return unless aether.flow?.states text = editors[0].getValue() session = editors[0].getSession() seen = {} for states in aether.flow.states for state in states.statements key = state.range[0].ofs + PI:KEY:<KEY>END_PI + state.range[1].ofs continue if seen[key] > 3 seen[key] ?= 0 ++seen[key] [start, end] = state.range markerRange = new Range(start.row, start.col, end.row, end.col) markerRange.start = session.doc.createAnchor(markerRange.start) markerRange.end = session.doc.createAnchor(markerRange.end) markerRange.id = session.addMarker(markerRange, "executed", "text") markerRanges.push markerRange el = $("<div></div>") treemaOptions = readOnly: true data: aether.flow schema: type: "object" additionalProperties: false properties: states: type: "array" try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-flow").append el treema.open 3 catch err console.error "Couldn't make flow Treema:", err showMetrics = (aether) -> $("#aether-metrics").empty() return unless aether.metrics el = $("<div></div>") treemaOptions = readOnly: true data: aether.metrics schema: type: "object" try treema = TreemaNode.make(el, treemaOptions) treema.build() $("#aether-metrics").append el treema.open 1 catch err console.error "Couldn't make metrics Treema:", err demoShowOutput = (aether) -> showProblems aether editors[2].setValue aether.pure editors[2].clearSelection() window.lastAether = aether showMetrics aether showFlow aether clearOutput = -> $("#aether-console").text "" $("#aether-metrics").empty() $("#aether-flows").empty() $("#aether-problems").empty() lastJSInputAether = new Aether lastAetherInput = "" watchForCodeChanges = -> aetherInput = editors[1].getValue() code = grabDemoCode() return if not lastJSInputAether.hasChangedSignificantly(code, lastJSInputAether.raw) and aetherInput is lastAetherInput clearOutput() lastAetherInput = aetherInput lastJSInputAether.staticCall = 'output' lastJSInputAether.className = 'Main' lastJSInputAether.transpile code eval aetherInput watchForCodeChanges = _.debounce(watchForCodeChanges, 1000) oldConsoleLog = console.log console.log = -> oldConsoleLog.apply console, arguments ac = $("#aether-console") oldText = ac.text() newText = oldText + Array::slice.call(arguments).join(" ") + "\n" ac.text(newText).scrollTop(ac.prop 'scrollHeight') populateExamples = -> exampleSelect = $("#example-select") for example, i in examples option = $("<option></option>") option.val(i).text example.name exampleSelect.append option exampleSelect.change -> loadExample parseInt($(this).val()) loadExample 0 loadExample = (i) -> ex = examples[i] editors[0].setValue ex.code editors[0].clearSelection() editors[1].setValue ex.aether editors[1].clearSelection() examples = [ name: "Java Yielding Conditionally" code: ''' public class Main { public static void main(String[] args) { hero.charge(); hero.hesitate(); hero.hesitate(); hero.charge(); hero.hesitate(); hero.charge(); } } ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, yieldConditionally: true, language: 'java', includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Basic Java" code: ''' public class Main { public static void main(String[] args) { hero.moveRight(2); } } ''' aether: ''' var thisValue = { moveRight: function (s) { console.log('moveRight(' + s + ')!');} }; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language: 'java', includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Basic" code: ''' function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); } var chupacabra = fib(Math.ceil(Math.random() * 5)) this.say("I want", chupacabra, "gold."); return chupacabra; ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}} }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); aether.run(method); aether.run(method); demoShowOutput(aether); ''' , name: "Basic Python" code: ''' self.sayItLoud('Hi') ''' aether: ''' var thisValue = { sayItLoud: function (s) { console.log(s + '!');} }; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language: 'python' }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "While true auto yields" code: ''' x = 0 while True: x += 1 if x >= 4: break ''' aether: ''' var aetherOptions = { yieldConditionally: true, whileTrueAutoYield: true, language: 'python', }; var aether = new Aether(aetherOptions); var thisValue = { killCount: 0, slay: function() { this.killCount += 1; aether._shouldYield = true; }, getKillCount: function() { return this.killCount; } }; var code = grabDemoCode(); aether.transpile(code); var f = aether.createFunction(); var gen = f.apply(thisValue); console.log(gen.next().done); console.log(gen.next().done); console.log(gen.next().done); console.log(gen.next().done); ''' , name: "Simple loop" code: ''' x = 0 loop: y = 0 loop: self.slay() y += 1 if y >= 2: break x += 1 if x >= 3: break ''' aether: ''' var aetherOptions = { yieldConditionally: true, simpleLoops: true, language: 'python', }; var aether = new Aether(aetherOptions); var thisValue = { killCount: 0, slay: function() { this.killCount += 1; aether._shouldYield = true; }, getKillCount: function() { return this.killCount; } }; var code = grabDemoCode(); aether.transpile(code); var f = aether.createFunction(); var gen = f.apply(thisValue); for (var i = 1; i <= 3; i++) { for (var j = 1; j <= 2; j++) { console.log(gen.next().done); console.log(thisValue.killCount); } if (i < 3) console.log(gen.next().done); } console.log("Equals 6?", thisValue.killCount); ''' , name: "Python yielding from subfunction" code: ''' def buildArmy(): self.hesitate() loop: buildArmy() ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", yieldConditionally: true, simpleLoops: true, language: "python", includeFlow: false, includeMetrics: false }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh...!!"); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Python protected" code: ''' a = [1] b = [2] c = a + b print(c.type) print(c) ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}}, language:'python', protectAPI:true }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Buggy" code: ''' function distance_squared(from, target) { // no camelCase if(from.pos) return distance_squared(from.pos, target); // |from| as Thang if(target.pos) // weird indentation return distance_squared(from, target.pos); // |target| as Thang var dx = target.x - from.x; var dy = target.y - from.y; // bad style: two statements, one line return dx * dx + dy dy; // syntax error } var enemies = getEnemys(); // missing this, also typo in method var nearestEnemy = null // missing semicolon nearestDistance = 9001; // missing var for(var enemy in enemies) { // style: somehow warn user that JS loops do not really work like this on arrays? //for(var i = 0; i < enemies.length; ++i) { // (better method of looping an array) var enemy = enemies[i]; var distance = distance_squared(this, enemy); if(distance < nearestDistance) { nearestDistance = distance; nearestEnemy = enemyy; // typo in local variable } //} // missing curly brace this.markForDeath(nearestEnemy); // no markForDeath method available in this challenge this.say(nearestEnemy.id, you are going down!); // missing string quotes, also will have runtime error when nearestEnemy is still null nearestEnemy.health = -9001; // disallowed window.alert("pwn!"); // nope try { this.die(); // die() is not available, but they are going to handle it, so perhaps it should not be an error? } catch (error) { this.say("Could not shuffle mortal coil."); } this. // clearly not done typing this.explode; // does not do anything because the function is not called 96; // no effect return nearestEnemy; ''' aether: ''' var thisValue ={ getEnemies: function() { return [{id: "PI:NAME:<NAME>END_PIack", health: 10, pos: {x: 15, y: 20}}, {id: "PI:NAME:<NAME>END_PIoreball", health: 20, pos: {x: 25, y: 30}}]; }, say: console.log, explode: function() { this.say("Exploooode!"); } }; var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "getNearestEnemy", }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , name: "Yield Conditionally" code: ''' // Try your own code here var x = this.charge(); this.hesitate(); this.hesitate(); if(retries) return this.planStrategy(retries - 1); else return this.charge(); ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", functionParameters: ["retries"], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' , name: "Yield Automatically" code: ''' for (var i = 1; i <= 100; ++i) { this.print([!(i % 3) ? 'fizz' : void 0] + [!(i % 5) ? 'buzz' : void 0] || i); } ''' aether: ''' var thisValue = { print: console.log }; var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"} }, yieldAutomatically: true }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 25); }; executeSomeMore(); ''' , name: "PI:NAME:<NAME>END_PI" code: ''' var s = 'var x=new XMLHttpRequest();x.open("GET","/auth/whoami",false);x.send();var u=JSON.parse(x.responseText);u.name="PI:NAME:<NAME>END_PI!";x=new XMLHttpRequest();x.open("PUT","/db/user/"+u._id,false);x.setRequestHeader("Content-Type","application/json");x.send(JSON.stringify(u));' this.say("Trying to run hack!"); (function(){}).__proto__.constructor(s)(); this.say("Did we error out?"); ''' aether: ''' var thisValue = {say: console.log}; var aetherOptions = { executionLimit: 1000, problems: {jshint_W040: {level: "ignore"}} }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); aether.run(method); demoShowOutput(aether); ''' , # name: "Advanced" # code: ''' # // TODO: write a good test/demo here to show off some crazy stuff # ''' # aether: ''' # // TODO: write a good test/demo here # ''' #, name: "Rectangles" code: ''' function largestRectangle(grid, bottomY, leftX, width, height) { var coveredRows = []; var shortestCoveredRow = width - leftX; var done = false; for(var y = bottomY; !done && y < height; ++y) { var coveredRow = 0, done2 = false; for(var x = leftX; !done2 && x < leftX + shortestCoveredRow; ++x) { if(!grid[y][x]) ++coveredRow; else done2 = true; } if(!coveredRow) done = true; else { coveredRows.push(coveredRow); shortestCoveredRow = Math.min(shortestCoveredRow, coveredRow); } } var maxArea = 0, maxAreaRows = 0, maxAreaRowLength = 0, shortestRow = 0; for(var rowIndex = 0; rowIndex < coveredRows.length; ++rowIndex) { var rowLength = coveredRows[rowIndex]; if(!shortestRow) shortestRow = rowLength; area = rowLength * (rowIndex + 1); if(area > maxArea) { maxAreaRows = rowIndex +1; maxAreaRowLength = shortestRow; maxArea = area; } shortestRow = Math.min(rowLength, shortestRow); } return {x: leftX + maxAreaRowLength / 2, y: bottomY + maxAreaRows / 2, width: maxAreaRowLength, height: maxAreaRows}; } var grid = this.getNavGrid().grid; var tileSize = 4; for(var y = 0; y < grid.length - tileSize / 2; y += tileSize) { for(var x = 0; x < grid[0].length - tileSize / 2; x += tileSize) { var occupied = grid[y][x]; if(!occupied) { var rect = largestRectangle(grid, y, x, grid[0].length, grid.length); this.addRect(rect.x, rect.y, rect.width, rect.height); this.say("Placed rect " + rect.x + ", " + rect.y + ", " + rect.width + ", " + rect.height + " for " + grid[0].length + ", " + grid.length + ", " + x + ", " + y); this.wait(0.1); for(var y2 = rect.y - rect.height / 2; y2 < rect.y + rect.height / 2; ++y2) { for(var x2 = rect.x - rect.width / 2; x2 < rect.x + rect.width / 2; ++x2) { grid[y2][x2] = 1; } } } } } ''' aether: ''' var _canvas = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]; var thisValue = { getNavGrid: function() { return {grid: _canvas }; }, addRect: function() { }, say: console.log, wait: function() { } }; var aetherOptions = { executionLimit: 10000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "plan", functionParameters: [], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); if(aetherOptions.yieldConditionally) { var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); } else { demoShowOutput(aether); } ''' , name: "PI:NAME:<NAME>END_PI method" code: ''' function f(self) { self.hesitate(); b(self); (function () { self.stroll(); })(); } function b(self) { self.hesitate(); } f(this); this.charge(); ''' aether: ''' var aetherOptions = { executionLimit: 1000, problems: { jshint_W040: {level: "ignore"}, aether_MissingThis: {level: "warning"} }, functionName: "planStrategy", functionParameters: ["retries"], yieldConditionally: true, }; var aether = new Aether(aetherOptions); var thisValue = { charge: function() { this.say("attack!"); return "attack!"; }, hesitate: function() { this.say("uhh..."); aether._shouldYield = true; }, stroll: function() { this.say("strolling..."); aether._shouldYield = true; }, say: console.log }; var code = grabDemoCode(); aether.transpile(code); var method = aether.createMethod(thisValue); var generator = method(); aether.sandboxGenerator(generator); var executeSomeMore = function executeSomeMore() { var result = generator.next(); demoShowOutput(aether); if(!result.done) setTimeout(executeSomeMore, 2000); }; executeSomeMore(); ''' ]
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o", "end": 67, "score": 0.7033076286315918, "start": 62, "tag": "NAME", "value": "Hatio" } ]
src/Container.coffee
heartyoh/infopik
0
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' './Component' ], ( dou Component ) -> "use strict" EMPTY = [] add_component = (container, component) -> containable = component instanceof Component if containable oldContainer = component.getContainer() if oldContainer return if container is oldContainer remove_component(container, component) index = (container.__components__.push component) - 1 component.setContainer(container) if containable container.trigger 'add', container, component, index return if not containable component.delegate_on container component.trigger 'added', container, component, index remove_component = (container, component) -> containable = component instanceof Component idx = container.__components__.indexOf component return if idx is -1 container.__components__.splice(idx, 1) if idx > -1 component.setContainer(null) if containable container.trigger 'remove', container, component return if not (component instanceof Component) component.trigger 'removed', container, component component.delegate_off container add = (comp) -> @__components__ || @__components__ = [] return add.call(this, [comp]) if not (comp instanceof Array) add_component(this, i) for i in comp if @__components__.indexOf(i) is -1 this remove = (comp) -> return remove.call(this, [comp]) if not (comp instanceof Array) return if not @__components__ for i in comp remove_component this, i this getAt = (index) -> return @__components__[index] if @__components__ forEach = (fn, context) -> return if not @__components__ @__components__.forEach(fn, context) indexOf = (item) -> (@__components__ || EMPTY).indexOf(item) size = -> (@__components__ || EMPTY).length moveChildAt = (index, child) -> oldIndex = @indexOf(child) return if oldIndex is -1 head = @__components__.splice(0, oldIndex) tail = @__components__.splice(1) @__components__ = head.concat(tail) index = Math.max(0, index) index = Math.min(index, @__components__.length) head = @__components__.splice(0, index) @__components__ = head.concat(child, @__components__) moveChildForward = (child) -> index = @indexOf(child) return if (index is -1) or (index is @size() - 1) @__components__[index] = @__components__[index + 1] @__components__[index + 1] = child moveChildBackward = (child) -> index = @indexOf(child) return if index is -1 or index is 0 @__components__[index] = @__components__[index - 1] @__components__[index - 1] = child moveChildToFront = (child) -> index = @indexOf(child) return if index is -1 or (index is @size() - 1) head = @__components__.splice(0, index) tail = @__components__.splice(1) @__components__ = head.concat(tail, @__components__) moveChildToBack = (child) -> index = @indexOf(child) return if index is -1 or index is 0 head = @__components__.splice(0, index) tail = @__components__.splice(1) @__components__ = @__components__.concat(head, tail) class Container extends Component constructor: (type) -> super(type) dispose: -> if @__components__ children = dou.util.clone(@__components__) for component in children component.dispose() @__components__ = null super() add: add remove: remove size: size getAt: getAt indexOf: indexOf forEach: forEach moveChildAt: moveChildAt moveChildForward: moveChildForward moveChildBackward: moveChildBackward moveChildToFront: moveChildToFront moveChildToBack: moveChildToBack Container
47221
# ========================================== # Copyright 2014 <NAME>, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' './Component' ], ( dou Component ) -> "use strict" EMPTY = [] add_component = (container, component) -> containable = component instanceof Component if containable oldContainer = component.getContainer() if oldContainer return if container is oldContainer remove_component(container, component) index = (container.__components__.push component) - 1 component.setContainer(container) if containable container.trigger 'add', container, component, index return if not containable component.delegate_on container component.trigger 'added', container, component, index remove_component = (container, component) -> containable = component instanceof Component idx = container.__components__.indexOf component return if idx is -1 container.__components__.splice(idx, 1) if idx > -1 component.setContainer(null) if containable container.trigger 'remove', container, component return if not (component instanceof Component) component.trigger 'removed', container, component component.delegate_off container add = (comp) -> @__components__ || @__components__ = [] return add.call(this, [comp]) if not (comp instanceof Array) add_component(this, i) for i in comp if @__components__.indexOf(i) is -1 this remove = (comp) -> return remove.call(this, [comp]) if not (comp instanceof Array) return if not @__components__ for i in comp remove_component this, i this getAt = (index) -> return @__components__[index] if @__components__ forEach = (fn, context) -> return if not @__components__ @__components__.forEach(fn, context) indexOf = (item) -> (@__components__ || EMPTY).indexOf(item) size = -> (@__components__ || EMPTY).length moveChildAt = (index, child) -> oldIndex = @indexOf(child) return if oldIndex is -1 head = @__components__.splice(0, oldIndex) tail = @__components__.splice(1) @__components__ = head.concat(tail) index = Math.max(0, index) index = Math.min(index, @__components__.length) head = @__components__.splice(0, index) @__components__ = head.concat(child, @__components__) moveChildForward = (child) -> index = @indexOf(child) return if (index is -1) or (index is @size() - 1) @__components__[index] = @__components__[index + 1] @__components__[index + 1] = child moveChildBackward = (child) -> index = @indexOf(child) return if index is -1 or index is 0 @__components__[index] = @__components__[index - 1] @__components__[index - 1] = child moveChildToFront = (child) -> index = @indexOf(child) return if index is -1 or (index is @size() - 1) head = @__components__.splice(0, index) tail = @__components__.splice(1) @__components__ = head.concat(tail, @__components__) moveChildToBack = (child) -> index = @indexOf(child) return if index is -1 or index is 0 head = @__components__.splice(0, index) tail = @__components__.splice(1) @__components__ = @__components__.concat(head, tail) class Container extends Component constructor: (type) -> super(type) dispose: -> if @__components__ children = dou.util.clone(@__components__) for component in children component.dispose() @__components__ = null super() add: add remove: remove size: size getAt: getAt indexOf: indexOf forEach: forEach moveChildAt: moveChildAt moveChildForward: moveChildForward moveChildBackward: moveChildBackward moveChildToFront: moveChildToFront moveChildToBack: moveChildToBack Container
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PI, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' './Component' ], ( dou Component ) -> "use strict" EMPTY = [] add_component = (container, component) -> containable = component instanceof Component if containable oldContainer = component.getContainer() if oldContainer return if container is oldContainer remove_component(container, component) index = (container.__components__.push component) - 1 component.setContainer(container) if containable container.trigger 'add', container, component, index return if not containable component.delegate_on container component.trigger 'added', container, component, index remove_component = (container, component) -> containable = component instanceof Component idx = container.__components__.indexOf component return if idx is -1 container.__components__.splice(idx, 1) if idx > -1 component.setContainer(null) if containable container.trigger 'remove', container, component return if not (component instanceof Component) component.trigger 'removed', container, component component.delegate_off container add = (comp) -> @__components__ || @__components__ = [] return add.call(this, [comp]) if not (comp instanceof Array) add_component(this, i) for i in comp if @__components__.indexOf(i) is -1 this remove = (comp) -> return remove.call(this, [comp]) if not (comp instanceof Array) return if not @__components__ for i in comp remove_component this, i this getAt = (index) -> return @__components__[index] if @__components__ forEach = (fn, context) -> return if not @__components__ @__components__.forEach(fn, context) indexOf = (item) -> (@__components__ || EMPTY).indexOf(item) size = -> (@__components__ || EMPTY).length moveChildAt = (index, child) -> oldIndex = @indexOf(child) return if oldIndex is -1 head = @__components__.splice(0, oldIndex) tail = @__components__.splice(1) @__components__ = head.concat(tail) index = Math.max(0, index) index = Math.min(index, @__components__.length) head = @__components__.splice(0, index) @__components__ = head.concat(child, @__components__) moveChildForward = (child) -> index = @indexOf(child) return if (index is -1) or (index is @size() - 1) @__components__[index] = @__components__[index + 1] @__components__[index + 1] = child moveChildBackward = (child) -> index = @indexOf(child) return if index is -1 or index is 0 @__components__[index] = @__components__[index - 1] @__components__[index - 1] = child moveChildToFront = (child) -> index = @indexOf(child) return if index is -1 or (index is @size() - 1) head = @__components__.splice(0, index) tail = @__components__.splice(1) @__components__ = head.concat(tail, @__components__) moveChildToBack = (child) -> index = @indexOf(child) return if index is -1 or index is 0 head = @__components__.splice(0, index) tail = @__components__.splice(1) @__components__ = @__components__.concat(head, tail) class Container extends Component constructor: (type) -> super(type) dispose: -> if @__components__ children = dou.util.clone(@__components__) for component in children component.dispose() @__components__ = null super() add: add remove: remove size: size getAt: getAt indexOf: indexOf forEach: forEach moveChildAt: moveChildAt moveChildForward: moveChildForward moveChildBackward: moveChildBackward moveChildToFront: moveChildToFront moveChildToBack: moveChildToBack Container
[ { "context": "t message', () ->\n expect(validator_default 'test@example.com').toBeUndefined()\n expect(validator_colon 't", "end": 451, "score": 0.9999179840087891, "start": 435, "tag": "EMAIL", "value": "test@example.com" }, { "context": "m').toBeUndefined()\n expect(validator_colon 'test@example.com').toBeUndefined()\n expect(validator_default ", "end": 516, "score": 0.9999185800552368, "start": 500, "tag": "EMAIL", "value": "test@example.com" }, { "context": "n message', () ->\n expect(validator_message 'test@example.com').toBeUndefined()\n expect(validator_message ", "end": 739, "score": 0.9999163746833801, "start": 723, "tag": "EMAIL", "value": "test@example.com" }, { "context": "t message', () ->\n expect(validator_default 'test@example.com;other@example.com').toBeUndefined()\n expect(", "end": 983, "score": 0.9999212026596069, "start": 967, "tag": "EMAIL", "value": "test@example.com" }, { "context": "\n expect(validator_default 'test@example.com;other@example.com').toBeUndefined()\n expect(validator_colon 't", "end": 1001, "score": 0.9999191164970398, "start": 984, "tag": "EMAIL", "value": "other@example.com" }, { "context": "m').toBeUndefined()\n expect(validator_colon 'test@example.com,other@example.com').toBeUndefined()\n expect(", "end": 1066, "score": 0.9999205470085144, "start": 1050, "tag": "EMAIL", "value": "test@example.com" }, { "context": "()\n expect(validator_colon 'test@example.com,other@example.com').toBeUndefined()\n expect(validator_default ", "end": 1084, "score": 0.9999204874038696, "start": 1067, "tag": "EMAIL", "value": "other@example.com" }, { "context": ").toBeUndefined()\n expect(validator_default 'test@example.com;test@example').toEqual type: 'email', message: Ba", "end": 1151, "score": 0.9999086260795593, "start": 1135, "tag": "EMAIL", "value": "test@example.com" }, { "context": "n message', () ->\n expect(validator_message 'test@example.com;other@example.com').toBeUndefined()\n expect(", "end": 1324, "score": 0.9999212026596069, "start": 1308, "tag": "EMAIL", "value": "test@example.com" }, { "context": "\n expect(validator_message 'test@example.com;other@example.com').toBeUndefined()\n expect(validator_message ", "end": 1342, "score": 0.9999223947525024, "start": 1325, "tag": "EMAIL", "value": "other@example.com" }, { "context": ").toBeUndefined()\n expect(validator_message 'test@example.com;test@example').toEqual type: 'email', message: 'I", "end": 1409, "score": 0.9999167323112488, "start": 1393, "tag": "EMAIL", "value": "test@example.com" }, { "context": " expect(validator_message 'test@example.com;test@example').toEqual type: 'email', message: 'Invalid'\n", "end": 1422, "score": 0.7019022703170776, "start": 1415, "tag": "EMAIL", "value": "example" } ]
spec/multiple.spec.coffee
tomi77/backbone-forms-validators
0
describe 'A multiple validator', () -> validator_default = Backbone.Form.validators.multiple base_type: 'email' validator_colon = Backbone.Form.validators.multiple base_type: 'email' separator: ',' validator_message = Backbone.Form.validators.multiple base_type: 'email' message: 'Invalid' describe 'should handle single value', () -> it 'with default message', () -> expect(validator_default 'test@example.com').toBeUndefined() expect(validator_colon 'test@example.com').toBeUndefined() expect(validator_default 'test@example').toEqual type: 'email', message: Backbone.Form.validators.errMessages.email it 'with own message', () -> expect(validator_message 'test@example.com').toBeUndefined() expect(validator_message 'test@example').toEqual type: 'email', message: 'Invalid' describe 'should handle multiple values', () -> it 'with default message', () -> expect(validator_default 'test@example.com;other@example.com').toBeUndefined() expect(validator_colon 'test@example.com,other@example.com').toBeUndefined() expect(validator_default 'test@example.com;test@example').toEqual type: 'email', message: Backbone.Form.validators.errMessages.email it 'with own message', () -> expect(validator_message 'test@example.com;other@example.com').toBeUndefined() expect(validator_message 'test@example.com;test@example').toEqual type: 'email', message: 'Invalid'
163739
describe 'A multiple validator', () -> validator_default = Backbone.Form.validators.multiple base_type: 'email' validator_colon = Backbone.Form.validators.multiple base_type: 'email' separator: ',' validator_message = Backbone.Form.validators.multiple base_type: 'email' message: 'Invalid' describe 'should handle single value', () -> it 'with default message', () -> expect(validator_default '<EMAIL>').toBeUndefined() expect(validator_colon '<EMAIL>').toBeUndefined() expect(validator_default 'test@example').toEqual type: 'email', message: Backbone.Form.validators.errMessages.email it 'with own message', () -> expect(validator_message '<EMAIL>').toBeUndefined() expect(validator_message 'test@example').toEqual type: 'email', message: 'Invalid' describe 'should handle multiple values', () -> it 'with default message', () -> expect(validator_default '<EMAIL>;<EMAIL>').toBeUndefined() expect(validator_colon '<EMAIL>,<EMAIL>').toBeUndefined() expect(validator_default '<EMAIL>;test@example').toEqual type: 'email', message: Backbone.Form.validators.errMessages.email it 'with own message', () -> expect(validator_message '<EMAIL>;<EMAIL>').toBeUndefined() expect(validator_message '<EMAIL>;test@<EMAIL>').toEqual type: 'email', message: 'Invalid'
true
describe 'A multiple validator', () -> validator_default = Backbone.Form.validators.multiple base_type: 'email' validator_colon = Backbone.Form.validators.multiple base_type: 'email' separator: ',' validator_message = Backbone.Form.validators.multiple base_type: 'email' message: 'Invalid' describe 'should handle single value', () -> it 'with default message', () -> expect(validator_default 'PI:EMAIL:<EMAIL>END_PI').toBeUndefined() expect(validator_colon 'PI:EMAIL:<EMAIL>END_PI').toBeUndefined() expect(validator_default 'test@example').toEqual type: 'email', message: Backbone.Form.validators.errMessages.email it 'with own message', () -> expect(validator_message 'PI:EMAIL:<EMAIL>END_PI').toBeUndefined() expect(validator_message 'test@example').toEqual type: 'email', message: 'Invalid' describe 'should handle multiple values', () -> it 'with default message', () -> expect(validator_default 'PI:EMAIL:<EMAIL>END_PI;PI:EMAIL:<EMAIL>END_PI').toBeUndefined() expect(validator_colon 'PI:EMAIL:<EMAIL>END_PI,PI:EMAIL:<EMAIL>END_PI').toBeUndefined() expect(validator_default 'PI:EMAIL:<EMAIL>END_PI;test@example').toEqual type: 'email', message: Backbone.Form.validators.errMessages.email it 'with own message', () -> expect(validator_message 'PI:EMAIL:<EMAIL>END_PI;PI:EMAIL:<EMAIL>END_PI').toBeUndefined() expect(validator_message 'PI:EMAIL:<EMAIL>END_PI;test@PI:EMAIL:<EMAIL>END_PI').toEqual type: 'email', message: 'Invalid'
[ { "context": " base_url: @state.currentBaseUrl\n username: @state.currentUsername\n password: @state.currentPass", "end": 691, "score": 0.7041974067687988, "start": 685, "tag": "USERNAME", "value": "@state" }, { "context": "tate.currentBaseUrl\n username: @state.currentUsername\n password: @state.currentPassword\n )\n ", "end": 707, "score": 0.8811472058296204, "start": 699, "tag": "USERNAME", "value": "Username" }, { "context": " username: @state.currentUsername\n password: @state.currentPassword\n )\n @submitPasswords(passwords, (=> @setSta", "end": 746, "score": 0.9977096319198608, "start": 724, "tag": "PASSWORD", "value": "@state.currentPassword" }, { "context": "className: 'username',\n input name: 'username', placeholder: 'alice', value: state.currentUsern", "end": 2538, "score": 0.9934045076370239, "start": 2530, "tag": "USERNAME", "value": "username" }, { "context": " input name: 'username', placeholder: 'alice', value: state.currentUsername, onChange: ((e) =>", "end": 2560, "score": 0.9989306926727295, "start": 2555, "tag": "USERNAME", "value": "alice" } ]
app/assets/javascripts/1-components/password_list.js.coffee
quark-zju/gerrit-frontend
2
{div, span, table, code, tbody, thead, tr, th, td, i, input, li, ul, p, pre, br, button} = React.DOM cx = React.addons.classSet @PasswordList = React.createClass displayName: 'PasswordList' getInitialState: -> passwords: @props.initialPasswords busy: false isBaseUrlIllegal: -> url = @state.currentBaseUrl || '' return false if url == '' !url.match(/^https?:\/\/[^.]+\.[^.]+/i) || _.find(@state.passwords, (x) -> x.base_url == url) handleAddButtonClick: -> return if @isBaseUrlIllegal() || (@state.currentBaseUrl || '').length == 0 passwords = _.clone(@state.passwords) passwords.push( base_url: @state.currentBaseUrl username: @state.currentUsername password: @state.currentPassword ) @submitPasswords(passwords, (=> @setState {passwords, currentUsername: '', currentBaseUrl: '', currentPassword: ''})) handleRemoveButtonClick: (baseUrl) -> passwords = _.reject(_.clone(@state.passwords), (x) -> x.base_url == baseUrl) @submitPasswords(passwords, (=> @setState {passwords})) submitPasswords: (passwords, onSuccess, onError) -> return if @state.busy @setState busy: true $.post( Routes.passwords_path(), passwords: passwords ).done((data)-> onSuccess(data) if onSuccess ).fail((data)-> alert('Cannot save passwords. Please try again later.') onError(data) if onError ).always( => @setState busy: false ) render: -> state = @state illegalBaseUrl = @isBaseUrlIllegal() div className: 'passwordList', table className: 'passwordTable', thead null, th null, 'Base URL' th null, 'Username' th null, 'Password' th null tbody null, state.passwords.map (x, y) => tr key: y, className: 'passwordItem', td className: 'baseUrl', x.base_url td className: 'username', x.username td className: 'password', '<hidden>' td className: 'actions', button className: 'removeButton', disabled: state.busy, onClick: @handleRemoveButtonClick.bind(this, x.base_url), '-' tr key: 'new', className: 'passwordItem', td className: 'baseUrl', input className: cx(illegal: illegalBaseUrl), name: 'base_url', placeholder: 'https://gerrit.example.com', value: state.currentBaseUrl, onChange: ((e) => @setState currentBaseUrl: e.target.value) td className: 'username', input name: 'username', placeholder: 'alice', value: state.currentUsername, onChange: ((e) => @setState currentUsername: e.target.value) td className: 'password', input name: 'password', value: state.currentPassword, onChange: ((e) => @setState currentPassword: e.target.value) td className: 'actions', button className: 'addButton', disabled: illegalBaseUrl || state.busy || (state.currentBaseUrl || '').length == 0, onClick: @handleAddButtonClick, '+'
76597
{div, span, table, code, tbody, thead, tr, th, td, i, input, li, ul, p, pre, br, button} = React.DOM cx = React.addons.classSet @PasswordList = React.createClass displayName: 'PasswordList' getInitialState: -> passwords: @props.initialPasswords busy: false isBaseUrlIllegal: -> url = @state.currentBaseUrl || '' return false if url == '' !url.match(/^https?:\/\/[^.]+\.[^.]+/i) || _.find(@state.passwords, (x) -> x.base_url == url) handleAddButtonClick: -> return if @isBaseUrlIllegal() || (@state.currentBaseUrl || '').length == 0 passwords = _.clone(@state.passwords) passwords.push( base_url: @state.currentBaseUrl username: @state.currentUsername password: <PASSWORD> ) @submitPasswords(passwords, (=> @setState {passwords, currentUsername: '', currentBaseUrl: '', currentPassword: ''})) handleRemoveButtonClick: (baseUrl) -> passwords = _.reject(_.clone(@state.passwords), (x) -> x.base_url == baseUrl) @submitPasswords(passwords, (=> @setState {passwords})) submitPasswords: (passwords, onSuccess, onError) -> return if @state.busy @setState busy: true $.post( Routes.passwords_path(), passwords: passwords ).done((data)-> onSuccess(data) if onSuccess ).fail((data)-> alert('Cannot save passwords. Please try again later.') onError(data) if onError ).always( => @setState busy: false ) render: -> state = @state illegalBaseUrl = @isBaseUrlIllegal() div className: 'passwordList', table className: 'passwordTable', thead null, th null, 'Base URL' th null, 'Username' th null, 'Password' th null tbody null, state.passwords.map (x, y) => tr key: y, className: 'passwordItem', td className: 'baseUrl', x.base_url td className: 'username', x.username td className: 'password', '<hidden>' td className: 'actions', button className: 'removeButton', disabled: state.busy, onClick: @handleRemoveButtonClick.bind(this, x.base_url), '-' tr key: 'new', className: 'passwordItem', td className: 'baseUrl', input className: cx(illegal: illegalBaseUrl), name: 'base_url', placeholder: 'https://gerrit.example.com', value: state.currentBaseUrl, onChange: ((e) => @setState currentBaseUrl: e.target.value) td className: 'username', input name: 'username', placeholder: 'alice', value: state.currentUsername, onChange: ((e) => @setState currentUsername: e.target.value) td className: 'password', input name: 'password', value: state.currentPassword, onChange: ((e) => @setState currentPassword: e.target.value) td className: 'actions', button className: 'addButton', disabled: illegalBaseUrl || state.busy || (state.currentBaseUrl || '').length == 0, onClick: @handleAddButtonClick, '+'
true
{div, span, table, code, tbody, thead, tr, th, td, i, input, li, ul, p, pre, br, button} = React.DOM cx = React.addons.classSet @PasswordList = React.createClass displayName: 'PasswordList' getInitialState: -> passwords: @props.initialPasswords busy: false isBaseUrlIllegal: -> url = @state.currentBaseUrl || '' return false if url == '' !url.match(/^https?:\/\/[^.]+\.[^.]+/i) || _.find(@state.passwords, (x) -> x.base_url == url) handleAddButtonClick: -> return if @isBaseUrlIllegal() || (@state.currentBaseUrl || '').length == 0 passwords = _.clone(@state.passwords) passwords.push( base_url: @state.currentBaseUrl username: @state.currentUsername password: PI:PASSWORD:<PASSWORD>END_PI ) @submitPasswords(passwords, (=> @setState {passwords, currentUsername: '', currentBaseUrl: '', currentPassword: ''})) handleRemoveButtonClick: (baseUrl) -> passwords = _.reject(_.clone(@state.passwords), (x) -> x.base_url == baseUrl) @submitPasswords(passwords, (=> @setState {passwords})) submitPasswords: (passwords, onSuccess, onError) -> return if @state.busy @setState busy: true $.post( Routes.passwords_path(), passwords: passwords ).done((data)-> onSuccess(data) if onSuccess ).fail((data)-> alert('Cannot save passwords. Please try again later.') onError(data) if onError ).always( => @setState busy: false ) render: -> state = @state illegalBaseUrl = @isBaseUrlIllegal() div className: 'passwordList', table className: 'passwordTable', thead null, th null, 'Base URL' th null, 'Username' th null, 'Password' th null tbody null, state.passwords.map (x, y) => tr key: y, className: 'passwordItem', td className: 'baseUrl', x.base_url td className: 'username', x.username td className: 'password', '<hidden>' td className: 'actions', button className: 'removeButton', disabled: state.busy, onClick: @handleRemoveButtonClick.bind(this, x.base_url), '-' tr key: 'new', className: 'passwordItem', td className: 'baseUrl', input className: cx(illegal: illegalBaseUrl), name: 'base_url', placeholder: 'https://gerrit.example.com', value: state.currentBaseUrl, onChange: ((e) => @setState currentBaseUrl: e.target.value) td className: 'username', input name: 'username', placeholder: 'alice', value: state.currentUsername, onChange: ((e) => @setState currentUsername: e.target.value) td className: 'password', input name: 'password', value: state.currentPassword, onChange: ((e) => @setState currentPassword: e.target.value) td className: 'actions', button className: 'addButton', disabled: illegalBaseUrl || state.busy || (state.currentBaseUrl || '').length == 0, onClick: @handleAddButtonClick, '+'
[ { "context": "ct':{Project:Project}\n\t\t\t'../../models/User':{User:@User}\n\t\t\t\"./ProjectGetter\":@ProjectGetter\n\t\t\t'logger-s", "end": 1539, "score": 0.8278820514678955, "start": 1534, "tag": "USERNAME", "value": "@User" }, { "context": "an array case insenstive', (done)->\n\t\t\tuser_id = \"123jojoidns\"\n\t\t\tstubbedProject = {name:\"findThis\"}\n\t\t\tproject", "end": 12041, "score": 0.9994229078292847, "start": 12030, "tag": "USERNAME", "value": "123jojoidns" }, { "context": "ct which is not archived', (done)->\n\t\t\tuser_id = \"123jojoidns\"\n\t\t\tstubbedProject = {name:\"findThis\", _id:123313", "end": 12505, "score": 0.9994826912879944, "start": 12494, "tag": "USERNAME", "value": "123jojoidns" }, { "context": " collab projects as well', (done)->\n\t\t\tuser_id = \"123jojoidns\"\n\t\t\tstubbedProject = {name:\"findThis\"}\n\t\t\tproject", "end": 13083, "score": 0.9994942545890808, "start": 13072, "tag": "USERNAME", "value": "123jojoidns" }, { "context": "projects = {\n\t\t\t\towned: [{name:\"notThis\"}, {name:\"wellll\"}, {name:\"Noooo\"}]\n\t\t\t\treadAndWrite: [stubbedProj", "end": 13182, "score": 0.9977689981460571, "start": 13176, "tag": "NAME", "value": "wellll" }, { "context": "owned: [{name:\"notThis\"}, {name:\"wellll\"}, {name:\"Noooo\"}]\n\t\t\t\treadAndWrite: [stubbedProject]\n\t\t\t}\n\t\t\t@Pr", "end": 13198, "score": 0.9991219639778137, "start": 13193, "tag": "NAME", "value": "Noooo" } ]
test/UnitTests/coffee/Project/ProjectLocatorTests.coffee
HasanSanli/web-sharelatex
0
spies = require('chai-spies') chai = require('chai').use(spies) assert = require('chai').assert should = chai.should() modulePath = "../../../../app/js/Features/Project/ProjectLocator" SandboxedModule = require('sandboxed-module') sinon = require('sinon') Errors = require "../../../../app/js/Features/Errors/Errors" expect = require("chai").expect Project = class Project project = _id : "1234566", rootFolder:[] rootDoc = name:"rootDoc", _id:"das239djd" doc1 = name:"otherDoc.txt", _id:"dsad2ddd" doc2 = name:"docname.txt", _id:"dsad2ddddd" file1 = name:"file1", _id:"dsa9lkdsad" subSubFile = name:"subSubFile", _id:"d1d2dk" subSubDoc = name:"subdoc.txt", _id:"321dmdwi" secondSubFolder = name:"secondSubFolder", _id:"dsa3e23", docs:[subSubDoc], fileRefs:[subSubFile], folders:[] subFolder = name:"subFolder", _id:"dsadsa93", folders:[secondSubFolder, null], docs:[], fileRefs:[] subFolder1 = name:"subFolder1", _id:"123asdjoij" rootFolder = _id : "123sdskd" docs:[doc1, doc2, null, rootDoc] fileRefs:[file1] folders:[subFolder1, subFolder] project.rootFolder[0] = rootFolder project.rootDoc_id = rootDoc._id describe 'ProjectLocator', -> beforeEach -> Project.getProject = (project_id, fields, callback)=> callback(null, project) Project.findById = (project_id, callback)=> callback(null, project) @ProjectGetter = getProject: sinon.stub().callsArgWith(2, null, project) @locator = SandboxedModule.require modulePath, requires: '../../models/Project':{Project:Project} '../../models/User':{User:@User} "./ProjectGetter":@ProjectGetter 'logger-sharelatex': log:-> err:-> warn: -> describe 'finding a doc', -> it 'finds one at the root level', (done)-> @locator.findElement {project_id:project._id, element_id:doc2._id, type:"docs"}, (err, foundElement, path, parentFolder)-> assert(!err?) foundElement._id.should.equal doc2._id path.fileSystem.should.equal "/#{doc2.name}" parentFolder._id.should.equal project.rootFolder[0]._id path.mongo.should.equal "rootFolder.0.docs.1" done() it 'when it is nested', (done)-> @locator.findElement {project_id:project._id, element_id:subSubDoc._id, type:"doc"}, (err, foundElement, path, parentFolder)-> assert(!err?) should.equal foundElement._id, subSubDoc._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}/#{subSubDoc.name}" parentFolder._id.should.equal secondSubFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0.docs.0" done() it 'should give error if element could not be found', (done)-> @locator.findElement {project_id:project._id, element_id:"ddsd432nj42", type:"docs"}, (err, foundElement, path, parentFolder)-> err.should.deep.equal new Errors.NotFoundError("entity not found") done() describe 'finding a folder', -> it 'should return root folder when looking for root folder', (done)-> @locator.findElement {project_id:project._id, element_id:rootFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal rootFolder._id done() it 'when at root', (done)-> @locator.findElement {project_id:project._id, element_id:subFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subFolder._id path.fileSystem.should.equal "/#{subFolder.name}" parentFolder._id.should.equal rootFolder._id path.mongo.should.equal "rootFolder.0.folders.1" done() it 'when deeply nested', (done)-> @locator.findElement {project_id:project._id, element_id:secondSubFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal secondSubFolder._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}" parentFolder._id.should.equal subFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0" done() describe 'finding a file', -> it 'when at root', (done)-> @locator.findElement {project_id:project._id, element_id:file1._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal file1._id path.fileSystem.should.equal "/#{file1.name}" parentFolder._id.should.equal rootFolder._id path.mongo.should.equal "rootFolder.0.fileRefs.0" done() it 'when deeply nested', (done)-> @locator.findElement {project_id:project._id, element_id:subSubFile._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subSubFile._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}/#{subSubFile.name}" parentFolder._id.should.equal secondSubFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0.fileRefs.0" done() describe 'finding an element with wrong element type', -> it 'should add an s onto the element type', (done)-> @locator.findElement {project_id:project._id, element_id:subSubDoc._id, type:"doc"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subSubDoc._id done() it 'should convert file to fileRefs', (done)-> @locator.findElement {project_id:project._id, element_id:file1._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal file1._id done() describe 'should be able to take actual project as well as id', -> doc3 = _id:"123dsdj3" name:"doc3" rootFolder2 = _id : "123sddedskd" docs:[doc3] project2 = _id : "1234566" rootFolder:[rootFolder2] it 'should find doc in project', (done)-> @locator.findElement {project:project2, element_id:doc3._id, type:"docs"}, (err, foundElement, path, parentFolder)-> assert(!err?) foundElement._id.should.equal doc3._id path.fileSystem.should.equal "/#{doc3.name}" parentFolder._id.should.equal project2.rootFolder[0]._id path.mongo.should.equal "rootFolder.0.docs.0" done() describe 'finding root doc', -> it 'should return root doc when passed project', (done)-> @locator.findRootDoc project, (err, doc)-> assert !err? doc._id.should.equal rootDoc._id done() it 'should return root doc when passed project_id', (done)-> @locator.findRootDoc project._id, (err, doc)-> assert !err? doc._id.should.equal rootDoc._id done() it 'should return null when the project has no rootDoc', (done) -> project.rootDoc_id = null @locator.findRootDoc project, (err, doc)-> assert !err? expect(doc).to.equal null done() it 'should return null when the rootDoc_id no longer exists', (done) -> project.rootDoc_id = "doesntexist" @locator.findRootDoc project, (err, doc)-> assert !err? expect(doc).to.equal null done() describe 'findElementByPath', -> it 'should take a doc path and return the element for a root level document', (done)-> path = "#{doc1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal doc1 expect(type).to.equal "doc" done() it 'should take a doc path and return the element for a root level document with a starting slash', (done)-> path = "/#{doc1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal doc1 expect(type).to.equal "doc" done() it 'should take a doc path and return the element for a nested document', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}/#{subSubDoc.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubDoc expect(type).to.equal "doc" done() it 'should take a file path and return the element for a root level document', (done)-> path = "#{file1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal file1 expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested document', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}/#{subSubFile.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubFile expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested document case insenstive', (done)-> path = "#{subFolder.name.toUpperCase()}/#{secondSubFolder.name.toUpperCase()}/#{subSubFile.name.toUpperCase()}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubFile expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested folder', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal secondSubFolder expect(type).to.equal "folder" done() it 'should take a file path and return the root folder', (done)-> @locator.findElementByPath project._id, "/", (err, element, type)-> element.should.deep.equal rootFolder expect(type).to.equal "folder" done() it 'should return an error if the file can not be found inside know folder', (done)-> @locator.findElementByPath project._id, "#{subFolder.name}/#{secondSubFolder.name}/exist.txt", (err, element, type)-> err.should.not.equal undefined assert.equal element, undefined expect(type).to.be.undefined done() it 'should return an error if the file can not be found inside unknown folder', (done)-> @locator.findElementByPath project._id, "this/does/not/exist.txt", (err, element, type)-> err.should.not.equal undefined assert.equal element, undefined expect(type).to.be.undefined done() describe "where duplicate folder exists", -> beforeEach -> @duplicateFolder = {name:"duplicate1", _id:"1234", folders:[{ name: "1" docs:[{name:"main.tex", _id:"456"}] folders: [] fileRefs: [] }], docs:[@doc = {name:"main.tex", _id:"456"}], fileRefs:[]} @project = rootFolder:[ folders: [@duplicateFolder, @duplicateFolder] fileRefs: [] docs: [] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null, @project) it "should not call the callback more than once", (done)-> @locator.findElementByPath project._id, "#{@duplicateFolder.name}/#{@doc.name}", -> done() #mocha will throw exception if done called multiple times it "should not call the callback more than once when the path is longer than 1 level below the duplicate level", (done)-> @locator.findElementByPath project._id, "#{@duplicateFolder.name}/1/main.tex", -> done() #mocha will throw exception if done called multiple times describe "with a null doc", -> beforeEach -> @project = rootFolder:[ folders: [] fileRefs: [] docs: [{name:"main.tex"}, null, {name:"other.tex"}] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null, @project) it "should not crash with a null", (done)-> callback = sinon.stub() @locator.findElementByPath project._id, "/other.tex", (err, element)-> element.name.should.equal "other.tex" done() describe "with a null project", -> beforeEach -> @project = rootFolder:[ folders: [] fileRefs: [] docs: [{name:"main.tex"}, null, {name:"other.tex"}] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null) it "should not crash with a null", (done)-> callback = sinon.stub() @locator.findElementByPath project._id, "/other.tex", (err, element)-> expect(err).to.exist done() describe 'findUsersProjectByName finding a project by user_id and project name', ()-> it 'should return the project from an array case insenstive', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis"} projects = { owned: [{name:"notThis"}, {name:"wellll"}, stubbedProject, {name:"Noooo"}] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project.should.equal stubbedProject done() it 'should return the project which is not archived', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis", _id:12331321} projects = { owned: [ {name:"notThis"}, {name:"wellll"}, {name:"findThis",archived:true}, stubbedProject, {name:"findThis",archived:true}, {name:"Noooo"} ] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project._id.should.equal stubbedProject._id done() it 'should search collab projects as well', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis"} projects = { owned: [{name:"notThis"}, {name:"wellll"}, {name:"Noooo"}] readAndWrite: [stubbedProject] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project.should.equal stubbedProject done()
160723
spies = require('chai-spies') chai = require('chai').use(spies) assert = require('chai').assert should = chai.should() modulePath = "../../../../app/js/Features/Project/ProjectLocator" SandboxedModule = require('sandboxed-module') sinon = require('sinon') Errors = require "../../../../app/js/Features/Errors/Errors" expect = require("chai").expect Project = class Project project = _id : "1234566", rootFolder:[] rootDoc = name:"rootDoc", _id:"das239djd" doc1 = name:"otherDoc.txt", _id:"dsad2ddd" doc2 = name:"docname.txt", _id:"dsad2ddddd" file1 = name:"file1", _id:"dsa9lkdsad" subSubFile = name:"subSubFile", _id:"d1d2dk" subSubDoc = name:"subdoc.txt", _id:"321dmdwi" secondSubFolder = name:"secondSubFolder", _id:"dsa3e23", docs:[subSubDoc], fileRefs:[subSubFile], folders:[] subFolder = name:"subFolder", _id:"dsadsa93", folders:[secondSubFolder, null], docs:[], fileRefs:[] subFolder1 = name:"subFolder1", _id:"123asdjoij" rootFolder = _id : "123sdskd" docs:[doc1, doc2, null, rootDoc] fileRefs:[file1] folders:[subFolder1, subFolder] project.rootFolder[0] = rootFolder project.rootDoc_id = rootDoc._id describe 'ProjectLocator', -> beforeEach -> Project.getProject = (project_id, fields, callback)=> callback(null, project) Project.findById = (project_id, callback)=> callback(null, project) @ProjectGetter = getProject: sinon.stub().callsArgWith(2, null, project) @locator = SandboxedModule.require modulePath, requires: '../../models/Project':{Project:Project} '../../models/User':{User:@User} "./ProjectGetter":@ProjectGetter 'logger-sharelatex': log:-> err:-> warn: -> describe 'finding a doc', -> it 'finds one at the root level', (done)-> @locator.findElement {project_id:project._id, element_id:doc2._id, type:"docs"}, (err, foundElement, path, parentFolder)-> assert(!err?) foundElement._id.should.equal doc2._id path.fileSystem.should.equal "/#{doc2.name}" parentFolder._id.should.equal project.rootFolder[0]._id path.mongo.should.equal "rootFolder.0.docs.1" done() it 'when it is nested', (done)-> @locator.findElement {project_id:project._id, element_id:subSubDoc._id, type:"doc"}, (err, foundElement, path, parentFolder)-> assert(!err?) should.equal foundElement._id, subSubDoc._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}/#{subSubDoc.name}" parentFolder._id.should.equal secondSubFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0.docs.0" done() it 'should give error if element could not be found', (done)-> @locator.findElement {project_id:project._id, element_id:"ddsd432nj42", type:"docs"}, (err, foundElement, path, parentFolder)-> err.should.deep.equal new Errors.NotFoundError("entity not found") done() describe 'finding a folder', -> it 'should return root folder when looking for root folder', (done)-> @locator.findElement {project_id:project._id, element_id:rootFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal rootFolder._id done() it 'when at root', (done)-> @locator.findElement {project_id:project._id, element_id:subFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subFolder._id path.fileSystem.should.equal "/#{subFolder.name}" parentFolder._id.should.equal rootFolder._id path.mongo.should.equal "rootFolder.0.folders.1" done() it 'when deeply nested', (done)-> @locator.findElement {project_id:project._id, element_id:secondSubFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal secondSubFolder._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}" parentFolder._id.should.equal subFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0" done() describe 'finding a file', -> it 'when at root', (done)-> @locator.findElement {project_id:project._id, element_id:file1._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal file1._id path.fileSystem.should.equal "/#{file1.name}" parentFolder._id.should.equal rootFolder._id path.mongo.should.equal "rootFolder.0.fileRefs.0" done() it 'when deeply nested', (done)-> @locator.findElement {project_id:project._id, element_id:subSubFile._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subSubFile._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}/#{subSubFile.name}" parentFolder._id.should.equal secondSubFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0.fileRefs.0" done() describe 'finding an element with wrong element type', -> it 'should add an s onto the element type', (done)-> @locator.findElement {project_id:project._id, element_id:subSubDoc._id, type:"doc"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subSubDoc._id done() it 'should convert file to fileRefs', (done)-> @locator.findElement {project_id:project._id, element_id:file1._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal file1._id done() describe 'should be able to take actual project as well as id', -> doc3 = _id:"123dsdj3" name:"doc3" rootFolder2 = _id : "123sddedskd" docs:[doc3] project2 = _id : "1234566" rootFolder:[rootFolder2] it 'should find doc in project', (done)-> @locator.findElement {project:project2, element_id:doc3._id, type:"docs"}, (err, foundElement, path, parentFolder)-> assert(!err?) foundElement._id.should.equal doc3._id path.fileSystem.should.equal "/#{doc3.name}" parentFolder._id.should.equal project2.rootFolder[0]._id path.mongo.should.equal "rootFolder.0.docs.0" done() describe 'finding root doc', -> it 'should return root doc when passed project', (done)-> @locator.findRootDoc project, (err, doc)-> assert !err? doc._id.should.equal rootDoc._id done() it 'should return root doc when passed project_id', (done)-> @locator.findRootDoc project._id, (err, doc)-> assert !err? doc._id.should.equal rootDoc._id done() it 'should return null when the project has no rootDoc', (done) -> project.rootDoc_id = null @locator.findRootDoc project, (err, doc)-> assert !err? expect(doc).to.equal null done() it 'should return null when the rootDoc_id no longer exists', (done) -> project.rootDoc_id = "doesntexist" @locator.findRootDoc project, (err, doc)-> assert !err? expect(doc).to.equal null done() describe 'findElementByPath', -> it 'should take a doc path and return the element for a root level document', (done)-> path = "#{doc1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal doc1 expect(type).to.equal "doc" done() it 'should take a doc path and return the element for a root level document with a starting slash', (done)-> path = "/#{doc1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal doc1 expect(type).to.equal "doc" done() it 'should take a doc path and return the element for a nested document', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}/#{subSubDoc.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubDoc expect(type).to.equal "doc" done() it 'should take a file path and return the element for a root level document', (done)-> path = "#{file1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal file1 expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested document', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}/#{subSubFile.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubFile expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested document case insenstive', (done)-> path = "#{subFolder.name.toUpperCase()}/#{secondSubFolder.name.toUpperCase()}/#{subSubFile.name.toUpperCase()}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubFile expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested folder', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal secondSubFolder expect(type).to.equal "folder" done() it 'should take a file path and return the root folder', (done)-> @locator.findElementByPath project._id, "/", (err, element, type)-> element.should.deep.equal rootFolder expect(type).to.equal "folder" done() it 'should return an error if the file can not be found inside know folder', (done)-> @locator.findElementByPath project._id, "#{subFolder.name}/#{secondSubFolder.name}/exist.txt", (err, element, type)-> err.should.not.equal undefined assert.equal element, undefined expect(type).to.be.undefined done() it 'should return an error if the file can not be found inside unknown folder', (done)-> @locator.findElementByPath project._id, "this/does/not/exist.txt", (err, element, type)-> err.should.not.equal undefined assert.equal element, undefined expect(type).to.be.undefined done() describe "where duplicate folder exists", -> beforeEach -> @duplicateFolder = {name:"duplicate1", _id:"1234", folders:[{ name: "1" docs:[{name:"main.tex", _id:"456"}] folders: [] fileRefs: [] }], docs:[@doc = {name:"main.tex", _id:"456"}], fileRefs:[]} @project = rootFolder:[ folders: [@duplicateFolder, @duplicateFolder] fileRefs: [] docs: [] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null, @project) it "should not call the callback more than once", (done)-> @locator.findElementByPath project._id, "#{@duplicateFolder.name}/#{@doc.name}", -> done() #mocha will throw exception if done called multiple times it "should not call the callback more than once when the path is longer than 1 level below the duplicate level", (done)-> @locator.findElementByPath project._id, "#{@duplicateFolder.name}/1/main.tex", -> done() #mocha will throw exception if done called multiple times describe "with a null doc", -> beforeEach -> @project = rootFolder:[ folders: [] fileRefs: [] docs: [{name:"main.tex"}, null, {name:"other.tex"}] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null, @project) it "should not crash with a null", (done)-> callback = sinon.stub() @locator.findElementByPath project._id, "/other.tex", (err, element)-> element.name.should.equal "other.tex" done() describe "with a null project", -> beforeEach -> @project = rootFolder:[ folders: [] fileRefs: [] docs: [{name:"main.tex"}, null, {name:"other.tex"}] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null) it "should not crash with a null", (done)-> callback = sinon.stub() @locator.findElementByPath project._id, "/other.tex", (err, element)-> expect(err).to.exist done() describe 'findUsersProjectByName finding a project by user_id and project name', ()-> it 'should return the project from an array case insenstive', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis"} projects = { owned: [{name:"notThis"}, {name:"wellll"}, stubbedProject, {name:"Noooo"}] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project.should.equal stubbedProject done() it 'should return the project which is not archived', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis", _id:12331321} projects = { owned: [ {name:"notThis"}, {name:"wellll"}, {name:"findThis",archived:true}, stubbedProject, {name:"findThis",archived:true}, {name:"Noooo"} ] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project._id.should.equal stubbedProject._id done() it 'should search collab projects as well', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis"} projects = { owned: [{name:"notThis"}, {name:"<NAME>"}, {name:"<NAME>"}] readAndWrite: [stubbedProject] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project.should.equal stubbedProject done()
true
spies = require('chai-spies') chai = require('chai').use(spies) assert = require('chai').assert should = chai.should() modulePath = "../../../../app/js/Features/Project/ProjectLocator" SandboxedModule = require('sandboxed-module') sinon = require('sinon') Errors = require "../../../../app/js/Features/Errors/Errors" expect = require("chai").expect Project = class Project project = _id : "1234566", rootFolder:[] rootDoc = name:"rootDoc", _id:"das239djd" doc1 = name:"otherDoc.txt", _id:"dsad2ddd" doc2 = name:"docname.txt", _id:"dsad2ddddd" file1 = name:"file1", _id:"dsa9lkdsad" subSubFile = name:"subSubFile", _id:"d1d2dk" subSubDoc = name:"subdoc.txt", _id:"321dmdwi" secondSubFolder = name:"secondSubFolder", _id:"dsa3e23", docs:[subSubDoc], fileRefs:[subSubFile], folders:[] subFolder = name:"subFolder", _id:"dsadsa93", folders:[secondSubFolder, null], docs:[], fileRefs:[] subFolder1 = name:"subFolder1", _id:"123asdjoij" rootFolder = _id : "123sdskd" docs:[doc1, doc2, null, rootDoc] fileRefs:[file1] folders:[subFolder1, subFolder] project.rootFolder[0] = rootFolder project.rootDoc_id = rootDoc._id describe 'ProjectLocator', -> beforeEach -> Project.getProject = (project_id, fields, callback)=> callback(null, project) Project.findById = (project_id, callback)=> callback(null, project) @ProjectGetter = getProject: sinon.stub().callsArgWith(2, null, project) @locator = SandboxedModule.require modulePath, requires: '../../models/Project':{Project:Project} '../../models/User':{User:@User} "./ProjectGetter":@ProjectGetter 'logger-sharelatex': log:-> err:-> warn: -> describe 'finding a doc', -> it 'finds one at the root level', (done)-> @locator.findElement {project_id:project._id, element_id:doc2._id, type:"docs"}, (err, foundElement, path, parentFolder)-> assert(!err?) foundElement._id.should.equal doc2._id path.fileSystem.should.equal "/#{doc2.name}" parentFolder._id.should.equal project.rootFolder[0]._id path.mongo.should.equal "rootFolder.0.docs.1" done() it 'when it is nested', (done)-> @locator.findElement {project_id:project._id, element_id:subSubDoc._id, type:"doc"}, (err, foundElement, path, parentFolder)-> assert(!err?) should.equal foundElement._id, subSubDoc._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}/#{subSubDoc.name}" parentFolder._id.should.equal secondSubFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0.docs.0" done() it 'should give error if element could not be found', (done)-> @locator.findElement {project_id:project._id, element_id:"ddsd432nj42", type:"docs"}, (err, foundElement, path, parentFolder)-> err.should.deep.equal new Errors.NotFoundError("entity not found") done() describe 'finding a folder', -> it 'should return root folder when looking for root folder', (done)-> @locator.findElement {project_id:project._id, element_id:rootFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal rootFolder._id done() it 'when at root', (done)-> @locator.findElement {project_id:project._id, element_id:subFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subFolder._id path.fileSystem.should.equal "/#{subFolder.name}" parentFolder._id.should.equal rootFolder._id path.mongo.should.equal "rootFolder.0.folders.1" done() it 'when deeply nested', (done)-> @locator.findElement {project_id:project._id, element_id:secondSubFolder._id, type:"folder"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal secondSubFolder._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}" parentFolder._id.should.equal subFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0" done() describe 'finding a file', -> it 'when at root', (done)-> @locator.findElement {project_id:project._id, element_id:file1._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal file1._id path.fileSystem.should.equal "/#{file1.name}" parentFolder._id.should.equal rootFolder._id path.mongo.should.equal "rootFolder.0.fileRefs.0" done() it 'when deeply nested', (done)-> @locator.findElement {project_id:project._id, element_id:subSubFile._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subSubFile._id path.fileSystem.should.equal "/#{subFolder.name}/#{secondSubFolder.name}/#{subSubFile.name}" parentFolder._id.should.equal secondSubFolder._id path.mongo.should.equal "rootFolder.0.folders.1.folders.0.fileRefs.0" done() describe 'finding an element with wrong element type', -> it 'should add an s onto the element type', (done)-> @locator.findElement {project_id:project._id, element_id:subSubDoc._id, type:"doc"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal subSubDoc._id done() it 'should convert file to fileRefs', (done)-> @locator.findElement {project_id:project._id, element_id:file1._id, type:"fileRefs"}, (err, foundElement, path, parentFolder)-> assert(!err) foundElement._id.should.equal file1._id done() describe 'should be able to take actual project as well as id', -> doc3 = _id:"123dsdj3" name:"doc3" rootFolder2 = _id : "123sddedskd" docs:[doc3] project2 = _id : "1234566" rootFolder:[rootFolder2] it 'should find doc in project', (done)-> @locator.findElement {project:project2, element_id:doc3._id, type:"docs"}, (err, foundElement, path, parentFolder)-> assert(!err?) foundElement._id.should.equal doc3._id path.fileSystem.should.equal "/#{doc3.name}" parentFolder._id.should.equal project2.rootFolder[0]._id path.mongo.should.equal "rootFolder.0.docs.0" done() describe 'finding root doc', -> it 'should return root doc when passed project', (done)-> @locator.findRootDoc project, (err, doc)-> assert !err? doc._id.should.equal rootDoc._id done() it 'should return root doc when passed project_id', (done)-> @locator.findRootDoc project._id, (err, doc)-> assert !err? doc._id.should.equal rootDoc._id done() it 'should return null when the project has no rootDoc', (done) -> project.rootDoc_id = null @locator.findRootDoc project, (err, doc)-> assert !err? expect(doc).to.equal null done() it 'should return null when the rootDoc_id no longer exists', (done) -> project.rootDoc_id = "doesntexist" @locator.findRootDoc project, (err, doc)-> assert !err? expect(doc).to.equal null done() describe 'findElementByPath', -> it 'should take a doc path and return the element for a root level document', (done)-> path = "#{doc1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal doc1 expect(type).to.equal "doc" done() it 'should take a doc path and return the element for a root level document with a starting slash', (done)-> path = "/#{doc1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal doc1 expect(type).to.equal "doc" done() it 'should take a doc path and return the element for a nested document', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}/#{subSubDoc.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubDoc expect(type).to.equal "doc" done() it 'should take a file path and return the element for a root level document', (done)-> path = "#{file1.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal file1 expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested document', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}/#{subSubFile.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubFile expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested document case insenstive', (done)-> path = "#{subFolder.name.toUpperCase()}/#{secondSubFolder.name.toUpperCase()}/#{subSubFile.name.toUpperCase()}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal subSubFile expect(type).to.equal "file" done() it 'should take a file path and return the element for a nested folder', (done)-> path = "#{subFolder.name}/#{secondSubFolder.name}" @locator.findElementByPath project._id, path, (err, element, type)-> element.should.deep.equal secondSubFolder expect(type).to.equal "folder" done() it 'should take a file path and return the root folder', (done)-> @locator.findElementByPath project._id, "/", (err, element, type)-> element.should.deep.equal rootFolder expect(type).to.equal "folder" done() it 'should return an error if the file can not be found inside know folder', (done)-> @locator.findElementByPath project._id, "#{subFolder.name}/#{secondSubFolder.name}/exist.txt", (err, element, type)-> err.should.not.equal undefined assert.equal element, undefined expect(type).to.be.undefined done() it 'should return an error if the file can not be found inside unknown folder', (done)-> @locator.findElementByPath project._id, "this/does/not/exist.txt", (err, element, type)-> err.should.not.equal undefined assert.equal element, undefined expect(type).to.be.undefined done() describe "where duplicate folder exists", -> beforeEach -> @duplicateFolder = {name:"duplicate1", _id:"1234", folders:[{ name: "1" docs:[{name:"main.tex", _id:"456"}] folders: [] fileRefs: [] }], docs:[@doc = {name:"main.tex", _id:"456"}], fileRefs:[]} @project = rootFolder:[ folders: [@duplicateFolder, @duplicateFolder] fileRefs: [] docs: [] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null, @project) it "should not call the callback more than once", (done)-> @locator.findElementByPath project._id, "#{@duplicateFolder.name}/#{@doc.name}", -> done() #mocha will throw exception if done called multiple times it "should not call the callback more than once when the path is longer than 1 level below the duplicate level", (done)-> @locator.findElementByPath project._id, "#{@duplicateFolder.name}/1/main.tex", -> done() #mocha will throw exception if done called multiple times describe "with a null doc", -> beforeEach -> @project = rootFolder:[ folders: [] fileRefs: [] docs: [{name:"main.tex"}, null, {name:"other.tex"}] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null, @project) it "should not crash with a null", (done)-> callback = sinon.stub() @locator.findElementByPath project._id, "/other.tex", (err, element)-> element.name.should.equal "other.tex" done() describe "with a null project", -> beforeEach -> @project = rootFolder:[ folders: [] fileRefs: [] docs: [{name:"main.tex"}, null, {name:"other.tex"}] ] Project.getProject = sinon.stub() Project.getProject.callsArgWith(2, null) it "should not crash with a null", (done)-> callback = sinon.stub() @locator.findElementByPath project._id, "/other.tex", (err, element)-> expect(err).to.exist done() describe 'findUsersProjectByName finding a project by user_id and project name', ()-> it 'should return the project from an array case insenstive', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis"} projects = { owned: [{name:"notThis"}, {name:"wellll"}, stubbedProject, {name:"Noooo"}] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project.should.equal stubbedProject done() it 'should return the project which is not archived', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis", _id:12331321} projects = { owned: [ {name:"notThis"}, {name:"wellll"}, {name:"findThis",archived:true}, stubbedProject, {name:"findThis",archived:true}, {name:"Noooo"} ] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project._id.should.equal stubbedProject._id done() it 'should search collab projects as well', (done)-> user_id = "123jojoidns" stubbedProject = {name:"findThis"} projects = { owned: [{name:"notThis"}, {name:"PI:NAME:<NAME>END_PI"}, {name:"PI:NAME:<NAME>END_PI"}] readAndWrite: [stubbedProject] } @ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, projects) @locator.findUsersProjectByName user_id, stubbedProject.name.toLowerCase(), (err, project)-> project.should.equal stubbedProject done()
[ { "context": "om/articulate/grunt-release\n#\n# Copyright (c) 2013 Andrew Nordman\n# Licensed under the MIT license.\n#\n\nexec = requi", "end": 101, "score": 0.9998394250869751, "start": 87, "tag": "NAME", "value": "Andrew Nordman" } ]
src/tasks/release.coffee
articulate/grunt-release
0
# # grunt-release # https://github.com/articulate/grunt-release # # Copyright (c) 2013 Andrew Nordman # Licensed under the MIT license. # exec = require('child_process').exec fs = require 'fs' path = require 'path' module.exports = (grunt) -> grunt.registerMultiTask 'release', 'Release a version of application', -> options = @options repo: 'articulate/grunt-release' remote: 'origin' branch: 'master' done = @async() determineVersion options updatePackage options generateChangelog options, -> versionBump options, (error) -> if error? done(false) else done() determineVersion = (options) -> unless grunt.option('currentVersion') version = grunt.file.readJSON('package.json')['version'] grunt.option('currentVersion', version) unless grunt.option('newVersion') [major, minor, patch] = grunt.option('currentVersion').split('.') if grunt.option('major')? major++ else if grunt.option('minor') minor++ else if grunt.option('patch') patch++ newVersion = "#{major}.#{minor}.#{patch}" grunt.option('newVersion', newVersion) generateChangelog = (options, callback) -> currentVersion = grunt.option('currentVersion') nextVersion = grunt.option('newVersion') range = "#{currentVersion}...HEAD" grunt.log.writeln "Generating CHANGELOG entry for #{nextVersion}..." format = '%s|||||%b' cmd = "git log #{range} --pretty='#{format}' --reverse --grep='pull request'" exec cmd, (error, stdout, stderr) -> date = new Date() changes = "## Authoring Tools #{nextVersion} (#{date.toDateString()})" + '\n\n' for line in stdout.split('\n') if line != '' [title, description] = line.split "|||||" pr_id = title.match(/request #(\d+)/)[1] changes += "* [##{pr_id} - #{description}](https://github.com/#{options.repo}/pull/#{pr_id})" + '\r\n' fs.readFile './CHANGELOG.md', (error, data) -> newLog = changes + '\n' + data fs.writeFile './CHANGELOG.md', newLog, (err) -> callback(null) updatePackage = () -> pkg = grunt.config('pkg') || grunt.file.readJSON('package.json') grunt.log.writeln "Updating package.json version to #{grunt.option('newVersion')}..." pkg.version = grunt.option('newVersion') grunt.file.write './package.json', JSON.stringify(pkg, undefined, 2) versionBump = (options, callback) -> commands = [ "git add package.json CHANGELOG.md" "git commit -m 'Version bump to v#{grunt.option('newVersion')}'" "git tag v#{grunt.option('newVersion')}" "git push #{options.remote} #{options.branch} --tags" ] grunt.log.writeln "Committing changes and pushing tag..." exec commands.join(" && "), (error, stdout, stderr) -> if error grunt.log.error stderr callback(error) else callback(null)
199581
# # grunt-release # https://github.com/articulate/grunt-release # # Copyright (c) 2013 <NAME> # Licensed under the MIT license. # exec = require('child_process').exec fs = require 'fs' path = require 'path' module.exports = (grunt) -> grunt.registerMultiTask 'release', 'Release a version of application', -> options = @options repo: 'articulate/grunt-release' remote: 'origin' branch: 'master' done = @async() determineVersion options updatePackage options generateChangelog options, -> versionBump options, (error) -> if error? done(false) else done() determineVersion = (options) -> unless grunt.option('currentVersion') version = grunt.file.readJSON('package.json')['version'] grunt.option('currentVersion', version) unless grunt.option('newVersion') [major, minor, patch] = grunt.option('currentVersion').split('.') if grunt.option('major')? major++ else if grunt.option('minor') minor++ else if grunt.option('patch') patch++ newVersion = "#{major}.#{minor}.#{patch}" grunt.option('newVersion', newVersion) generateChangelog = (options, callback) -> currentVersion = grunt.option('currentVersion') nextVersion = grunt.option('newVersion') range = "#{currentVersion}...HEAD" grunt.log.writeln "Generating CHANGELOG entry for #{nextVersion}..." format = '%s|||||%b' cmd = "git log #{range} --pretty='#{format}' --reverse --grep='pull request'" exec cmd, (error, stdout, stderr) -> date = new Date() changes = "## Authoring Tools #{nextVersion} (#{date.toDateString()})" + '\n\n' for line in stdout.split('\n') if line != '' [title, description] = line.split "|||||" pr_id = title.match(/request #(\d+)/)[1] changes += "* [##{pr_id} - #{description}](https://github.com/#{options.repo}/pull/#{pr_id})" + '\r\n' fs.readFile './CHANGELOG.md', (error, data) -> newLog = changes + '\n' + data fs.writeFile './CHANGELOG.md', newLog, (err) -> callback(null) updatePackage = () -> pkg = grunt.config('pkg') || grunt.file.readJSON('package.json') grunt.log.writeln "Updating package.json version to #{grunt.option('newVersion')}..." pkg.version = grunt.option('newVersion') grunt.file.write './package.json', JSON.stringify(pkg, undefined, 2) versionBump = (options, callback) -> commands = [ "git add package.json CHANGELOG.md" "git commit -m 'Version bump to v#{grunt.option('newVersion')}'" "git tag v#{grunt.option('newVersion')}" "git push #{options.remote} #{options.branch} --tags" ] grunt.log.writeln "Committing changes and pushing tag..." exec commands.join(" && "), (error, stdout, stderr) -> if error grunt.log.error stderr callback(error) else callback(null)
true
# # grunt-release # https://github.com/articulate/grunt-release # # Copyright (c) 2013 PI:NAME:<NAME>END_PI # Licensed under the MIT license. # exec = require('child_process').exec fs = require 'fs' path = require 'path' module.exports = (grunt) -> grunt.registerMultiTask 'release', 'Release a version of application', -> options = @options repo: 'articulate/grunt-release' remote: 'origin' branch: 'master' done = @async() determineVersion options updatePackage options generateChangelog options, -> versionBump options, (error) -> if error? done(false) else done() determineVersion = (options) -> unless grunt.option('currentVersion') version = grunt.file.readJSON('package.json')['version'] grunt.option('currentVersion', version) unless grunt.option('newVersion') [major, minor, patch] = grunt.option('currentVersion').split('.') if grunt.option('major')? major++ else if grunt.option('minor') minor++ else if grunt.option('patch') patch++ newVersion = "#{major}.#{minor}.#{patch}" grunt.option('newVersion', newVersion) generateChangelog = (options, callback) -> currentVersion = grunt.option('currentVersion') nextVersion = grunt.option('newVersion') range = "#{currentVersion}...HEAD" grunt.log.writeln "Generating CHANGELOG entry for #{nextVersion}..." format = '%s|||||%b' cmd = "git log #{range} --pretty='#{format}' --reverse --grep='pull request'" exec cmd, (error, stdout, stderr) -> date = new Date() changes = "## Authoring Tools #{nextVersion} (#{date.toDateString()})" + '\n\n' for line in stdout.split('\n') if line != '' [title, description] = line.split "|||||" pr_id = title.match(/request #(\d+)/)[1] changes += "* [##{pr_id} - #{description}](https://github.com/#{options.repo}/pull/#{pr_id})" + '\r\n' fs.readFile './CHANGELOG.md', (error, data) -> newLog = changes + '\n' + data fs.writeFile './CHANGELOG.md', newLog, (err) -> callback(null) updatePackage = () -> pkg = grunt.config('pkg') || grunt.file.readJSON('package.json') grunt.log.writeln "Updating package.json version to #{grunt.option('newVersion')}..." pkg.version = grunt.option('newVersion') grunt.file.write './package.json', JSON.stringify(pkg, undefined, 2) versionBump = (options, callback) -> commands = [ "git add package.json CHANGELOG.md" "git commit -m 'Version bump to v#{grunt.option('newVersion')}'" "git tag v#{grunt.option('newVersion')}" "git push #{options.remote} #{options.branch} --tags" ] grunt.log.writeln "Committing changes and pushing tag..." exec commands.join(" && "), (error, stdout, stderr) -> if error grunt.log.error stderr callback(error) else callback(null)
[ { "context": "# * http://foundation.zurb.com\n# * Copyright 2012, ZURB\n# * Free to use under the MIT license.\n# * http:/", "end": 165, "score": 0.9732481837272644, "start": 161, "tag": "NAME", "value": "ZURB" }, { "context": "control whether cookies are used\n cookieName: \"joyride\" # Name the cookie you'll use\n cookieDomai", "end": 1241, "score": 0.5761966705322266, "start": 1238, "tag": "USERNAME", "value": "joy" } ]
coffee/nextstep.coffee
alejo8591/shurikend
0
### Inspired in foundation v.3.2 joyride: joyride.coffee ### # # * jQuery Foundation Joyride Plugin 2.0.3 # * http://foundation.zurb.com # * Copyright 2012, ZURB # * Free to use under the MIT license. # * http://www.opensource.org/licenses/mit-license.php # #jslint unparam: true, browser: true, indent: 2 (($, window, undefined_) -> "use strict" defaults = version: "2.0.3" tipLocation: "bottom" # 'top' or 'bottom' in relation to parent nubPosition: "auto" # override on a per tooltip bases scrollSpeed: 300 # Page scrolling speed in milliseconds timer: 0 # 0 = no timer , all other numbers = timer in milliseconds startTimerOnClick: true # true or false - true requires clicking the first button start the timer startOffset: 0 # the index of the tooltip you want to start on (index of the li) nextButton: true # true or false to control whether a next button is used tipAnimation: "fade" # 'pop' or 'fade' in each tip pauseAfter: [] # array of indexes where to pause the tour after tipAnimationFadeSpeed: 300 # when tipAnimation = 'fade' this is speed in milliseconds for the transition cookieMonster: false # true or false to control whether cookies are used cookieName: "joyride" # Name the cookie you'll use cookieDomain: false # Will this cookie be attached to a domain, ie. '.notableapp.com' tipContainer: "body" # Where will the tip be attached postRideCallback: $.noop # A method to call once the tour closes (canceled or complete) postStepCallback: $.noop # A method to call after each step template: # HTML segments for tip layout link: "<a href=\"#close\" class=\"joyride-close-tip\">X</a>" timer: "<div class=\"joyride-timer-indicator-wrap\"><span class=\"joyride-timer-indicator\"></span></div>" tip: "<div class=\"joyride-tip-guide\"><span class=\"joyride-nub\"></span></div>" wrapper: "<div class=\"joyride-content-wrapper\"></div>" button: "<a href=\"#\" class=\"small button joyride-next-tip\"></a>" Modernizr = Modernizr or false settings = {} methods = init: (opts) -> @each -> if $.isEmptyObject(settings) settings = $.extend(true, defaults, opts) # non configurable settings settings.document = window.document settings.$document = $(settings.document) settings.$window = $(window) settings.$content_el = $(this) settings.body_offset = $(settings.tipContainer).position() settings.$tip_content = $("> li", settings.$content_el) settings.paused = false settings.attempts = 0 settings.tipLocationPatterns = top: ["bottom"] bottom: [] # bottom should not need to be repositioned left: ["right", "top", "bottom"] right: ["left", "top", "bottom"] # are we using jQuery 1.7+ methods.jquery_check() # can we create cookies? settings.cookieMonster = false unless $.isFunction($.cookie) # generate the tips and insert into dom. if not settings.cookieMonster or not $.cookie(settings.cookieName) settings.$tip_content.each (index) -> methods.create $li: $(this) index: index # show first tip if not settings.startTimerOnClick and settings.timer > 0 methods.show "init" methods.startTimer() else methods.show "init" settings.$document.on "click.joyride", ".joyride-next-tip, .joyride-modal-bg", (e) -> e.preventDefault() if settings.$li.next().length < 1 methods.end() else if settings.timer > 0 clearTimeout settings.automate methods.hide() methods.show() methods.startTimer() else methods.hide() methods.show() settings.$document.on "click.joyride", ".joyride-close-tip", (e) -> e.preventDefault() methods.end() settings.$window.bind "resize.joyride", (e) -> if methods.is_phone() methods.pos_phone() else methods.pos_default() else methods.restart() # call this method when you want to resume the tour resume: -> methods.set_li() methods.show() tip_template: (opts) -> $blank = undefined_ content = undefined_ opts.tip_class = opts.tip_class or "" $blank = $(settings.template.tip).addClass(opts.tip_class) content = $.trim($(opts.li).html()) + methods.button_text(opts.button_text) + settings.template.link + methods.timer_instance(opts.index) $blank.append $(settings.template.wrapper) $blank.first().attr "data-index", opts.index $(".joyride-content-wrapper", $blank).append content $blank[0] timer_instance: (index) -> txt = undefined_ if (index is 0 and settings.startTimerOnClick and settings.timer > 0) or settings.timer is 0 txt = "" else txt = methods.outerHTML($(settings.template.timer)[0]) txt button_text: (txt) -> if settings.nextButton txt = $.trim(txt) or "Next" txt = methods.outerHTML($(settings.template.button).append(txt)[0]) else txt = "" txt create: (opts) -> # backwards compatibility with data-text attribute buttonText = opts.$li.attr("data-button") or opts.$li.attr("data-text") tipClass = opts.$li.attr("class") $tip_content = $(methods.tip_template( tip_class: tipClass index: opts.index button_text: buttonText li: opts.$li )) $(settings.tipContainer).append $tip_content show: (init) -> opts = {} ii = undefined_ opts_arr = [] opts_len = 0 p = undefined_ $timer = null # are we paused? if settings.$li is `undefined` or ($.inArray(settings.$li.index(), settings.pauseAfter) is -1) # don't go to the next li if the tour was paused if settings.paused settings.paused = false else methods.set_li init settings.attempts = 0 if settings.$li.length and settings.$target.length > 0 opts_arr = (settings.$li.data("options") or ":").split(";") opts_len = opts_arr.length # parse options ii = opts_len - 1 while ii >= 0 p = opts_arr[ii].split(":") opts[$.trim(p[0])] = $.trim(p[1]) if p.length is 2 ii-- settings.tipSettings = $.extend({}, settings, opts) settings.tipSettings.tipLocationPattern = settings.tipLocationPatterns[settings.tipSettings.tipLocation] # scroll if not modal methods.scroll_to() unless /body/i.test(settings.$target.selector) if methods.is_phone() methods.pos_phone true else methods.pos_default true $timer = $(".joyride-timer-indicator", settings.$next_tip) if /pop/i.test(settings.tipAnimation) $timer.outerWidth 0 if settings.timer > 0 settings.$next_tip.show() $timer.animate width: $(".joyride-timer-indicator-wrap", settings.$next_tip).outerWidth() , settings.timer else settings.$next_tip.show() else if /fade/i.test(settings.tipAnimation) $timer.outerWidth 0 if settings.timer > 0 settings.$next_tip.fadeIn settings.tipAnimationFadeSpeed settings.$next_tip.show() $timer.animate width: $(".joyride-timer-indicator-wrap", settings.$next_tip).outerWidth() , settings.timer else settings.$next_tip.fadeIn settings.tipAnimationFadeSpeed settings.$current_tip = settings.$next_tip # skip non-existent targets else if settings.$li and settings.$target.length < 1 methods.show() else methods.end() else settings.paused = true # detect phones with media queries if supported. is_phone: -> return Modernizr.mq("only screen and (max-width: 767px)") if Modernizr (if (settings.$window.width() < 767) then true else false) hide: -> settings.postStepCallback settings.$li.index(), settings.$current_tip $(".joyride-modal-bg").hide() settings.$current_tip.hide() set_li: (init) -> if init settings.$li = settings.$tip_content.eq(settings.startOffset) methods.set_next_tip() settings.$current_tip = settings.$next_tip else settings.$li = settings.$li.next() methods.set_next_tip() methods.set_target() set_next_tip: -> settings.$next_tip = $(".joyride-tip-guide[data-index=" + settings.$li.index() + "]") set_target: -> cl = settings.$li.attr("data-class") id = settings.$li.attr("data-id") $sel = -> if id $ settings.document.getElementById(id) else if cl $("." + cl).first() else $ "body" settings.$target = $sel() scroll_to: -> window_half = undefined_ tipOffset = undefined_ window_half = settings.$window.height() / 2 tipOffset = Math.ceil(settings.$target.offset().top - window_half + settings.$next_tip.outerHeight()) $("html, body").stop().animate scrollTop: tipOffset , settings.scrollSpeed paused: -> return true if $.inArray((settings.$li.index() + 1), settings.pauseAfter) is -1 false destroy: -> settings.$document.off ".joyride" $(window).off ".joyride" $(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off ".joyride" $(".joyride-tip-guide, .joyride-modal-bg").remove() clearTimeout settings.automate settings = {} restart: -> methods.hide() settings.$li = `undefined` methods.show "init" pos_default: (init) -> half_fold = Math.ceil(settings.$window.height() / 2) tip_position = settings.$next_tip.offset() $nub = $(".joyride-nub", settings.$next_tip) nub_height = Math.ceil($nub.outerHeight() / 2) toggle = init or false # tip must not be "display: none" to calculate position if toggle settings.$next_tip.css "visibility", "hidden" settings.$next_tip.show() unless /body/i.test(settings.$target.selector) if methods.bottom() settings.$next_tip.css top: (settings.$target.offset().top + nub_height + settings.$target.outerHeight()) left: settings.$target.offset().left methods.nub_position $nub, settings.tipSettings.nubPosition, "top" else if methods.top() settings.$next_tip.css top: (settings.$target.offset().top - settings.$next_tip.outerHeight() - nub_height) left: settings.$target.offset().left methods.nub_position $nub, settings.tipSettings.nubPosition, "bottom" else if methods.right() settings.$next_tip.css top: settings.$target.offset().top left: (settings.$target.outerWidth() + settings.$target.offset().left) methods.nub_position $nub, settings.tipSettings.nubPosition, "left" else if methods.left() settings.$next_tip.css top: settings.$target.offset().top left: (settings.$target.offset().left - settings.$next_tip.outerWidth() - nub_height) methods.nub_position $nub, settings.tipSettings.nubPosition, "right" if not methods.visible(methods.corners(settings.$next_tip)) and settings.attempts < settings.tipSettings.tipLocationPattern.length $nub.removeClass("bottom").removeClass("top").removeClass("right").removeClass "left" settings.tipSettings.tipLocation = settings.tipSettings.tipLocationPattern[settings.attempts] settings.attempts++ methods.pos_default true else methods.pos_modal $nub if settings.$li.length if toggle settings.$next_tip.hide() settings.$next_tip.css "visibility", "visible" pos_phone: (init) -> tip_height = settings.$next_tip.outerHeight() tip_offset = settings.$next_tip.offset() target_height = settings.$target.outerHeight() $nub = $(".joyride-nub", settings.$next_tip) nub_height = Math.ceil($nub.outerHeight() / 2) toggle = init or false $nub.removeClass("bottom").removeClass("top").removeClass("right").removeClass "left" if toggle settings.$next_tip.css "visibility", "hidden" settings.$next_tip.show() unless /body/i.test(settings.$target.selector) if methods.top() settings.$next_tip.offset top: settings.$target.offset().top - tip_height - nub_height $nub.addClass "bottom" else settings.$next_tip.offset top: settings.$target.offset().top + target_height + nub_height $nub.addClass "top" else methods.pos_modal $nub if settings.$li.length if toggle settings.$next_tip.hide() settings.$next_tip.css "visibility", "visible" pos_modal: ($nub) -> methods.center() $nub.hide() $("body").append("<div class=\"joyride-modal-bg\">").show() if $(".joyride-modal-bg").length < 1 if /pop/i.test(settings.tipAnimation) $(".joyride-modal-bg").show() else $(".joyride-modal-bg").fadeIn settings.tipAnimationFadeSpeed center: -> $w = settings.$window settings.$next_tip.css top: ((($w.height() - settings.$next_tip.outerHeight()) / 2) + $w.scrollTop()) left: ((($w.width() - settings.$next_tip.outerWidth()) / 2) + $w.scrollLeft()) true bottom: -> /bottom/i.test settings.tipSettings.tipLocation top: -> /top/i.test settings.tipSettings.tipLocation right: -> /right/i.test settings.tipSettings.tipLocation left: -> /left/i.test settings.tipSettings.tipLocation corners: (el) -> w = settings.$window right = w.width() + w.scrollLeft() bottom = w.width() + w.scrollTop() [el.offset().top <= w.scrollTop(), right <= el.offset().left + el.outerWidth(), bottom <= el.offset().top + el.outerHeight(), w.scrollLeft() >= el.offset().left] visible: (hidden_corners) -> i = hidden_corners.length return false if hidden_corners[i] while i-- true nub_position: (nub, pos, def) -> if pos is "auto" nub.addClass def else nub.addClass pos startTimer: -> if settings.$li.length settings.automate = setTimeout(-> methods.hide() methods.show() methods.startTimer() , settings.timer) else clearTimeout settings.automate end: -> if settings.cookieMonster $.cookie settings.cookieName, "ridden", expires: 365 domain: settings.cookieDomain clearTimeout settings.automate if settings.timer > 0 $(".joyride-modal-bg").hide() settings.$current_tip.hide() settings.postStepCallback settings.$li.index(), settings.$current_tip settings.postRideCallback settings.$li.index(), settings.$current_tip jquery_check: -> # define on() and off() for older jQuery unless $.isFunction($.fn.on) $.fn.on = (types, sel, fn) -> @delegate sel, types, fn $.fn.off = (types, sel, fn) -> @undelegate sel, types, fn return false true outerHTML: (el) -> # support FireFox < 11 el.outerHTML or new XMLSerializer().serializeToString(el) version: -> settings.version $.fn.joyride = (method) -> if methods[method] methods[method].apply this, Array::slice.call(arguments, 1) else if typeof method is "object" or not method methods.init.apply this, arguments else $.error "Method " + method + " does not exist on jQuery.joyride" ) jQuery, this
172955
### Inspired in foundation v.3.2 joyride: joyride.coffee ### # # * jQuery Foundation Joyride Plugin 2.0.3 # * http://foundation.zurb.com # * Copyright 2012, <NAME> # * Free to use under the MIT license. # * http://www.opensource.org/licenses/mit-license.php # #jslint unparam: true, browser: true, indent: 2 (($, window, undefined_) -> "use strict" defaults = version: "2.0.3" tipLocation: "bottom" # 'top' or 'bottom' in relation to parent nubPosition: "auto" # override on a per tooltip bases scrollSpeed: 300 # Page scrolling speed in milliseconds timer: 0 # 0 = no timer , all other numbers = timer in milliseconds startTimerOnClick: true # true or false - true requires clicking the first button start the timer startOffset: 0 # the index of the tooltip you want to start on (index of the li) nextButton: true # true or false to control whether a next button is used tipAnimation: "fade" # 'pop' or 'fade' in each tip pauseAfter: [] # array of indexes where to pause the tour after tipAnimationFadeSpeed: 300 # when tipAnimation = 'fade' this is speed in milliseconds for the transition cookieMonster: false # true or false to control whether cookies are used cookieName: "joyride" # Name the cookie you'll use cookieDomain: false # Will this cookie be attached to a domain, ie. '.notableapp.com' tipContainer: "body" # Where will the tip be attached postRideCallback: $.noop # A method to call once the tour closes (canceled or complete) postStepCallback: $.noop # A method to call after each step template: # HTML segments for tip layout link: "<a href=\"#close\" class=\"joyride-close-tip\">X</a>" timer: "<div class=\"joyride-timer-indicator-wrap\"><span class=\"joyride-timer-indicator\"></span></div>" tip: "<div class=\"joyride-tip-guide\"><span class=\"joyride-nub\"></span></div>" wrapper: "<div class=\"joyride-content-wrapper\"></div>" button: "<a href=\"#\" class=\"small button joyride-next-tip\"></a>" Modernizr = Modernizr or false settings = {} methods = init: (opts) -> @each -> if $.isEmptyObject(settings) settings = $.extend(true, defaults, opts) # non configurable settings settings.document = window.document settings.$document = $(settings.document) settings.$window = $(window) settings.$content_el = $(this) settings.body_offset = $(settings.tipContainer).position() settings.$tip_content = $("> li", settings.$content_el) settings.paused = false settings.attempts = 0 settings.tipLocationPatterns = top: ["bottom"] bottom: [] # bottom should not need to be repositioned left: ["right", "top", "bottom"] right: ["left", "top", "bottom"] # are we using jQuery 1.7+ methods.jquery_check() # can we create cookies? settings.cookieMonster = false unless $.isFunction($.cookie) # generate the tips and insert into dom. if not settings.cookieMonster or not $.cookie(settings.cookieName) settings.$tip_content.each (index) -> methods.create $li: $(this) index: index # show first tip if not settings.startTimerOnClick and settings.timer > 0 methods.show "init" methods.startTimer() else methods.show "init" settings.$document.on "click.joyride", ".joyride-next-tip, .joyride-modal-bg", (e) -> e.preventDefault() if settings.$li.next().length < 1 methods.end() else if settings.timer > 0 clearTimeout settings.automate methods.hide() methods.show() methods.startTimer() else methods.hide() methods.show() settings.$document.on "click.joyride", ".joyride-close-tip", (e) -> e.preventDefault() methods.end() settings.$window.bind "resize.joyride", (e) -> if methods.is_phone() methods.pos_phone() else methods.pos_default() else methods.restart() # call this method when you want to resume the tour resume: -> methods.set_li() methods.show() tip_template: (opts) -> $blank = undefined_ content = undefined_ opts.tip_class = opts.tip_class or "" $blank = $(settings.template.tip).addClass(opts.tip_class) content = $.trim($(opts.li).html()) + methods.button_text(opts.button_text) + settings.template.link + methods.timer_instance(opts.index) $blank.append $(settings.template.wrapper) $blank.first().attr "data-index", opts.index $(".joyride-content-wrapper", $blank).append content $blank[0] timer_instance: (index) -> txt = undefined_ if (index is 0 and settings.startTimerOnClick and settings.timer > 0) or settings.timer is 0 txt = "" else txt = methods.outerHTML($(settings.template.timer)[0]) txt button_text: (txt) -> if settings.nextButton txt = $.trim(txt) or "Next" txt = methods.outerHTML($(settings.template.button).append(txt)[0]) else txt = "" txt create: (opts) -> # backwards compatibility with data-text attribute buttonText = opts.$li.attr("data-button") or opts.$li.attr("data-text") tipClass = opts.$li.attr("class") $tip_content = $(methods.tip_template( tip_class: tipClass index: opts.index button_text: buttonText li: opts.$li )) $(settings.tipContainer).append $tip_content show: (init) -> opts = {} ii = undefined_ opts_arr = [] opts_len = 0 p = undefined_ $timer = null # are we paused? if settings.$li is `undefined` or ($.inArray(settings.$li.index(), settings.pauseAfter) is -1) # don't go to the next li if the tour was paused if settings.paused settings.paused = false else methods.set_li init settings.attempts = 0 if settings.$li.length and settings.$target.length > 0 opts_arr = (settings.$li.data("options") or ":").split(";") opts_len = opts_arr.length # parse options ii = opts_len - 1 while ii >= 0 p = opts_arr[ii].split(":") opts[$.trim(p[0])] = $.trim(p[1]) if p.length is 2 ii-- settings.tipSettings = $.extend({}, settings, opts) settings.tipSettings.tipLocationPattern = settings.tipLocationPatterns[settings.tipSettings.tipLocation] # scroll if not modal methods.scroll_to() unless /body/i.test(settings.$target.selector) if methods.is_phone() methods.pos_phone true else methods.pos_default true $timer = $(".joyride-timer-indicator", settings.$next_tip) if /pop/i.test(settings.tipAnimation) $timer.outerWidth 0 if settings.timer > 0 settings.$next_tip.show() $timer.animate width: $(".joyride-timer-indicator-wrap", settings.$next_tip).outerWidth() , settings.timer else settings.$next_tip.show() else if /fade/i.test(settings.tipAnimation) $timer.outerWidth 0 if settings.timer > 0 settings.$next_tip.fadeIn settings.tipAnimationFadeSpeed settings.$next_tip.show() $timer.animate width: $(".joyride-timer-indicator-wrap", settings.$next_tip).outerWidth() , settings.timer else settings.$next_tip.fadeIn settings.tipAnimationFadeSpeed settings.$current_tip = settings.$next_tip # skip non-existent targets else if settings.$li and settings.$target.length < 1 methods.show() else methods.end() else settings.paused = true # detect phones with media queries if supported. is_phone: -> return Modernizr.mq("only screen and (max-width: 767px)") if Modernizr (if (settings.$window.width() < 767) then true else false) hide: -> settings.postStepCallback settings.$li.index(), settings.$current_tip $(".joyride-modal-bg").hide() settings.$current_tip.hide() set_li: (init) -> if init settings.$li = settings.$tip_content.eq(settings.startOffset) methods.set_next_tip() settings.$current_tip = settings.$next_tip else settings.$li = settings.$li.next() methods.set_next_tip() methods.set_target() set_next_tip: -> settings.$next_tip = $(".joyride-tip-guide[data-index=" + settings.$li.index() + "]") set_target: -> cl = settings.$li.attr("data-class") id = settings.$li.attr("data-id") $sel = -> if id $ settings.document.getElementById(id) else if cl $("." + cl).first() else $ "body" settings.$target = $sel() scroll_to: -> window_half = undefined_ tipOffset = undefined_ window_half = settings.$window.height() / 2 tipOffset = Math.ceil(settings.$target.offset().top - window_half + settings.$next_tip.outerHeight()) $("html, body").stop().animate scrollTop: tipOffset , settings.scrollSpeed paused: -> return true if $.inArray((settings.$li.index() + 1), settings.pauseAfter) is -1 false destroy: -> settings.$document.off ".joyride" $(window).off ".joyride" $(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off ".joyride" $(".joyride-tip-guide, .joyride-modal-bg").remove() clearTimeout settings.automate settings = {} restart: -> methods.hide() settings.$li = `undefined` methods.show "init" pos_default: (init) -> half_fold = Math.ceil(settings.$window.height() / 2) tip_position = settings.$next_tip.offset() $nub = $(".joyride-nub", settings.$next_tip) nub_height = Math.ceil($nub.outerHeight() / 2) toggle = init or false # tip must not be "display: none" to calculate position if toggle settings.$next_tip.css "visibility", "hidden" settings.$next_tip.show() unless /body/i.test(settings.$target.selector) if methods.bottom() settings.$next_tip.css top: (settings.$target.offset().top + nub_height + settings.$target.outerHeight()) left: settings.$target.offset().left methods.nub_position $nub, settings.tipSettings.nubPosition, "top" else if methods.top() settings.$next_tip.css top: (settings.$target.offset().top - settings.$next_tip.outerHeight() - nub_height) left: settings.$target.offset().left methods.nub_position $nub, settings.tipSettings.nubPosition, "bottom" else if methods.right() settings.$next_tip.css top: settings.$target.offset().top left: (settings.$target.outerWidth() + settings.$target.offset().left) methods.nub_position $nub, settings.tipSettings.nubPosition, "left" else if methods.left() settings.$next_tip.css top: settings.$target.offset().top left: (settings.$target.offset().left - settings.$next_tip.outerWidth() - nub_height) methods.nub_position $nub, settings.tipSettings.nubPosition, "right" if not methods.visible(methods.corners(settings.$next_tip)) and settings.attempts < settings.tipSettings.tipLocationPattern.length $nub.removeClass("bottom").removeClass("top").removeClass("right").removeClass "left" settings.tipSettings.tipLocation = settings.tipSettings.tipLocationPattern[settings.attempts] settings.attempts++ methods.pos_default true else methods.pos_modal $nub if settings.$li.length if toggle settings.$next_tip.hide() settings.$next_tip.css "visibility", "visible" pos_phone: (init) -> tip_height = settings.$next_tip.outerHeight() tip_offset = settings.$next_tip.offset() target_height = settings.$target.outerHeight() $nub = $(".joyride-nub", settings.$next_tip) nub_height = Math.ceil($nub.outerHeight() / 2) toggle = init or false $nub.removeClass("bottom").removeClass("top").removeClass("right").removeClass "left" if toggle settings.$next_tip.css "visibility", "hidden" settings.$next_tip.show() unless /body/i.test(settings.$target.selector) if methods.top() settings.$next_tip.offset top: settings.$target.offset().top - tip_height - nub_height $nub.addClass "bottom" else settings.$next_tip.offset top: settings.$target.offset().top + target_height + nub_height $nub.addClass "top" else methods.pos_modal $nub if settings.$li.length if toggle settings.$next_tip.hide() settings.$next_tip.css "visibility", "visible" pos_modal: ($nub) -> methods.center() $nub.hide() $("body").append("<div class=\"joyride-modal-bg\">").show() if $(".joyride-modal-bg").length < 1 if /pop/i.test(settings.tipAnimation) $(".joyride-modal-bg").show() else $(".joyride-modal-bg").fadeIn settings.tipAnimationFadeSpeed center: -> $w = settings.$window settings.$next_tip.css top: ((($w.height() - settings.$next_tip.outerHeight()) / 2) + $w.scrollTop()) left: ((($w.width() - settings.$next_tip.outerWidth()) / 2) + $w.scrollLeft()) true bottom: -> /bottom/i.test settings.tipSettings.tipLocation top: -> /top/i.test settings.tipSettings.tipLocation right: -> /right/i.test settings.tipSettings.tipLocation left: -> /left/i.test settings.tipSettings.tipLocation corners: (el) -> w = settings.$window right = w.width() + w.scrollLeft() bottom = w.width() + w.scrollTop() [el.offset().top <= w.scrollTop(), right <= el.offset().left + el.outerWidth(), bottom <= el.offset().top + el.outerHeight(), w.scrollLeft() >= el.offset().left] visible: (hidden_corners) -> i = hidden_corners.length return false if hidden_corners[i] while i-- true nub_position: (nub, pos, def) -> if pos is "auto" nub.addClass def else nub.addClass pos startTimer: -> if settings.$li.length settings.automate = setTimeout(-> methods.hide() methods.show() methods.startTimer() , settings.timer) else clearTimeout settings.automate end: -> if settings.cookieMonster $.cookie settings.cookieName, "ridden", expires: 365 domain: settings.cookieDomain clearTimeout settings.automate if settings.timer > 0 $(".joyride-modal-bg").hide() settings.$current_tip.hide() settings.postStepCallback settings.$li.index(), settings.$current_tip settings.postRideCallback settings.$li.index(), settings.$current_tip jquery_check: -> # define on() and off() for older jQuery unless $.isFunction($.fn.on) $.fn.on = (types, sel, fn) -> @delegate sel, types, fn $.fn.off = (types, sel, fn) -> @undelegate sel, types, fn return false true outerHTML: (el) -> # support FireFox < 11 el.outerHTML or new XMLSerializer().serializeToString(el) version: -> settings.version $.fn.joyride = (method) -> if methods[method] methods[method].apply this, Array::slice.call(arguments, 1) else if typeof method is "object" or not method methods.init.apply this, arguments else $.error "Method " + method + " does not exist on jQuery.joyride" ) jQuery, this
true
### Inspired in foundation v.3.2 joyride: joyride.coffee ### # # * jQuery Foundation Joyride Plugin 2.0.3 # * http://foundation.zurb.com # * Copyright 2012, PI:NAME:<NAME>END_PI # * Free to use under the MIT license. # * http://www.opensource.org/licenses/mit-license.php # #jslint unparam: true, browser: true, indent: 2 (($, window, undefined_) -> "use strict" defaults = version: "2.0.3" tipLocation: "bottom" # 'top' or 'bottom' in relation to parent nubPosition: "auto" # override on a per tooltip bases scrollSpeed: 300 # Page scrolling speed in milliseconds timer: 0 # 0 = no timer , all other numbers = timer in milliseconds startTimerOnClick: true # true or false - true requires clicking the first button start the timer startOffset: 0 # the index of the tooltip you want to start on (index of the li) nextButton: true # true or false to control whether a next button is used tipAnimation: "fade" # 'pop' or 'fade' in each tip pauseAfter: [] # array of indexes where to pause the tour after tipAnimationFadeSpeed: 300 # when tipAnimation = 'fade' this is speed in milliseconds for the transition cookieMonster: false # true or false to control whether cookies are used cookieName: "joyride" # Name the cookie you'll use cookieDomain: false # Will this cookie be attached to a domain, ie. '.notableapp.com' tipContainer: "body" # Where will the tip be attached postRideCallback: $.noop # A method to call once the tour closes (canceled or complete) postStepCallback: $.noop # A method to call after each step template: # HTML segments for tip layout link: "<a href=\"#close\" class=\"joyride-close-tip\">X</a>" timer: "<div class=\"joyride-timer-indicator-wrap\"><span class=\"joyride-timer-indicator\"></span></div>" tip: "<div class=\"joyride-tip-guide\"><span class=\"joyride-nub\"></span></div>" wrapper: "<div class=\"joyride-content-wrapper\"></div>" button: "<a href=\"#\" class=\"small button joyride-next-tip\"></a>" Modernizr = Modernizr or false settings = {} methods = init: (opts) -> @each -> if $.isEmptyObject(settings) settings = $.extend(true, defaults, opts) # non configurable settings settings.document = window.document settings.$document = $(settings.document) settings.$window = $(window) settings.$content_el = $(this) settings.body_offset = $(settings.tipContainer).position() settings.$tip_content = $("> li", settings.$content_el) settings.paused = false settings.attempts = 0 settings.tipLocationPatterns = top: ["bottom"] bottom: [] # bottom should not need to be repositioned left: ["right", "top", "bottom"] right: ["left", "top", "bottom"] # are we using jQuery 1.7+ methods.jquery_check() # can we create cookies? settings.cookieMonster = false unless $.isFunction($.cookie) # generate the tips and insert into dom. if not settings.cookieMonster or not $.cookie(settings.cookieName) settings.$tip_content.each (index) -> methods.create $li: $(this) index: index # show first tip if not settings.startTimerOnClick and settings.timer > 0 methods.show "init" methods.startTimer() else methods.show "init" settings.$document.on "click.joyride", ".joyride-next-tip, .joyride-modal-bg", (e) -> e.preventDefault() if settings.$li.next().length < 1 methods.end() else if settings.timer > 0 clearTimeout settings.automate methods.hide() methods.show() methods.startTimer() else methods.hide() methods.show() settings.$document.on "click.joyride", ".joyride-close-tip", (e) -> e.preventDefault() methods.end() settings.$window.bind "resize.joyride", (e) -> if methods.is_phone() methods.pos_phone() else methods.pos_default() else methods.restart() # call this method when you want to resume the tour resume: -> methods.set_li() methods.show() tip_template: (opts) -> $blank = undefined_ content = undefined_ opts.tip_class = opts.tip_class or "" $blank = $(settings.template.tip).addClass(opts.tip_class) content = $.trim($(opts.li).html()) + methods.button_text(opts.button_text) + settings.template.link + methods.timer_instance(opts.index) $blank.append $(settings.template.wrapper) $blank.first().attr "data-index", opts.index $(".joyride-content-wrapper", $blank).append content $blank[0] timer_instance: (index) -> txt = undefined_ if (index is 0 and settings.startTimerOnClick and settings.timer > 0) or settings.timer is 0 txt = "" else txt = methods.outerHTML($(settings.template.timer)[0]) txt button_text: (txt) -> if settings.nextButton txt = $.trim(txt) or "Next" txt = methods.outerHTML($(settings.template.button).append(txt)[0]) else txt = "" txt create: (opts) -> # backwards compatibility with data-text attribute buttonText = opts.$li.attr("data-button") or opts.$li.attr("data-text") tipClass = opts.$li.attr("class") $tip_content = $(methods.tip_template( tip_class: tipClass index: opts.index button_text: buttonText li: opts.$li )) $(settings.tipContainer).append $tip_content show: (init) -> opts = {} ii = undefined_ opts_arr = [] opts_len = 0 p = undefined_ $timer = null # are we paused? if settings.$li is `undefined` or ($.inArray(settings.$li.index(), settings.pauseAfter) is -1) # don't go to the next li if the tour was paused if settings.paused settings.paused = false else methods.set_li init settings.attempts = 0 if settings.$li.length and settings.$target.length > 0 opts_arr = (settings.$li.data("options") or ":").split(";") opts_len = opts_arr.length # parse options ii = opts_len - 1 while ii >= 0 p = opts_arr[ii].split(":") opts[$.trim(p[0])] = $.trim(p[1]) if p.length is 2 ii-- settings.tipSettings = $.extend({}, settings, opts) settings.tipSettings.tipLocationPattern = settings.tipLocationPatterns[settings.tipSettings.tipLocation] # scroll if not modal methods.scroll_to() unless /body/i.test(settings.$target.selector) if methods.is_phone() methods.pos_phone true else methods.pos_default true $timer = $(".joyride-timer-indicator", settings.$next_tip) if /pop/i.test(settings.tipAnimation) $timer.outerWidth 0 if settings.timer > 0 settings.$next_tip.show() $timer.animate width: $(".joyride-timer-indicator-wrap", settings.$next_tip).outerWidth() , settings.timer else settings.$next_tip.show() else if /fade/i.test(settings.tipAnimation) $timer.outerWidth 0 if settings.timer > 0 settings.$next_tip.fadeIn settings.tipAnimationFadeSpeed settings.$next_tip.show() $timer.animate width: $(".joyride-timer-indicator-wrap", settings.$next_tip).outerWidth() , settings.timer else settings.$next_tip.fadeIn settings.tipAnimationFadeSpeed settings.$current_tip = settings.$next_tip # skip non-existent targets else if settings.$li and settings.$target.length < 1 methods.show() else methods.end() else settings.paused = true # detect phones with media queries if supported. is_phone: -> return Modernizr.mq("only screen and (max-width: 767px)") if Modernizr (if (settings.$window.width() < 767) then true else false) hide: -> settings.postStepCallback settings.$li.index(), settings.$current_tip $(".joyride-modal-bg").hide() settings.$current_tip.hide() set_li: (init) -> if init settings.$li = settings.$tip_content.eq(settings.startOffset) methods.set_next_tip() settings.$current_tip = settings.$next_tip else settings.$li = settings.$li.next() methods.set_next_tip() methods.set_target() set_next_tip: -> settings.$next_tip = $(".joyride-tip-guide[data-index=" + settings.$li.index() + "]") set_target: -> cl = settings.$li.attr("data-class") id = settings.$li.attr("data-id") $sel = -> if id $ settings.document.getElementById(id) else if cl $("." + cl).first() else $ "body" settings.$target = $sel() scroll_to: -> window_half = undefined_ tipOffset = undefined_ window_half = settings.$window.height() / 2 tipOffset = Math.ceil(settings.$target.offset().top - window_half + settings.$next_tip.outerHeight()) $("html, body").stop().animate scrollTop: tipOffset , settings.scrollSpeed paused: -> return true if $.inArray((settings.$li.index() + 1), settings.pauseAfter) is -1 false destroy: -> settings.$document.off ".joyride" $(window).off ".joyride" $(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off ".joyride" $(".joyride-tip-guide, .joyride-modal-bg").remove() clearTimeout settings.automate settings = {} restart: -> methods.hide() settings.$li = `undefined` methods.show "init" pos_default: (init) -> half_fold = Math.ceil(settings.$window.height() / 2) tip_position = settings.$next_tip.offset() $nub = $(".joyride-nub", settings.$next_tip) nub_height = Math.ceil($nub.outerHeight() / 2) toggle = init or false # tip must not be "display: none" to calculate position if toggle settings.$next_tip.css "visibility", "hidden" settings.$next_tip.show() unless /body/i.test(settings.$target.selector) if methods.bottom() settings.$next_tip.css top: (settings.$target.offset().top + nub_height + settings.$target.outerHeight()) left: settings.$target.offset().left methods.nub_position $nub, settings.tipSettings.nubPosition, "top" else if methods.top() settings.$next_tip.css top: (settings.$target.offset().top - settings.$next_tip.outerHeight() - nub_height) left: settings.$target.offset().left methods.nub_position $nub, settings.tipSettings.nubPosition, "bottom" else if methods.right() settings.$next_tip.css top: settings.$target.offset().top left: (settings.$target.outerWidth() + settings.$target.offset().left) methods.nub_position $nub, settings.tipSettings.nubPosition, "left" else if methods.left() settings.$next_tip.css top: settings.$target.offset().top left: (settings.$target.offset().left - settings.$next_tip.outerWidth() - nub_height) methods.nub_position $nub, settings.tipSettings.nubPosition, "right" if not methods.visible(methods.corners(settings.$next_tip)) and settings.attempts < settings.tipSettings.tipLocationPattern.length $nub.removeClass("bottom").removeClass("top").removeClass("right").removeClass "left" settings.tipSettings.tipLocation = settings.tipSettings.tipLocationPattern[settings.attempts] settings.attempts++ methods.pos_default true else methods.pos_modal $nub if settings.$li.length if toggle settings.$next_tip.hide() settings.$next_tip.css "visibility", "visible" pos_phone: (init) -> tip_height = settings.$next_tip.outerHeight() tip_offset = settings.$next_tip.offset() target_height = settings.$target.outerHeight() $nub = $(".joyride-nub", settings.$next_tip) nub_height = Math.ceil($nub.outerHeight() / 2) toggle = init or false $nub.removeClass("bottom").removeClass("top").removeClass("right").removeClass "left" if toggle settings.$next_tip.css "visibility", "hidden" settings.$next_tip.show() unless /body/i.test(settings.$target.selector) if methods.top() settings.$next_tip.offset top: settings.$target.offset().top - tip_height - nub_height $nub.addClass "bottom" else settings.$next_tip.offset top: settings.$target.offset().top + target_height + nub_height $nub.addClass "top" else methods.pos_modal $nub if settings.$li.length if toggle settings.$next_tip.hide() settings.$next_tip.css "visibility", "visible" pos_modal: ($nub) -> methods.center() $nub.hide() $("body").append("<div class=\"joyride-modal-bg\">").show() if $(".joyride-modal-bg").length < 1 if /pop/i.test(settings.tipAnimation) $(".joyride-modal-bg").show() else $(".joyride-modal-bg").fadeIn settings.tipAnimationFadeSpeed center: -> $w = settings.$window settings.$next_tip.css top: ((($w.height() - settings.$next_tip.outerHeight()) / 2) + $w.scrollTop()) left: ((($w.width() - settings.$next_tip.outerWidth()) / 2) + $w.scrollLeft()) true bottom: -> /bottom/i.test settings.tipSettings.tipLocation top: -> /top/i.test settings.tipSettings.tipLocation right: -> /right/i.test settings.tipSettings.tipLocation left: -> /left/i.test settings.tipSettings.tipLocation corners: (el) -> w = settings.$window right = w.width() + w.scrollLeft() bottom = w.width() + w.scrollTop() [el.offset().top <= w.scrollTop(), right <= el.offset().left + el.outerWidth(), bottom <= el.offset().top + el.outerHeight(), w.scrollLeft() >= el.offset().left] visible: (hidden_corners) -> i = hidden_corners.length return false if hidden_corners[i] while i-- true nub_position: (nub, pos, def) -> if pos is "auto" nub.addClass def else nub.addClass pos startTimer: -> if settings.$li.length settings.automate = setTimeout(-> methods.hide() methods.show() methods.startTimer() , settings.timer) else clearTimeout settings.automate end: -> if settings.cookieMonster $.cookie settings.cookieName, "ridden", expires: 365 domain: settings.cookieDomain clearTimeout settings.automate if settings.timer > 0 $(".joyride-modal-bg").hide() settings.$current_tip.hide() settings.postStepCallback settings.$li.index(), settings.$current_tip settings.postRideCallback settings.$li.index(), settings.$current_tip jquery_check: -> # define on() and off() for older jQuery unless $.isFunction($.fn.on) $.fn.on = (types, sel, fn) -> @delegate sel, types, fn $.fn.off = (types, sel, fn) -> @undelegate sel, types, fn return false true outerHTML: (el) -> # support FireFox < 11 el.outerHTML or new XMLSerializer().serializeToString(el) version: -> settings.version $.fn.joyride = (method) -> if methods[method] methods[method].apply this, Array::slice.call(arguments, 1) else if typeof method is "object" or not method methods.init.apply this, arguments else $.error "Method " + method + " does not exist on jQuery.joyride" ) jQuery, this
[ { "context": " people who do not use Coffeescript. \n \n @author Mads Hartmann Jensen. \n###\n\nmugs.provide(\"mugs.range\")\n\nmugs.range = {", "end": 185, "score": 0.9998239278793335, "start": 165, "tag": "NAME", "value": "Mads Hartmann Jensen" } ]
src/Range.coffee
mads-hartmann/mugs
1
### range is a utility object that can create arrays with all natural number in a given range. Convenient for people who do not use Coffeescript. @author Mads Hartmann Jensen. ### mugs.provide("mugs.range") mugs.range = {} ###* Creates an array with all the numbers between from and to inclusive. @param from The lower bound of the range (included) @param to The upper bound of the range (included) @return An array with all the numbers between from and to inclusive. ### mugs.range.to = (from, to) -> [from..to] ###* Creates an array with all the numbers between from and until. From is included, until isn't. @param from The lower bound of the range (included) @param until_ The upper bound of the range (excluded) @return An array with all the numbers between from and until. From is included, until isn't. ### mugs.range.until = (from, until_) -> [from..until_-1]
180086
### range is a utility object that can create arrays with all natural number in a given range. Convenient for people who do not use Coffeescript. @author <NAME>. ### mugs.provide("mugs.range") mugs.range = {} ###* Creates an array with all the numbers between from and to inclusive. @param from The lower bound of the range (included) @param to The upper bound of the range (included) @return An array with all the numbers between from and to inclusive. ### mugs.range.to = (from, to) -> [from..to] ###* Creates an array with all the numbers between from and until. From is included, until isn't. @param from The lower bound of the range (included) @param until_ The upper bound of the range (excluded) @return An array with all the numbers between from and until. From is included, until isn't. ### mugs.range.until = (from, until_) -> [from..until_-1]
true
### range is a utility object that can create arrays with all natural number in a given range. Convenient for people who do not use Coffeescript. @author PI:NAME:<NAME>END_PI. ### mugs.provide("mugs.range") mugs.range = {} ###* Creates an array with all the numbers between from and to inclusive. @param from The lower bound of the range (included) @param to The upper bound of the range (included) @return An array with all the numbers between from and to inclusive. ### mugs.range.to = (from, to) -> [from..to] ###* Creates an array with all the numbers between from and until. From is included, until isn't. @param from The lower bound of the range (included) @param until_ The upper bound of the range (excluded) @return An array with all the numbers between from and until. From is included, until isn't. ### mugs.range.until = (from, until_) -> [from..until_-1]
[ { "context": "# base64\n# \n# @description\n# @Copyright 2014 Fantasy <fantasyshao@icloud.com>\n# @create 2014-12-11\n# @", "end": 52, "score": 0.9777643084526062, "start": 45, "tag": "USERNAME", "value": "Fantasy" }, { "context": "se64\n# \n# @description\n# @Copyright 2014 Fantasy <fantasyshao@icloud.com>\n# @create 2014-12-11\n# @update 2014-12-22\n\nexpor", "end": 76, "score": 0.9999297261238098, "start": 54, "tag": "EMAIL", "value": "fantasyshao@icloud.com" } ]
src/coffee/base64.coffee
FantasyMedia/Toolbox
0
# base64 # # @description # @Copyright 2014 Fantasy <fantasyshao@icloud.com> # @create 2014-12-11 # @update 2014-12-22 exports.encode = (str) -> try new Buffer(str).toString('base64') catch err console.debug err exports.decode = (str) -> try new Buffer(str, 'base64').toString('ascii') catch err console.debug err
63538
# base64 # # @description # @Copyright 2014 Fantasy <<EMAIL>> # @create 2014-12-11 # @update 2014-12-22 exports.encode = (str) -> try new Buffer(str).toString('base64') catch err console.debug err exports.decode = (str) -> try new Buffer(str, 'base64').toString('ascii') catch err console.debug err
true
# base64 # # @description # @Copyright 2014 Fantasy <PI:EMAIL:<EMAIL>END_PI> # @create 2014-12-11 # @update 2014-12-22 exports.encode = (str) -> try new Buffer(str).toString('base64') catch err console.debug err exports.decode = (str) -> try new Buffer(str, 'base64').toString('ascii') catch err console.debug err
[ { "context": "rn\n\ncola.util.cancelDelay = (owner, name)->\n\tkey = \"_timer_\" + name\n\ttimerId = owner[key]\n\tif timerId\n\t\tdelete owner[", "end": 3221, "score": 0.9747292399406433, "start": 3205, "tag": "KEY", "value": "\"_timer_\" + name" } ]
src/core/util.coffee
homeant/cola-ui
90
cola.util.createDeferredIf = (originDfd, failbackArgs)-> return originDfd or $.Deferred().resolve(failbackArgs) cola.util.wrapDeferredWith = (context, originDfd, failbackArgs)-> if originDfd and (not originDfd.done or not originDfd.fail) return originDfd dfd = $.Deferred() if originDfd originDfd.done(()-> dfd.resolveWith.apply(dfd, [context, arguments]) ).fail(()-> dfd.rejectWith.apply(dfd, [context, arguments]) ).notify?(()-> dfd.notifyWith.apply(dfd, [context, arguments]) ) else dfd.resolveWith(context, failbackArgs) return dfd cola.util.findModel = (dom)-> scope = cola.util.userData(dom, "scope") if scope return scope domBinding = cola.util.userData(dom, cola.constants.DOM_BINDING_KEY) if domBinding return domBinding.scope if dom.parentNode return cola.util.findModel(dom.parentNode) else return null cola.util.trim = (text)-> return if text? then String.prototype.trim.call(text) else "" cola.util.capitalize = (text)-> return text unless text return text.charAt(0).toUpperCase() + text.slice(1); cola.util.isSimpleValue = (value)-> if value == null or value == undefined then return true type = typeof value return type != "object" and type != "function" or value instanceof Date or value instanceof Array cola.util.path = (parts...)-> last = parts.length - 1 for part, i in parts changed = false if i > 0 and part.charCodeAt(0) is 47 # `/` part = part.substring(1) changed = true if i < last and part.charCodeAt(part.length - 1) is 47 # `/` part = part.substring(0, part.length - 1) changed = true if changed then parts[i] = part return parts.join("/") cola.util.each = (array, fn)-> for item, i in array if fn(item, i) is false break return cola.util.parseStyleLikeString = (styleStr, headerProp)-> return false unless styleStr style = {} parts = styleStr.split(";") for part, i in parts j = part.indexOf(":") if j > 0 styleProp = @trim(part.substring(0, j)) styleExpr = @trim(part.substring(j + 1)) if styleProp and styleExpr style[styleProp] = styleExpr else part = @trim(part) if not part then continue if i is 0 and headerProp style[headerProp] = part else style[part] = true return style cola.util.parseFunctionArgs = (func)-> argStr = func.toString().match(/\([^\(\)]*\)/)[0] rawArgs = argStr.substring(1, argStr.length - 1).split(","); args = [] for arg, i in rawArgs arg = cola.util.trim(arg) if arg then args.push(arg) return args cola.util.parseListener = (listener)-> argsMode = 1 argStr = listener.toString().match(/\([^\(\)]*\)/)[0] args = argStr.substring(1, argStr.length - 1).split(","); if args.length if cola.util.trim(args[0]) is "arg" then argsMode = 2 listener._argsMode = argsMode return argsMode cola.util.isCompatibleType = (baseType, type)-> if type == baseType then return true while type.__super__ type = type.__super__.constructor if type == baseType then return true return false cola.util.delay = (owner, name, delay, fn)-> cola.util.cancelDelay(owner, name) owner["_timer_" + name] = setTimeout(()-> fn.call(owner) return , delay) return cola.util.cancelDelay = (owner, name)-> key = "_timer_" + name timerId = owner[key] if timerId delete owner[key] clearTimeout(timerId) return cola.util.formatDate = (date, pattern)-> return "" unless date? if not (date instanceof XDate) date = new XDate(date) return date.toString(pattern or cola.setting("defaultDateFormat")) cola.util.formatNumber = (number, pattern)-> return "" unless number? return number if isNaN(number) return formatNumber(pattern or cola.setting("defaultNumberFormat"), number) cola.util.format = (value, format)-> if value is null or value is undefined or value is "" return "" else if value instanceof Date return cola.util.formatDate(value, format) else if isFinite(value) return cola.util.formatNumber(value, format) else if value and typeof value is "string" date = (new XDate(value)).toDate() if not isFinite(date) return value else return cola.util.formatDate(date, format) else return value cola.util.getItemByItemDom = (dom)-> scope = cola.util.userData(dom, "scope") if scope and scope instanceof cola.ItemScope return scope.data.getItemData() domBinding = cola.util.userData(dom, cola.constants.DOM_BINDING_KEY) if domBinding scope = domBinding.scope if scope and scope instanceof cola.ItemScope return scope.data.getItemData() if dom.parentNode return cola.util.getItemByItemDom(dom.parentNode) else return null ## URL cola.util.queryParams = ()-> decode = (str)-> decodeURIComponent((str || "").replace(/\+/g, " ")) query = (window.location.search || "").substring(1) params = {} if query.length > 0 for param, i in query.split("&") pair = param.split("=") key = decode(pair.shift()) value = decode(if pair.length then pair.join("=") else null) if (params.hasOwnProperty(key)) oldValue = params[key] if oldValue instanceof Array oldValue.push(value) else params[key] = [oldValue, value] else params[key] = value return params cola.util.pathParams = (prefix, index = 0)-> path = (window.location.pathname || "").replace(/^\//, "") parts = path.split("/") i = parts.indexOf(prefix) if i >= 0 return parts[i + 1 + index] else return ## Dictionary keyValuesMap = {} dictionaryMap = {} cola.util.dictionary = (name, keyValues)-> if keyValues is null delete keyValuesMap[name] delete dictionaryMap[name] return else if keyValues is undefined return keyValuesMap[name] else if keyValues instanceof Array keyValuesMap[name] = keyValues dictionaryMap[name] = dictionary = {} for pair in keyValues dictionary[pair.key or ""] = pair.value return dictionary else keyValuesMap[name] = values = [] for key, value of keyValues values.push( key: key value: value ) dictionaryMap[name] = keyValues return keyValues cola.util.translate = (dictionaryName, key)-> return dictionaryMap[dictionaryName]?[key or ""] # OO cola.util.isSuperClass = (superCls, cls)-> return false unless superCls while cls return true if cls.__super__ is superCls:: cls = cls.__super__?.constructor return false
209212
cola.util.createDeferredIf = (originDfd, failbackArgs)-> return originDfd or $.Deferred().resolve(failbackArgs) cola.util.wrapDeferredWith = (context, originDfd, failbackArgs)-> if originDfd and (not originDfd.done or not originDfd.fail) return originDfd dfd = $.Deferred() if originDfd originDfd.done(()-> dfd.resolveWith.apply(dfd, [context, arguments]) ).fail(()-> dfd.rejectWith.apply(dfd, [context, arguments]) ).notify?(()-> dfd.notifyWith.apply(dfd, [context, arguments]) ) else dfd.resolveWith(context, failbackArgs) return dfd cola.util.findModel = (dom)-> scope = cola.util.userData(dom, "scope") if scope return scope domBinding = cola.util.userData(dom, cola.constants.DOM_BINDING_KEY) if domBinding return domBinding.scope if dom.parentNode return cola.util.findModel(dom.parentNode) else return null cola.util.trim = (text)-> return if text? then String.prototype.trim.call(text) else "" cola.util.capitalize = (text)-> return text unless text return text.charAt(0).toUpperCase() + text.slice(1); cola.util.isSimpleValue = (value)-> if value == null or value == undefined then return true type = typeof value return type != "object" and type != "function" or value instanceof Date or value instanceof Array cola.util.path = (parts...)-> last = parts.length - 1 for part, i in parts changed = false if i > 0 and part.charCodeAt(0) is 47 # `/` part = part.substring(1) changed = true if i < last and part.charCodeAt(part.length - 1) is 47 # `/` part = part.substring(0, part.length - 1) changed = true if changed then parts[i] = part return parts.join("/") cola.util.each = (array, fn)-> for item, i in array if fn(item, i) is false break return cola.util.parseStyleLikeString = (styleStr, headerProp)-> return false unless styleStr style = {} parts = styleStr.split(";") for part, i in parts j = part.indexOf(":") if j > 0 styleProp = @trim(part.substring(0, j)) styleExpr = @trim(part.substring(j + 1)) if styleProp and styleExpr style[styleProp] = styleExpr else part = @trim(part) if not part then continue if i is 0 and headerProp style[headerProp] = part else style[part] = true return style cola.util.parseFunctionArgs = (func)-> argStr = func.toString().match(/\([^\(\)]*\)/)[0] rawArgs = argStr.substring(1, argStr.length - 1).split(","); args = [] for arg, i in rawArgs arg = cola.util.trim(arg) if arg then args.push(arg) return args cola.util.parseListener = (listener)-> argsMode = 1 argStr = listener.toString().match(/\([^\(\)]*\)/)[0] args = argStr.substring(1, argStr.length - 1).split(","); if args.length if cola.util.trim(args[0]) is "arg" then argsMode = 2 listener._argsMode = argsMode return argsMode cola.util.isCompatibleType = (baseType, type)-> if type == baseType then return true while type.__super__ type = type.__super__.constructor if type == baseType then return true return false cola.util.delay = (owner, name, delay, fn)-> cola.util.cancelDelay(owner, name) owner["_timer_" + name] = setTimeout(()-> fn.call(owner) return , delay) return cola.util.cancelDelay = (owner, name)-> key = <KEY> timerId = owner[key] if timerId delete owner[key] clearTimeout(timerId) return cola.util.formatDate = (date, pattern)-> return "" unless date? if not (date instanceof XDate) date = new XDate(date) return date.toString(pattern or cola.setting("defaultDateFormat")) cola.util.formatNumber = (number, pattern)-> return "" unless number? return number if isNaN(number) return formatNumber(pattern or cola.setting("defaultNumberFormat"), number) cola.util.format = (value, format)-> if value is null or value is undefined or value is "" return "" else if value instanceof Date return cola.util.formatDate(value, format) else if isFinite(value) return cola.util.formatNumber(value, format) else if value and typeof value is "string" date = (new XDate(value)).toDate() if not isFinite(date) return value else return cola.util.formatDate(date, format) else return value cola.util.getItemByItemDom = (dom)-> scope = cola.util.userData(dom, "scope") if scope and scope instanceof cola.ItemScope return scope.data.getItemData() domBinding = cola.util.userData(dom, cola.constants.DOM_BINDING_KEY) if domBinding scope = domBinding.scope if scope and scope instanceof cola.ItemScope return scope.data.getItemData() if dom.parentNode return cola.util.getItemByItemDom(dom.parentNode) else return null ## URL cola.util.queryParams = ()-> decode = (str)-> decodeURIComponent((str || "").replace(/\+/g, " ")) query = (window.location.search || "").substring(1) params = {} if query.length > 0 for param, i in query.split("&") pair = param.split("=") key = decode(pair.shift()) value = decode(if pair.length then pair.join("=") else null) if (params.hasOwnProperty(key)) oldValue = params[key] if oldValue instanceof Array oldValue.push(value) else params[key] = [oldValue, value] else params[key] = value return params cola.util.pathParams = (prefix, index = 0)-> path = (window.location.pathname || "").replace(/^\//, "") parts = path.split("/") i = parts.indexOf(prefix) if i >= 0 return parts[i + 1 + index] else return ## Dictionary keyValuesMap = {} dictionaryMap = {} cola.util.dictionary = (name, keyValues)-> if keyValues is null delete keyValuesMap[name] delete dictionaryMap[name] return else if keyValues is undefined return keyValuesMap[name] else if keyValues instanceof Array keyValuesMap[name] = keyValues dictionaryMap[name] = dictionary = {} for pair in keyValues dictionary[pair.key or ""] = pair.value return dictionary else keyValuesMap[name] = values = [] for key, value of keyValues values.push( key: key value: value ) dictionaryMap[name] = keyValues return keyValues cola.util.translate = (dictionaryName, key)-> return dictionaryMap[dictionaryName]?[key or ""] # OO cola.util.isSuperClass = (superCls, cls)-> return false unless superCls while cls return true if cls.__super__ is superCls:: cls = cls.__super__?.constructor return false
true
cola.util.createDeferredIf = (originDfd, failbackArgs)-> return originDfd or $.Deferred().resolve(failbackArgs) cola.util.wrapDeferredWith = (context, originDfd, failbackArgs)-> if originDfd and (not originDfd.done or not originDfd.fail) return originDfd dfd = $.Deferred() if originDfd originDfd.done(()-> dfd.resolveWith.apply(dfd, [context, arguments]) ).fail(()-> dfd.rejectWith.apply(dfd, [context, arguments]) ).notify?(()-> dfd.notifyWith.apply(dfd, [context, arguments]) ) else dfd.resolveWith(context, failbackArgs) return dfd cola.util.findModel = (dom)-> scope = cola.util.userData(dom, "scope") if scope return scope domBinding = cola.util.userData(dom, cola.constants.DOM_BINDING_KEY) if domBinding return domBinding.scope if dom.parentNode return cola.util.findModel(dom.parentNode) else return null cola.util.trim = (text)-> return if text? then String.prototype.trim.call(text) else "" cola.util.capitalize = (text)-> return text unless text return text.charAt(0).toUpperCase() + text.slice(1); cola.util.isSimpleValue = (value)-> if value == null or value == undefined then return true type = typeof value return type != "object" and type != "function" or value instanceof Date or value instanceof Array cola.util.path = (parts...)-> last = parts.length - 1 for part, i in parts changed = false if i > 0 and part.charCodeAt(0) is 47 # `/` part = part.substring(1) changed = true if i < last and part.charCodeAt(part.length - 1) is 47 # `/` part = part.substring(0, part.length - 1) changed = true if changed then parts[i] = part return parts.join("/") cola.util.each = (array, fn)-> for item, i in array if fn(item, i) is false break return cola.util.parseStyleLikeString = (styleStr, headerProp)-> return false unless styleStr style = {} parts = styleStr.split(";") for part, i in parts j = part.indexOf(":") if j > 0 styleProp = @trim(part.substring(0, j)) styleExpr = @trim(part.substring(j + 1)) if styleProp and styleExpr style[styleProp] = styleExpr else part = @trim(part) if not part then continue if i is 0 and headerProp style[headerProp] = part else style[part] = true return style cola.util.parseFunctionArgs = (func)-> argStr = func.toString().match(/\([^\(\)]*\)/)[0] rawArgs = argStr.substring(1, argStr.length - 1).split(","); args = [] for arg, i in rawArgs arg = cola.util.trim(arg) if arg then args.push(arg) return args cola.util.parseListener = (listener)-> argsMode = 1 argStr = listener.toString().match(/\([^\(\)]*\)/)[0] args = argStr.substring(1, argStr.length - 1).split(","); if args.length if cola.util.trim(args[0]) is "arg" then argsMode = 2 listener._argsMode = argsMode return argsMode cola.util.isCompatibleType = (baseType, type)-> if type == baseType then return true while type.__super__ type = type.__super__.constructor if type == baseType then return true return false cola.util.delay = (owner, name, delay, fn)-> cola.util.cancelDelay(owner, name) owner["_timer_" + name] = setTimeout(()-> fn.call(owner) return , delay) return cola.util.cancelDelay = (owner, name)-> key = PI:KEY:<KEY>END_PI timerId = owner[key] if timerId delete owner[key] clearTimeout(timerId) return cola.util.formatDate = (date, pattern)-> return "" unless date? if not (date instanceof XDate) date = new XDate(date) return date.toString(pattern or cola.setting("defaultDateFormat")) cola.util.formatNumber = (number, pattern)-> return "" unless number? return number if isNaN(number) return formatNumber(pattern or cola.setting("defaultNumberFormat"), number) cola.util.format = (value, format)-> if value is null or value is undefined or value is "" return "" else if value instanceof Date return cola.util.formatDate(value, format) else if isFinite(value) return cola.util.formatNumber(value, format) else if value and typeof value is "string" date = (new XDate(value)).toDate() if not isFinite(date) return value else return cola.util.formatDate(date, format) else return value cola.util.getItemByItemDom = (dom)-> scope = cola.util.userData(dom, "scope") if scope and scope instanceof cola.ItemScope return scope.data.getItemData() domBinding = cola.util.userData(dom, cola.constants.DOM_BINDING_KEY) if domBinding scope = domBinding.scope if scope and scope instanceof cola.ItemScope return scope.data.getItemData() if dom.parentNode return cola.util.getItemByItemDom(dom.parentNode) else return null ## URL cola.util.queryParams = ()-> decode = (str)-> decodeURIComponent((str || "").replace(/\+/g, " ")) query = (window.location.search || "").substring(1) params = {} if query.length > 0 for param, i in query.split("&") pair = param.split("=") key = decode(pair.shift()) value = decode(if pair.length then pair.join("=") else null) if (params.hasOwnProperty(key)) oldValue = params[key] if oldValue instanceof Array oldValue.push(value) else params[key] = [oldValue, value] else params[key] = value return params cola.util.pathParams = (prefix, index = 0)-> path = (window.location.pathname || "").replace(/^\//, "") parts = path.split("/") i = parts.indexOf(prefix) if i >= 0 return parts[i + 1 + index] else return ## Dictionary keyValuesMap = {} dictionaryMap = {} cola.util.dictionary = (name, keyValues)-> if keyValues is null delete keyValuesMap[name] delete dictionaryMap[name] return else if keyValues is undefined return keyValuesMap[name] else if keyValues instanceof Array keyValuesMap[name] = keyValues dictionaryMap[name] = dictionary = {} for pair in keyValues dictionary[pair.key or ""] = pair.value return dictionary else keyValuesMap[name] = values = [] for key, value of keyValues values.push( key: key value: value ) dictionaryMap[name] = keyValues return keyValues cola.util.translate = (dictionaryName, key)-> return dictionaryMap[dictionaryName]?[key or ""] # OO cola.util.isSuperClass = (superCls, cls)-> return false unless superCls while cls return true if cls.__super__ is superCls:: cls = cls.__super__?.constructor return false
[ { "context": "\ntest_passwords = '''\nzxcvbn\nqwER43@!\nTr0ub4dour&3\ncorrecthorsebatteryst", "end": 21, "score": 0.9680730104446411, "start": 21, "tag": "PASSWORD", "value": "" }, { "context": "\ntest_passwords = '''\nzxcvbn\nqwER43@!\nTr0ub4dour&3\ncorrecthorsebatterystaple\nco", "end": 28, "score": 0.9408754110336304, "start": 22, "tag": "PASSWORD", "value": "zxcvbn" }, { "context": "\ntest_passwords = '''\nzxcvbn\nqwER43@!\nTr0ub4dour&3\ncorrecthorsebatterystaple\ncoRrecth0rseba++ery9.23.2007staple$\n\nD0g.........", "end": 76, "score": 0.9406453967094421, "start": 29, "tag": "PASSWORD", "value": "qwER43@!\nTr0ub4dour&3\ncorrecthorsebatterystaple" }, { "context": "......\nabcdefghijk987654321\nneverforget13/3/1997\n1qaz2wsx3edc\n\ntemppass22\nbriansmith\nbriansmith4mayor\npasswo", "end": 187, "score": 0.8337382674217224, "start": 179, "tag": "PASSWORD", "value": "qaz2wsx3" }, { "context": "21\nneverforget13/3/1997\n1qaz2wsx3edc\n\ntemppass22\nbriansmith\nbriansmith4mayor\npassword1\nviking\nthx1138\nScoRpi0", "end": 213, "score": 0.8661907315254211, "start": 204, "tag": "PASSWORD", "value": "riansmith" }, { "context": "get13/3/1997\n1qaz2wsx3edc\n\ntemppass22\nbriansmith\nbriansmith4mayor\npassword1\nviking\nthx1138\nScoRpi0ns\ndo you know\n", "end": 228, "score": 0.8155181407928467, "start": 215, "tag": "PASSWORD", "value": "riansmith4may" }, { "context": "mppass22\nbriansmith\nbriansmith4mayor\npassword1\nviking\nthx1138\nScoRpi0ns\ndo you know\n\nryanhunter2000\nria", "end": 247, "score": 0.8201555013656616, "start": 244, "tag": "PASSWORD", "value": "ing" }, { "context": "22\nbriansmith\nbriansmith4mayor\npassword1\nviking\nthx1138\nScoRpi0ns\ndo you know\n\nryanhunter2000\nrianhunter2", "end": 255, "score": 0.7747747302055359, "start": 250, "tag": "PASSWORD", "value": "x1138" }, { "context": "r\npassword1\nviking\nthx1138\nScoRpi0ns\ndo you know\n\nryanhunter2000\nrianhunter2000\n\nasdfghju7654rewq\nAOEUIDHG&*()L", "end": 290, "score": 0.9352980852127075, "start": 279, "tag": "USERNAME", "value": "ryanhunter2" }, { "context": "ing\nthx1138\nScoRpi0ns\ndo you know\n\nryanhunter2000\nrianhunter2000\n\nasdfghju7654rewq\nAOEUIDHG&*()LS_\n\n12345678\nde", "end": 305, "score": 0.9563693404197693, "start": 294, "tag": "USERNAME", "value": "rianhunter2" }, { "context": "ScoRpi0ns\ndo you know\n\nryanhunter2000\nrianhunter2000\n\nasdfghju7654rewq\nAOEUIDHG&*()LS_\n\n12345678\ndefgh", "end": 308, "score": 0.6591482162475586, "start": 306, "tag": "USERNAME", "value": "00" } ]
contrib/client/zxcvbn-1.0/test/test.coffee
stdjon/httplib
2
test_passwords = ''' zxcvbn qwER43@! Tr0ub4dour&3 correcthorsebatterystaple coRrecth0rseba++ery9.23.2007staple$ D0g.................. abcdefghijk987654321 neverforget13/3/1997 1qaz2wsx3edc temppass22 briansmith briansmith4mayor password1 viking thx1138 ScoRpi0ns do you know ryanhunter2000 rianhunter2000 asdfghju7654rewq AOEUIDHG&*()LS_ 12345678 defghi6789 rosebud Rosebud ROSEBUD rosebuD ros3bud99 r0s3bud99 R0$38uD99 verlineVANDERMARK eheuczkqyq rWibMFACxAUGZmxhVncy Ba9ZyWABu99[BK#6MBgbH88Tofv)vs$w ''' results_tmpl = ''' {{#results}} <table class="result"> <tr> <td>password: </td> <td><strong>{{password}}</strong></td> </tr> <tr> <td>entropy: </td> <td>{{entropy}}</td> </tr> <tr> <td>crack time (seconds): </td> <td>{{crack_time}}</td> </tr> <tr> <td>crack time (display): </td> <td>{{crack_time_display}}</td> </tr> <tr> <td>score from 0 to 4:</td> <td>{{score}}</td> </tr> <tr> <td>calculation time (ms): </td> <td>{{calc_time}}</td> </tr> <tr> <td colspan="2"><strong>match sequence:</strong></td> </tr> </table> {{& match_sequence_display}} {{/results}} ''' props_tmpl = ''' <div class="match-sequence"> {{#match_sequence}} <table> <tr> <td colspan="2">'{{token}}'</td> </tr> <tr> <td>pattern:</td> <td>{{pattern}}</td> </tr> <tr> <td>entropy:</td> <td>{{entropy}}</td> </tr> {{#cardinality}} <tr> <td>cardinality:</td> <td>{{cardinality}}</td> </tr> {{/cardinality}} {{#rank}} <tr> <td>dict-name:</td> <td>{{dictionary_name}}</td> </tr> <tr> <td>rank:</td> <td>{{rank}}</td> </tr> <tr> <td>base-entropy:</td> <td>{{base_entropy}}</td> </tr> <tr> <td>upper-entropy:</td> <td>{{uppercase_entropy}}</td> </tr> {{/rank}} {{#l33t}} <tr> <td>l33t-entropy:</td> <td>{{l33t_entropy}}</td> </tr> <tr> <td>l33t subs:</td> <td>{{sub_display}}</td> </tr> <tr> <td>un-l33ted:</td> <td>{{matched_word}}</td> </tr> {{/l33t}} {{#graph}} <tr> <td>graph: </td> <td>{{graph}}</td> </tr> <tr> <td>turns: </td> <td>{{turns}}</td> </tr> <tr> <td>shifted keys: </td> <td>{{shifted_count}}</td> </tr> {{/graph}} {{#repeated_char}} <tr> <td>repeat-char:</td> <td>'{{repeated_char}}'</td> </tr> {{/repeated_char}} {{#sequence_name}} <tr> <td>sequence-name:</td> <td>{{sequence_name}}</td> </tr> <tr> <td>sequence-size</td> <td>{{sequence_space}}</td> </tr> <tr> <td>ascending:</td> <td>{{ascending}}</td> </tr> {{/sequence_name}} {{#day}} <tr> <td>day:</td> <td>{{day}}</td> </tr> <tr> <td>month:</td> <td>{{month}}</td> </tr> <tr> <td>year:</td> <td>{{year}}</td> </tr> <tr> <td>separator:</td> <td>'{{separator}}'</td> </tr> {{/day}} </table> {{/match_sequence}} </div> ''' zxcvbn_load_hook = -> $ -> results_lst = [] for password in test_passwords.split('\n') when password r = zxcvbn(password) r.match_sequence_display = Mustache.render(props_tmpl, r) results_lst.push r rendered = Mustache.render(results_tmpl, { results: results_lst, }) $('#results').html(rendered) last_q = '' _listener = -> current = $('#search-bar').val() unless current $('#search-results').html('') return if current != last_q last_q = current r = zxcvbn(current) r.match_sequence_display = Mustache.render(props_tmpl, r) results = {results: [r]} rendered = Mustache.render(results_tmpl, results) $('#search-results').html(rendered) setInterval _listener, 100
28563
test_passwords = '''<PASSWORD> <PASSWORD> <PASSWORD> coRrecth0rseba++ery9.23.2007staple$ D0g.................. abcdefghijk987654321 neverforget13/3/1997 1<PASSWORD>edc temppass22 b<PASSWORD> b<PASSWORD>or password1 vik<PASSWORD> th<PASSWORD> ScoRpi0ns do you know ryanhunter2000 rianhunter2000 asdfghju7654rewq AOEUIDHG&*()LS_ 12345678 defghi6789 rosebud Rosebud ROSEBUD rosebuD ros3bud99 r0s3bud99 R0$38uD99 verlineVANDERMARK eheuczkqyq rWibMFACxAUGZmxhVncy Ba9ZyWABu99[BK#6MBgbH88Tofv)vs$w ''' results_tmpl = ''' {{#results}} <table class="result"> <tr> <td>password: </td> <td><strong>{{password}}</strong></td> </tr> <tr> <td>entropy: </td> <td>{{entropy}}</td> </tr> <tr> <td>crack time (seconds): </td> <td>{{crack_time}}</td> </tr> <tr> <td>crack time (display): </td> <td>{{crack_time_display}}</td> </tr> <tr> <td>score from 0 to 4:</td> <td>{{score}}</td> </tr> <tr> <td>calculation time (ms): </td> <td>{{calc_time}}</td> </tr> <tr> <td colspan="2"><strong>match sequence:</strong></td> </tr> </table> {{& match_sequence_display}} {{/results}} ''' props_tmpl = ''' <div class="match-sequence"> {{#match_sequence}} <table> <tr> <td colspan="2">'{{token}}'</td> </tr> <tr> <td>pattern:</td> <td>{{pattern}}</td> </tr> <tr> <td>entropy:</td> <td>{{entropy}}</td> </tr> {{#cardinality}} <tr> <td>cardinality:</td> <td>{{cardinality}}</td> </tr> {{/cardinality}} {{#rank}} <tr> <td>dict-name:</td> <td>{{dictionary_name}}</td> </tr> <tr> <td>rank:</td> <td>{{rank}}</td> </tr> <tr> <td>base-entropy:</td> <td>{{base_entropy}}</td> </tr> <tr> <td>upper-entropy:</td> <td>{{uppercase_entropy}}</td> </tr> {{/rank}} {{#l33t}} <tr> <td>l33t-entropy:</td> <td>{{l33t_entropy}}</td> </tr> <tr> <td>l33t subs:</td> <td>{{sub_display}}</td> </tr> <tr> <td>un-l33ted:</td> <td>{{matched_word}}</td> </tr> {{/l33t}} {{#graph}} <tr> <td>graph: </td> <td>{{graph}}</td> </tr> <tr> <td>turns: </td> <td>{{turns}}</td> </tr> <tr> <td>shifted keys: </td> <td>{{shifted_count}}</td> </tr> {{/graph}} {{#repeated_char}} <tr> <td>repeat-char:</td> <td>'{{repeated_char}}'</td> </tr> {{/repeated_char}} {{#sequence_name}} <tr> <td>sequence-name:</td> <td>{{sequence_name}}</td> </tr> <tr> <td>sequence-size</td> <td>{{sequence_space}}</td> </tr> <tr> <td>ascending:</td> <td>{{ascending}}</td> </tr> {{/sequence_name}} {{#day}} <tr> <td>day:</td> <td>{{day}}</td> </tr> <tr> <td>month:</td> <td>{{month}}</td> </tr> <tr> <td>year:</td> <td>{{year}}</td> </tr> <tr> <td>separator:</td> <td>'{{separator}}'</td> </tr> {{/day}} </table> {{/match_sequence}} </div> ''' zxcvbn_load_hook = -> $ -> results_lst = [] for password in test_passwords.split('\n') when password r = zxcvbn(password) r.match_sequence_display = Mustache.render(props_tmpl, r) results_lst.push r rendered = Mustache.render(results_tmpl, { results: results_lst, }) $('#results').html(rendered) last_q = '' _listener = -> current = $('#search-bar').val() unless current $('#search-results').html('') return if current != last_q last_q = current r = zxcvbn(current) r.match_sequence_display = Mustache.render(props_tmpl, r) results = {results: [r]} rendered = Mustache.render(results_tmpl, results) $('#search-results').html(rendered) setInterval _listener, 100
true
test_passwords = '''PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI coRrecth0rseba++ery9.23.2007staple$ D0g.................. abcdefghijk987654321 neverforget13/3/1997 1PI:PASSWORD:<PASSWORD>END_PIedc temppass22 bPI:PASSWORD:<PASSWORD>END_PI bPI:PASSWORD:<PASSWORD>END_PIor password1 vikPI:PASSWORD:<PASSWORD>END_PI thPI:PASSWORD:<PASSWORD>END_PI ScoRpi0ns do you know ryanhunter2000 rianhunter2000 asdfghju7654rewq AOEUIDHG&*()LS_ 12345678 defghi6789 rosebud Rosebud ROSEBUD rosebuD ros3bud99 r0s3bud99 R0$38uD99 verlineVANDERMARK eheuczkqyq rWibMFACxAUGZmxhVncy Ba9ZyWABu99[BK#6MBgbH88Tofv)vs$w ''' results_tmpl = ''' {{#results}} <table class="result"> <tr> <td>password: </td> <td><strong>{{password}}</strong></td> </tr> <tr> <td>entropy: </td> <td>{{entropy}}</td> </tr> <tr> <td>crack time (seconds): </td> <td>{{crack_time}}</td> </tr> <tr> <td>crack time (display): </td> <td>{{crack_time_display}}</td> </tr> <tr> <td>score from 0 to 4:</td> <td>{{score}}</td> </tr> <tr> <td>calculation time (ms): </td> <td>{{calc_time}}</td> </tr> <tr> <td colspan="2"><strong>match sequence:</strong></td> </tr> </table> {{& match_sequence_display}} {{/results}} ''' props_tmpl = ''' <div class="match-sequence"> {{#match_sequence}} <table> <tr> <td colspan="2">'{{token}}'</td> </tr> <tr> <td>pattern:</td> <td>{{pattern}}</td> </tr> <tr> <td>entropy:</td> <td>{{entropy}}</td> </tr> {{#cardinality}} <tr> <td>cardinality:</td> <td>{{cardinality}}</td> </tr> {{/cardinality}} {{#rank}} <tr> <td>dict-name:</td> <td>{{dictionary_name}}</td> </tr> <tr> <td>rank:</td> <td>{{rank}}</td> </tr> <tr> <td>base-entropy:</td> <td>{{base_entropy}}</td> </tr> <tr> <td>upper-entropy:</td> <td>{{uppercase_entropy}}</td> </tr> {{/rank}} {{#l33t}} <tr> <td>l33t-entropy:</td> <td>{{l33t_entropy}}</td> </tr> <tr> <td>l33t subs:</td> <td>{{sub_display}}</td> </tr> <tr> <td>un-l33ted:</td> <td>{{matched_word}}</td> </tr> {{/l33t}} {{#graph}} <tr> <td>graph: </td> <td>{{graph}}</td> </tr> <tr> <td>turns: </td> <td>{{turns}}</td> </tr> <tr> <td>shifted keys: </td> <td>{{shifted_count}}</td> </tr> {{/graph}} {{#repeated_char}} <tr> <td>repeat-char:</td> <td>'{{repeated_char}}'</td> </tr> {{/repeated_char}} {{#sequence_name}} <tr> <td>sequence-name:</td> <td>{{sequence_name}}</td> </tr> <tr> <td>sequence-size</td> <td>{{sequence_space}}</td> </tr> <tr> <td>ascending:</td> <td>{{ascending}}</td> </tr> {{/sequence_name}} {{#day}} <tr> <td>day:</td> <td>{{day}}</td> </tr> <tr> <td>month:</td> <td>{{month}}</td> </tr> <tr> <td>year:</td> <td>{{year}}</td> </tr> <tr> <td>separator:</td> <td>'{{separator}}'</td> </tr> {{/day}} </table> {{/match_sequence}} </div> ''' zxcvbn_load_hook = -> $ -> results_lst = [] for password in test_passwords.split('\n') when password r = zxcvbn(password) r.match_sequence_display = Mustache.render(props_tmpl, r) results_lst.push r rendered = Mustache.render(results_tmpl, { results: results_lst, }) $('#results').html(rendered) last_q = '' _listener = -> current = $('#search-bar').val() unless current $('#search-results').html('') return if current != last_q last_q = current r = zxcvbn(current) r.match_sequence_display = Mustache.render(props_tmpl, r) results = {results: [r]} rendered = Mustache.render(results_tmpl, results) $('#search-results').html(rendered) setInterval _listener, 100
[ { "context": "\"fs\"\nlibraries = {}\nscripts =\n init:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: []\n upda", "end": 176, "score": 0.996023952960968, "start": 166, "tag": "KEY", "value": "b_settings" }, { "context": " = {}\nscripts =\n init:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: []\n updateSettings:\n ", "end": 189, "score": 0.9438126683235168, "start": 180, "tag": "KEY", "value": "b_running" }, { "context": " =\n init:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: []\n updateSettings:\n keys: [\"b_se", "end": 204, "score": 0.9235000014305115, "start": 193, "tag": "KEY", "value": "b_executing" }, { "context": "ting\"]\n libs: []\n updateSettings:\n keys: [\"b_settings\"]\n libs: []\n running:\n keys: [\"b_settings\"", "end": 260, "score": 0.9914607405662537, "start": 250, "tag": "KEY", "value": "b_settings" }, { "context": "\"b_settings\"]\n libs: []\n running:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh", "end": 309, "score": 0.989549458026886, "start": 299, "tag": "KEY", "value": "b_settings" }, { "context": " libs: []\n running:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\"]\n ", "end": 322, "score": 0.9199970364570618, "start": 313, "tag": "KEY", "value": "b_running" }, { "context": " running:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\"]\n check:\n keys", "end": 337, "score": 0.9390061497688293, "start": 326, "tag": "KEY", "value": "b_executing" }, { "context": " libs: [\"refresh_running\"]\n check:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_r", "end": 403, "score": 0.9597190022468567, "start": 391, "tag": "KEY", "value": "b_settings\"," }, { "context": "resh_running\"]\n check:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\", \"con", "end": 416, "score": 0.9377912282943726, "start": 405, "tag": "KEY", "value": "b_running\"," }, { "context": "]\n check:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\", \"conditions_check", "end": 429, "score": 0.966519832611084, "start": 418, "tag": "KEY", "value": "b_executing" }, { "context": "nning\", \"conditions_check\"]\n submit:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh", "end": 514, "score": 0.9947230219841003, "start": 504, "tag": "KEY", "value": "b_settings" }, { "context": "tions_check\"]\n submit:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\", \"con", "end": 529, "score": 0.8288503289222717, "start": 518, "tag": "KEY", "value": "b_running\"," }, { "context": "\n submit:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\", \"conditions_check", "end": 542, "score": 0.9108948707580566, "start": 531, "tag": "KEY", "value": "b_executing" }, { "context": "ing\", \"conditions_check\"]\n register:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh", "end": 629, "score": 0.9935616850852966, "start": 619, "tag": "KEY", "value": "b_settings" }, { "context": "ons_check\"]\n register:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\", \"con", "end": 644, "score": 0.8348021507263184, "start": 633, "tag": "KEY", "value": "b_running\"," }, { "context": " register:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\", \"conditions_check", "end": 657, "score": 0.9651995301246643, "start": 646, "tag": "KEY", "value": "b_executing" }, { "context": "running\", \"conditions_check\"]\n free:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_r", "end": 742, "score": 0.9804084897041321, "start": 730, "tag": "KEY", "value": "b_settings\"," }, { "context": "ditions_check\"]\n free:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\"]\n cu", "end": 755, "score": 0.9087504148483276, "start": 744, "tag": "KEY", "value": "b_running\"," }, { "context": "\"]\n free:\n keys: [\"b_settings\", \"b_running\", \"b_executing\"]\n libs: [\"refresh_running\"]\n current_reservo", "end": 768, "score": 0.9379499554634094, "start": 757, "tag": "KEY", "value": "b_executing" }, { "context": "efresh_running\"]\n current_reservoir:\n keys: [\"b_settings\"]\n libs: []\n increment_reservoir:\n keys: [", "end": 844, "score": 0.9920771718025208, "start": 834, "tag": "KEY", "value": "b_settings" }, { "context": "]\n libs: []\n increment_reservoir:\n keys: [\"b_settings\"]\n libs: []\n\n# Runs as-is in Node, but it also", "end": 905, "score": 0.9665215015411377, "start": 895, "tag": "KEY", "value": "b_settings" } ]
src/RedisStorage.coffee
VinayaSathyanarayana/bottleneck
0
parser = require "./parser" DLList = require "./DLList" BottleneckError = require "./BottleneckError" fs = require "fs" libraries = {} scripts = init: keys: ["b_settings", "b_running", "b_executing"] libs: [] updateSettings: keys: ["b_settings"] libs: [] running: keys: ["b_settings", "b_running", "b_executing"] libs: ["refresh_running"] check: keys: ["b_settings", "b_running", "b_executing"] libs: ["refresh_running", "conditions_check"] submit: keys: ["b_settings", "b_running", "b_executing"] libs: ["refresh_running", "conditions_check"] register: keys: ["b_settings", "b_running", "b_executing"] libs: ["refresh_running", "conditions_check"] free: keys: ["b_settings", "b_running", "b_executing"] libs: ["refresh_running"] current_reservoir: keys: ["b_settings"] libs: [] increment_reservoir: keys: ["b_settings"] libs: [] # Runs as-is in Node, but it also gets preprocessed by brfs # brfs looks for the pattern "fs.readFile [string], [function]", can't use variables here fs.readFile "./src/redis/refresh_running.lua", (err, data) -> if err? then throw err else libraries["refresh_running"] = data.toString "utf8" fs.readFile "./src/redis/conditions_check.lua", (err, data) -> if err? then throw err else libraries["conditions_check"] = data.toString "utf8" fs.readFile "./src/redis/init.lua", (err, data) -> if err? then throw err else scripts["init"].code = data.toString "utf8" fs.readFile "./src/redis/running.lua", (err, data) -> if err? then throw err else scripts["running"].code = data.toString "utf8" fs.readFile "./src/redis/update_settings.lua", (err, data) -> if err? then throw err else scripts["updateSettings"].code = data.toString "utf8" fs.readFile "./src/redis/check.lua", (err, data) -> if err? then throw err else scripts["check"].code = data.toString "utf8" fs.readFile "./src/redis/submit.lua", (err, data) -> if err? then throw err else scripts["submit"].code = data.toString "utf8" fs.readFile "./src/redis/register.lua", (err, data) -> if err? then throw err else scripts["register"].code = data.toString "utf8" fs.readFile "./src/redis/free.lua", (err, data) -> if err? then throw err else scripts["free"].code = data.toString "utf8" fs.readFile "./src/redis/current_reservoir.lua", (err, data) -> if err? then throw err else scripts["current_reservoir"].code = data.toString "utf8" fs.readFile "./src/redis/increment_reservoir.lua", (err, data) -> if err? then throw err else scripts["increment_reservoir"].code = data.toString "utf8" class RedisStorage constructor: (@instance, initSettings, options) -> redis = require "redis" parser.load options, options, @ @client = redis.createClient @clientOptions @subClient = redis.createClient @clientOptions @shas = {} @ready = new @Promise (resolve, reject) => count = 0 done = -> count++ if count == 2 then resolve() @client.on "error", (e) -> reject e @client.on "ready", -> done() @subClient.on "error", (e) -> reject e @subClient.on "ready", => @subClient.on "subscribe", -> done() @subClient.subscribe "bottleneck" .then @loadAll .then => @subClient.on "message", (channel, message) => [type, info] = message.split ":" if type == "freed" then @instance._drainAll ~~info initSettings.nextRequest = Date.now() initSettings.running = 0 initSettings.unblockTime = 0 # initSettings.version = args = @prepareObject(initSettings) args.unshift (if options.clearDatastore then 1 else 0) @runScript "init", args .then (results) => # console.log @shas @client disconnect: (flush) -> @client.end flush @subClient.end flush @ loadScript: (name) -> new @Promise (resolve, reject) => payload = scripts[name].libs.map (lib) -> libraries[lib] .join("\n") + scripts[name].code @client.multi([["script", "load", payload]]).exec (err, replies) => if err? then return reject err @shas[name] = replies[0] return resolve replies[0] loadAll: => @Promise.all(for k, v of scripts then @loadScript k) prepareArray: (arr) -> arr.map (x) -> if x? then x.toString() else "" prepareObject: (obj) -> arr = [] for k, v of obj then arr.push k, (if v? then v.toString() else "") arr runScript: (name, args) -> new @Promise (resolve, reject) => script = scripts[name] arr = [@shas[name], script.keys.length].concat script.keys, args, (err, replies) -> if err? then return reject err return resolve replies @client.evalsha.bind(@client).apply {}, arr convertBool: (b) -> !!b __updateSettings__: (options) -> @runScript "updateSettings", @prepareObject options __running__: -> await @runScript "running", [Date.now()] __incrementReservoir__: (incr) -> @runScript "increment_reservoir", [incr] __currentReservoir__: -> @runScript "current_reservoir", @prepareArray [] __check__: (weight) -> @convertBool await @runScript "check", @prepareArray [weight, Date.now()] __register__: (index, weight, expiration) -> [success, wait] = await @runScript "register", @prepareArray [index, weight, expiration, Date.now()] return { success: @convertBool(success), wait } __submit__: (queueLength, weight) -> try [reachedHWM, blocked, strategy] = await @runScript "submit", @prepareArray [queueLength, weight, Date.now()] return { reachedHWM: @convertBool(reachedHWM), blocked: @convertBool(blocked), strategy } catch e if e.message.indexOf("OVERWEIGHT") == 0 [overweight, weight, maxConcurrent] = e.message.split " " throw new BottleneckError("Impossible to add a job having a weight of #{weight} to a limiter having a maxConcurrent setting of #{maxConcurrent}") else throw e __free__: (index, weight) -> result = await @runScript "free", @prepareArray [index, Date.now()] return { running: result } module.exports = RedisStorage
217608
parser = require "./parser" DLList = require "./DLList" BottleneckError = require "./BottleneckError" fs = require "fs" libraries = {} scripts = init: keys: ["<KEY>", "<KEY>", "<KEY>"] libs: [] updateSettings: keys: ["<KEY>"] libs: [] running: keys: ["<KEY>", "<KEY>", "<KEY>"] libs: ["refresh_running"] check: keys: ["<KEY> "<KEY> "<KEY>"] libs: ["refresh_running", "conditions_check"] submit: keys: ["<KEY>", "<KEY> "<KEY>"] libs: ["refresh_running", "conditions_check"] register: keys: ["<KEY>", "<KEY> "<KEY>"] libs: ["refresh_running", "conditions_check"] free: keys: ["<KEY> "<KEY> "<KEY>"] libs: ["refresh_running"] current_reservoir: keys: ["<KEY>"] libs: [] increment_reservoir: keys: ["<KEY>"] libs: [] # Runs as-is in Node, but it also gets preprocessed by brfs # brfs looks for the pattern "fs.readFile [string], [function]", can't use variables here fs.readFile "./src/redis/refresh_running.lua", (err, data) -> if err? then throw err else libraries["refresh_running"] = data.toString "utf8" fs.readFile "./src/redis/conditions_check.lua", (err, data) -> if err? then throw err else libraries["conditions_check"] = data.toString "utf8" fs.readFile "./src/redis/init.lua", (err, data) -> if err? then throw err else scripts["init"].code = data.toString "utf8" fs.readFile "./src/redis/running.lua", (err, data) -> if err? then throw err else scripts["running"].code = data.toString "utf8" fs.readFile "./src/redis/update_settings.lua", (err, data) -> if err? then throw err else scripts["updateSettings"].code = data.toString "utf8" fs.readFile "./src/redis/check.lua", (err, data) -> if err? then throw err else scripts["check"].code = data.toString "utf8" fs.readFile "./src/redis/submit.lua", (err, data) -> if err? then throw err else scripts["submit"].code = data.toString "utf8" fs.readFile "./src/redis/register.lua", (err, data) -> if err? then throw err else scripts["register"].code = data.toString "utf8" fs.readFile "./src/redis/free.lua", (err, data) -> if err? then throw err else scripts["free"].code = data.toString "utf8" fs.readFile "./src/redis/current_reservoir.lua", (err, data) -> if err? then throw err else scripts["current_reservoir"].code = data.toString "utf8" fs.readFile "./src/redis/increment_reservoir.lua", (err, data) -> if err? then throw err else scripts["increment_reservoir"].code = data.toString "utf8" class RedisStorage constructor: (@instance, initSettings, options) -> redis = require "redis" parser.load options, options, @ @client = redis.createClient @clientOptions @subClient = redis.createClient @clientOptions @shas = {} @ready = new @Promise (resolve, reject) => count = 0 done = -> count++ if count == 2 then resolve() @client.on "error", (e) -> reject e @client.on "ready", -> done() @subClient.on "error", (e) -> reject e @subClient.on "ready", => @subClient.on "subscribe", -> done() @subClient.subscribe "bottleneck" .then @loadAll .then => @subClient.on "message", (channel, message) => [type, info] = message.split ":" if type == "freed" then @instance._drainAll ~~info initSettings.nextRequest = Date.now() initSettings.running = 0 initSettings.unblockTime = 0 # initSettings.version = args = @prepareObject(initSettings) args.unshift (if options.clearDatastore then 1 else 0) @runScript "init", args .then (results) => # console.log @shas @client disconnect: (flush) -> @client.end flush @subClient.end flush @ loadScript: (name) -> new @Promise (resolve, reject) => payload = scripts[name].libs.map (lib) -> libraries[lib] .join("\n") + scripts[name].code @client.multi([["script", "load", payload]]).exec (err, replies) => if err? then return reject err @shas[name] = replies[0] return resolve replies[0] loadAll: => @Promise.all(for k, v of scripts then @loadScript k) prepareArray: (arr) -> arr.map (x) -> if x? then x.toString() else "" prepareObject: (obj) -> arr = [] for k, v of obj then arr.push k, (if v? then v.toString() else "") arr runScript: (name, args) -> new @Promise (resolve, reject) => script = scripts[name] arr = [@shas[name], script.keys.length].concat script.keys, args, (err, replies) -> if err? then return reject err return resolve replies @client.evalsha.bind(@client).apply {}, arr convertBool: (b) -> !!b __updateSettings__: (options) -> @runScript "updateSettings", @prepareObject options __running__: -> await @runScript "running", [Date.now()] __incrementReservoir__: (incr) -> @runScript "increment_reservoir", [incr] __currentReservoir__: -> @runScript "current_reservoir", @prepareArray [] __check__: (weight) -> @convertBool await @runScript "check", @prepareArray [weight, Date.now()] __register__: (index, weight, expiration) -> [success, wait] = await @runScript "register", @prepareArray [index, weight, expiration, Date.now()] return { success: @convertBool(success), wait } __submit__: (queueLength, weight) -> try [reachedHWM, blocked, strategy] = await @runScript "submit", @prepareArray [queueLength, weight, Date.now()] return { reachedHWM: @convertBool(reachedHWM), blocked: @convertBool(blocked), strategy } catch e if e.message.indexOf("OVERWEIGHT") == 0 [overweight, weight, maxConcurrent] = e.message.split " " throw new BottleneckError("Impossible to add a job having a weight of #{weight} to a limiter having a maxConcurrent setting of #{maxConcurrent}") else throw e __free__: (index, weight) -> result = await @runScript "free", @prepareArray [index, Date.now()] return { running: result } module.exports = RedisStorage
true
parser = require "./parser" DLList = require "./DLList" BottleneckError = require "./BottleneckError" fs = require "fs" libraries = {} scripts = init: keys: ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"] libs: [] updateSettings: keys: ["PI:KEY:<KEY>END_PI"] libs: [] running: keys: ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"] libs: ["refresh_running"] check: keys: ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"] libs: ["refresh_running", "conditions_check"] submit: keys: ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"] libs: ["refresh_running", "conditions_check"] register: keys: ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"] libs: ["refresh_running", "conditions_check"] free: keys: ["PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI"] libs: ["refresh_running"] current_reservoir: keys: ["PI:KEY:<KEY>END_PI"] libs: [] increment_reservoir: keys: ["PI:KEY:<KEY>END_PI"] libs: [] # Runs as-is in Node, but it also gets preprocessed by brfs # brfs looks for the pattern "fs.readFile [string], [function]", can't use variables here fs.readFile "./src/redis/refresh_running.lua", (err, data) -> if err? then throw err else libraries["refresh_running"] = data.toString "utf8" fs.readFile "./src/redis/conditions_check.lua", (err, data) -> if err? then throw err else libraries["conditions_check"] = data.toString "utf8" fs.readFile "./src/redis/init.lua", (err, data) -> if err? then throw err else scripts["init"].code = data.toString "utf8" fs.readFile "./src/redis/running.lua", (err, data) -> if err? then throw err else scripts["running"].code = data.toString "utf8" fs.readFile "./src/redis/update_settings.lua", (err, data) -> if err? then throw err else scripts["updateSettings"].code = data.toString "utf8" fs.readFile "./src/redis/check.lua", (err, data) -> if err? then throw err else scripts["check"].code = data.toString "utf8" fs.readFile "./src/redis/submit.lua", (err, data) -> if err? then throw err else scripts["submit"].code = data.toString "utf8" fs.readFile "./src/redis/register.lua", (err, data) -> if err? then throw err else scripts["register"].code = data.toString "utf8" fs.readFile "./src/redis/free.lua", (err, data) -> if err? then throw err else scripts["free"].code = data.toString "utf8" fs.readFile "./src/redis/current_reservoir.lua", (err, data) -> if err? then throw err else scripts["current_reservoir"].code = data.toString "utf8" fs.readFile "./src/redis/increment_reservoir.lua", (err, data) -> if err? then throw err else scripts["increment_reservoir"].code = data.toString "utf8" class RedisStorage constructor: (@instance, initSettings, options) -> redis = require "redis" parser.load options, options, @ @client = redis.createClient @clientOptions @subClient = redis.createClient @clientOptions @shas = {} @ready = new @Promise (resolve, reject) => count = 0 done = -> count++ if count == 2 then resolve() @client.on "error", (e) -> reject e @client.on "ready", -> done() @subClient.on "error", (e) -> reject e @subClient.on "ready", => @subClient.on "subscribe", -> done() @subClient.subscribe "bottleneck" .then @loadAll .then => @subClient.on "message", (channel, message) => [type, info] = message.split ":" if type == "freed" then @instance._drainAll ~~info initSettings.nextRequest = Date.now() initSettings.running = 0 initSettings.unblockTime = 0 # initSettings.version = args = @prepareObject(initSettings) args.unshift (if options.clearDatastore then 1 else 0) @runScript "init", args .then (results) => # console.log @shas @client disconnect: (flush) -> @client.end flush @subClient.end flush @ loadScript: (name) -> new @Promise (resolve, reject) => payload = scripts[name].libs.map (lib) -> libraries[lib] .join("\n") + scripts[name].code @client.multi([["script", "load", payload]]).exec (err, replies) => if err? then return reject err @shas[name] = replies[0] return resolve replies[0] loadAll: => @Promise.all(for k, v of scripts then @loadScript k) prepareArray: (arr) -> arr.map (x) -> if x? then x.toString() else "" prepareObject: (obj) -> arr = [] for k, v of obj then arr.push k, (if v? then v.toString() else "") arr runScript: (name, args) -> new @Promise (resolve, reject) => script = scripts[name] arr = [@shas[name], script.keys.length].concat script.keys, args, (err, replies) -> if err? then return reject err return resolve replies @client.evalsha.bind(@client).apply {}, arr convertBool: (b) -> !!b __updateSettings__: (options) -> @runScript "updateSettings", @prepareObject options __running__: -> await @runScript "running", [Date.now()] __incrementReservoir__: (incr) -> @runScript "increment_reservoir", [incr] __currentReservoir__: -> @runScript "current_reservoir", @prepareArray [] __check__: (weight) -> @convertBool await @runScript "check", @prepareArray [weight, Date.now()] __register__: (index, weight, expiration) -> [success, wait] = await @runScript "register", @prepareArray [index, weight, expiration, Date.now()] return { success: @convertBool(success), wait } __submit__: (queueLength, weight) -> try [reachedHWM, blocked, strategy] = await @runScript "submit", @prepareArray [queueLength, weight, Date.now()] return { reachedHWM: @convertBool(reachedHWM), blocked: @convertBool(blocked), strategy } catch e if e.message.indexOf("OVERWEIGHT") == 0 [overweight, weight, maxConcurrent] = e.message.split " " throw new BottleneckError("Impossible to add a job having a weight of #{weight} to a limiter having a maxConcurrent setting of #{maxConcurrent}") else throw e __free__: (index, weight) -> result = await @runScript "free", @prepareArray [index, Date.now()] return { running: result } module.exports = RedisStorage
[ { "context": "f items[i].sell_in < 0\n if items[i].name != 'Aged Brie'\n if items[i].name != 'Backstage passes to", "end": 1487, "score": 0.9996030330657959, "start": 1478, "tag": "NAME", "value": "Aged Brie" }, { "context": "s[i].quality > 0\n if items[i].name != 'Sulfuras, Hand of Ragnaros'\n items[i].quality", "end": 1636, "score": 0.9900352954864502, "start": 1628, "tag": "NAME", "value": "Sulfuras" } ]
Original.coffee
Adelost/CodeKata-GildedRose-Redesign
0
Item = (name, sell_in, quality) -> @name = name @sell_in = sell_in @quality = quality return class Item constructor: (@name, @sell_in, @quality) -> items = [ new Item("+5 Dexterity Vest", 10, 20), new Item("Aged Brie", 2, 0), new Item("Elixir of the Mongoose", 5, 7), new Item("Sulfuras, Hand of Ragnaros", 0, 80), new Item("Sulfuras, Hand of Ragnaros", -1, 80), new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20), new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49), new Item("Backstage passes to a TAFKAL80ETC concert", 5, 49), new Item("Conjured Mana Cake", 3, 6); ] update_quality = -> i = 0 while i < items.length if items[i].name != 'Aged Brie' and items[i].name != 'Backstage passes to a TAFKAL80ETC concert' if items[i].quality > 0 if items[i].name != 'Sulfuras, Hand of Ragnaros' items[i].quality = items[i].quality - 1 else if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].name == 'Backstage passes to a TAFKAL80ETC concert' if items[i].sell_in < 11 if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].sell_in < 6 if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].name != 'Sulfuras, Hand of Ragnaros' items[i].sell_in = items[i].sell_in - 1 if items[i].sell_in < 0 if items[i].name != 'Aged Brie' if items[i].name != 'Backstage passes to a TAFKAL80ETC concert' if items[i].quality > 0 if items[i].name != 'Sulfuras, Hand of Ragnaros' items[i].quality = items[i].quality - 1 else items[i].quality = items[i].quality - (items[i].quality) else if items[i].quality < 50 items[i].quality = items[i].quality + 1 i++ return
137547
Item = (name, sell_in, quality) -> @name = name @sell_in = sell_in @quality = quality return class Item constructor: (@name, @sell_in, @quality) -> items = [ new Item("+5 Dexterity Vest", 10, 20), new Item("Aged Brie", 2, 0), new Item("Elixir of the Mongoose", 5, 7), new Item("Sulfuras, Hand of Ragnaros", 0, 80), new Item("Sulfuras, Hand of Ragnaros", -1, 80), new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20), new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49), new Item("Backstage passes to a TAFKAL80ETC concert", 5, 49), new Item("Conjured Mana Cake", 3, 6); ] update_quality = -> i = 0 while i < items.length if items[i].name != 'Aged Brie' and items[i].name != 'Backstage passes to a TAFKAL80ETC concert' if items[i].quality > 0 if items[i].name != 'Sulfuras, Hand of Ragnaros' items[i].quality = items[i].quality - 1 else if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].name == 'Backstage passes to a TAFKAL80ETC concert' if items[i].sell_in < 11 if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].sell_in < 6 if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].name != 'Sulfuras, Hand of Ragnaros' items[i].sell_in = items[i].sell_in - 1 if items[i].sell_in < 0 if items[i].name != '<NAME>' if items[i].name != 'Backstage passes to a TAFKAL80ETC concert' if items[i].quality > 0 if items[i].name != '<NAME>, Hand of Ragnaros' items[i].quality = items[i].quality - 1 else items[i].quality = items[i].quality - (items[i].quality) else if items[i].quality < 50 items[i].quality = items[i].quality + 1 i++ return
true
Item = (name, sell_in, quality) -> @name = name @sell_in = sell_in @quality = quality return class Item constructor: (@name, @sell_in, @quality) -> items = [ new Item("+5 Dexterity Vest", 10, 20), new Item("Aged Brie", 2, 0), new Item("Elixir of the Mongoose", 5, 7), new Item("Sulfuras, Hand of Ragnaros", 0, 80), new Item("Sulfuras, Hand of Ragnaros", -1, 80), new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20), new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49), new Item("Backstage passes to a TAFKAL80ETC concert", 5, 49), new Item("Conjured Mana Cake", 3, 6); ] update_quality = -> i = 0 while i < items.length if items[i].name != 'Aged Brie' and items[i].name != 'Backstage passes to a TAFKAL80ETC concert' if items[i].quality > 0 if items[i].name != 'Sulfuras, Hand of Ragnaros' items[i].quality = items[i].quality - 1 else if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].name == 'Backstage passes to a TAFKAL80ETC concert' if items[i].sell_in < 11 if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].sell_in < 6 if items[i].quality < 50 items[i].quality = items[i].quality + 1 if items[i].name != 'Sulfuras, Hand of Ragnaros' items[i].sell_in = items[i].sell_in - 1 if items[i].sell_in < 0 if items[i].name != 'PI:NAME:<NAME>END_PI' if items[i].name != 'Backstage passes to a TAFKAL80ETC concert' if items[i].quality > 0 if items[i].name != 'PI:NAME:<NAME>END_PI, Hand of Ragnaros' items[i].quality = items[i].quality - 1 else items[i].quality = items[i].quality - (items[i].quality) else if items[i].quality < 50 items[i].quality = items[i].quality + 1 i++ return
[ { "context": "key: 'todo'\npatterns: [\n {\n # Borrowed from language-gfm", "end": 10, "score": 0.9662103056907654, "start": 6, "tag": "KEY", "value": "todo" }, { "context": "wed from language-gfm, because https://github.com/atom/language-todo/pull/36 isn't coming through\n ma", "end": 93, "score": 0.9975720047950745, "start": 89, "tag": "USERNAME", "value": "atom" } ]
grammars/repositories/inlines/todo.cson
doc22940/language-markdown
138
key: 'todo' patterns: [ { # Borrowed from language-gfm, because https://github.com/atom/language-todo/pull/36 isn't coming through match: '(?<!\\w)@?(TODO|FIXME|CHANGED|XXX|IDEA|HACK|NOTE|REVIEW|NB|BUG|QUESTION|COMBAK|TEMP)\\b' name: 'storage.type.class.${1:/downcase}.md' } ]
198630
key: '<KEY>' patterns: [ { # Borrowed from language-gfm, because https://github.com/atom/language-todo/pull/36 isn't coming through match: '(?<!\\w)@?(TODO|FIXME|CHANGED|XXX|IDEA|HACK|NOTE|REVIEW|NB|BUG|QUESTION|COMBAK|TEMP)\\b' name: 'storage.type.class.${1:/downcase}.md' } ]
true
key: 'PI:KEY:<KEY>END_PI' patterns: [ { # Borrowed from language-gfm, because https://github.com/atom/language-todo/pull/36 isn't coming through match: '(?<!\\w)@?(TODO|FIXME|CHANGED|XXX|IDEA|HACK|NOTE|REVIEW|NB|BUG|QUESTION|COMBAK|TEMP)\\b' name: 'storage.type.class.${1:/downcase}.md' } ]
[ { "context": " uuid: 'dim-green'\n token: 'blue-purple'\n toUuid: 'bright-green'\n f", "end": 561, "score": 0.6870265603065491, "start": 550, "tag": "PASSWORD", "value": "blue-purple" }, { "context": " uuid: 'dim-green'\n token: 'blue-purple'\n as: 'potato'\n toUuid: '", "end": 1331, "score": 0.7045450210571289, "start": 1320, "tag": "PASSWORD", "value": "blue-purple" }, { "context": " uuid: 'dim-green'\n token: 'blue-purple'\n toUuid: 'bright-green'\n ", "end": 2110, "score": 0.544183075428009, "start": 2106, "tag": "PASSWORD", "value": "blue" }, { "context": " uuid: 'dim-green'\n token: 'blue-purple'\n toUuid: 'bright-green'\n f", "end": 2117, "score": 0.7027136087417603, "start": 2111, "tag": "KEY", "value": "purple" }, { "context": " uuid: 'dim-green'\n token: 'blue-purple'\n toUuid: 'bright-green'\n ", "end": 2866, "score": 0.5821751356124878, "start": 2862, "tag": "PASSWORD", "value": "blue" }, { "context": " uuid: 'dim-green'\n token: 'blue-purple'\n toUuid: 'bright-green'\n f", "end": 2873, "score": 0.6341642141342163, "start": 2867, "tag": "KEY", "value": "purple" }, { "context": " uuid: 'green-blue'\n token: 'blue-purple'\n toUuid: 'bright-green'\n ", "end": 3638, "score": 0.5209183692932129, "start": 3634, "tag": "PASSWORD", "value": "blue" }, { "context": " uuid: 'green-blue'\n token: 'blue-purple'\n toUuid: 'bright-green'\n r", "end": 3645, "score": 0.6690832376480103, "start": 3639, "tag": "KEY", "value": "purple" }, { "context": " uuid: 'green-blue'\n token: 'blue-purple'\n fromUuid: 'green-blue'\n r", "end": 4381, "score": 0.6006598472595215, "start": 4370, "tag": "KEY", "value": "blue-purple" }, { "context": " uuid: 'green-blue'\n token: 'blue-purple'\n as: 'monkey-man'\n toUui", "end": 5115, "score": 0.653824508190155, "start": 5104, "tag": "KEY", "value": "blue-purple" }, { "context": " token: 'blue-purple'\n as: 'monkey-man'\n toUuid: 'bright-green'\n f", "end": 5146, "score": 0.9686694145202637, "start": 5136, "tag": "USERNAME", "value": "monkey-man" }, { "context": " uuid: 'dim-green'\n token: 'blue-lime-green'\n toUuid: 'hot-yellow'\n fro", "end": 5797, "score": 0.7287129163742065, "start": 5782, "tag": "KEY", "value": "blue-lime-green" }, { "context": " uuid: 'puke-green'\n token: 'blue-lime-green'\n toUuid: 'super-purple'\n f", "end": 6602, "score": 0.9603716135025024, "start": 6587, "tag": "PASSWORD", "value": "blue-lime-green" }, { "context": " uuid: 'puke-green'\n token: 'blue-lime-green'\n toUuid: 'green-bomb'\n fro", "end": 7412, "score": 0.9563271403312683, "start": 7397, "tag": "PASSWORD", "value": "blue-lime-green" } ]
test/check-whitelist-message-from-spec.coffee
octoblu/meshblu-core-task-check-whitelist-message-from
0
http = require 'http' CheckWhitelistMessageFrom = require '../' describe 'CheckWhitelistMessageFrom', -> beforeEach -> @whitelistManager = checkMessageFrom: sinon.stub() @sut = new CheckWhitelistMessageFrom whitelistManager: @whitelistManager describe '->do', -> describe 'when the auth.uuid does not match the fromUuid', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'blue-purple' toUuid: 'bright-green' fromUuid: 'frog' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of 403', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when the auth.as does not match the fromUuid', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'blue-purple' as: 'potato' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of 403', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when called with a valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'blue-purple' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'blue-purple' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a valid job without a from', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: 'blue-purple' toUuid: 'bright-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 422', -> expect(@newJob.metadata.code).to.equal 422 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[422] describe 'when called with a valid job without a to', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: 'blue-purple' fromUuid: 'green-blue' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 422', -> expect(@newJob.metadata.code).to.equal 422 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[422] describe 'when called with a valid job with an as', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: 'blue-purple' as: 'monkey-man' toUuid: 'bright-green' fromUuid: 'monkey-man' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should call the whitelistmanager with the correct arguments', -> expect(@whitelistManager.checkMessageFrom).to.have.been.calledWith emitter: 'monkey-man' subscriber: 'bright-green' describe 'when called with a different valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'blue-lime-green' toUuid: 'hot-yellow' fromUuid: 'dim-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of OK', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a job that with a device that has an invalid whitelist', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, false job = metadata: auth: uuid: 'puke-green' token: 'blue-lime-green' toUuid: 'super-purple' fromUuid: 'puke-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of Forbidden', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when called and the checkMessageFrom yields an error', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields new Error "black-n-black" job = metadata: auth: uuid: 'puke-green' token: 'blue-lime-green' toUuid: 'green-bomb' fromUuid: 'puke-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 500', -> expect(@newJob.metadata.code).to.equal 500 it 'should get have the status of Forbidden', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[500]
41950
http = require 'http' CheckWhitelistMessageFrom = require '../' describe 'CheckWhitelistMessageFrom', -> beforeEach -> @whitelistManager = checkMessageFrom: sinon.stub() @sut = new CheckWhitelistMessageFrom whitelistManager: @whitelistManager describe '->do', -> describe 'when the auth.uuid does not match the fromUuid', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: '<PASSWORD>' toUuid: 'bright-green' fromUuid: 'frog' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of 403', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when the auth.as does not match the fromUuid', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: '<PASSWORD>' as: 'potato' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of 403', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when called with a valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: '<PASSWORD>-<KEY>' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: '<PASSWORD>-<KEY>' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a valid job without a from', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: '<PASSWORD>-<KEY>' toUuid: 'bright-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 422', -> expect(@newJob.metadata.code).to.equal 422 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[422] describe 'when called with a valid job without a to', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: '<PASSWORD>' fromUuid: 'green-blue' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 422', -> expect(@newJob.metadata.code).to.equal 422 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[422] describe 'when called with a valid job with an as', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: '<PASSWORD>' as: 'monkey-man' toUuid: 'bright-green' fromUuid: 'monkey-man' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should call the whitelistmanager with the correct arguments', -> expect(@whitelistManager.checkMessageFrom).to.have.been.calledWith emitter: 'monkey-man' subscriber: 'bright-green' describe 'when called with a different valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: '<KEY>' toUuid: 'hot-yellow' fromUuid: 'dim-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of OK', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a job that with a device that has an invalid whitelist', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, false job = metadata: auth: uuid: 'puke-green' token: '<KEY>' toUuid: 'super-purple' fromUuid: 'puke-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of Forbidden', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when called and the checkMessageFrom yields an error', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields new Error "black-n-black" job = metadata: auth: uuid: 'puke-green' token: '<KEY>' toUuid: 'green-bomb' fromUuid: 'puke-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 500', -> expect(@newJob.metadata.code).to.equal 500 it 'should get have the status of Forbidden', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[500]
true
http = require 'http' CheckWhitelistMessageFrom = require '../' describe 'CheckWhitelistMessageFrom', -> beforeEach -> @whitelistManager = checkMessageFrom: sinon.stub() @sut = new CheckWhitelistMessageFrom whitelistManager: @whitelistManager describe '->do', -> describe 'when the auth.uuid does not match the fromUuid', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'PI:PASSWORD:<PASSWORD>END_PI' toUuid: 'bright-green' fromUuid: 'frog' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of 403', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when the auth.as does not match the fromUuid', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'PI:PASSWORD:<PASSWORD>END_PI' as: 'potato' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of 403', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when called with a valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI' toUuid: 'bright-green' fromUuid: 'dim-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a valid job without a from', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: 'PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI' toUuid: 'bright-green' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 422', -> expect(@newJob.metadata.code).to.equal 422 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[422] describe 'when called with a valid job without a to', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: 'PI:KEY:<PASSWORD>END_PI' fromUuid: 'green-blue' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'yellow-green' it 'should get have the status code of 422', -> expect(@newJob.metadata.code).to.equal 422 it 'should get have the status of ', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[422] describe 'when called with a valid job with an as', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'green-blue' token: 'PI:KEY:<PASSWORD>END_PI' as: 'monkey-man' toUuid: 'bright-green' fromUuid: 'monkey-man' responseId: 'yellow-green' @sut.do job, (error, @newJob) => done error it 'should call the whitelistmanager with the correct arguments', -> expect(@whitelistManager.checkMessageFrom).to.have.been.calledWith emitter: 'monkey-man' subscriber: 'bright-green' describe 'when called with a different valid job', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, true job = metadata: auth: uuid: 'dim-green' token: 'PI:KEY:<KEY>END_PI' toUuid: 'hot-yellow' fromUuid: 'dim-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 204', -> expect(@newJob.metadata.code).to.equal 204 it 'should get have the status of OK', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[204] describe 'when called with a job that with a device that has an invalid whitelist', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields null, false job = metadata: auth: uuid: 'puke-green' token: 'PI:PASSWORD:<KEY>END_PI' toUuid: 'super-purple' fromUuid: 'puke-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 403', -> expect(@newJob.metadata.code).to.equal 403 it 'should get have the status of Forbidden', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[403] describe 'when called and the checkMessageFrom yields an error', -> beforeEach (done) -> @whitelistManager.checkMessageFrom.yields new Error "black-n-black" job = metadata: auth: uuid: 'puke-green' token: 'PI:PASSWORD:<KEY>END_PI' toUuid: 'green-bomb' fromUuid: 'puke-green' responseId: 'purple-green' @sut.do job, (error, @newJob) => done error it 'should get have the responseId', -> expect(@newJob.metadata.responseId).to.equal 'purple-green' it 'should get have the status code of 500', -> expect(@newJob.metadata.code).to.equal 500 it 'should get have the status of Forbidden', -> expect(@newJob.metadata.status).to.equal http.STATUS_CODES[500]
[ { "context": " mediamanager\n#\n# Nodize CMS\n# https://github.com/nodize/nodizecms\n#\n# Copyright 2012, Hypee\n# http://hype", "end": 72, "score": 0.9992935657501221, "start": 66, "tag": "USERNAME", "value": "nodize" }, { "context": "://github.com/nodize/nodizecms\n#\n# Copyright 2012, Hypee\n# http://hypee.com\n#\n# Licensed under the MIT lic", "end": 108, "score": 0.978455126285553, "start": 103, "tag": "NAME", "value": "Hypee" }, { "context": "ia/get_tokken' : ->\n response = \n tokken:\"8b84445bf7a72faf1de2fe58a058efe6\"\n\n @send respon", "end": 847, "score": 0.5066683292388916, "start": 846, "tag": "KEY", "value": "8" }, { "context": "a/get_tokken' : ->\n response = \n tokken:\"8b84445bf7a72faf1de2fe58a058efe6\"\n\n @send response\n\n\n #\n # Returning files & ", "end": 878, "score": 0.6392201781272888, "start": 847, "tag": "PASSWORD", "value": "b84445bf7a72faf1de2fe58a058efe6" } ]
modules/backend/controllers/ctrl_mediamanager.coffee
nodize/nodizecms
32
# Controller for mediamanager # # Nodize CMS # https://github.com/nodize/nodizecms # # Copyright 2012, Hypee # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # # Components used : # http://blueimp.github.com/jQuery-File-Upload/ # TinyMCE # ... @include = -> basePath = __applicationPath+'/themes/'+__nodizeTheme+"/public/files" # # Displaying MEDIA MANAGER # @get '/:lang/admin/media/get_media_manager' : -> renderPage = (user_groups) => @render "backend_mediamanager", layout : no hardcode : @helpers lang : @params.lang ion_lang : ion_lang[ @params.lang ] #user_groups : user_groups renderPage() # # Generating token # @post '/:lang?/admin/media/get_tokken' : -> response = tokken:"8b84445bf7a72faf1de2fe58a058efe6" @send response # # Returning files & folders DETAIL # TODO: manage token # @post '/:lang?/admin/media/filemanager/detail' : (req, res) -> values = req.body # Params : # uploadTokken # directory # file # filter # mode (direct) # # console.log values fileDirectory = values.directory.replace( basePath, '' ) ck = require 'coffeecup' imageinfo = require 'imageinfo' fs = require 'fs' # # Generate template & send response # generateTemplate = (filedata, filestats) -> if filedata fileinfo = imageinfo( filedata ) fileinfo.length = filedata.length else fileinfo = null template = -> dl -> dt "${modified}" dd ".filemanager-modified", -> @filestats.mtime.toString() if @fileinfo dt "${type}" dd ".filemanager-type", -> @fileinfo.mimeType dt "${size}" dd ".filemanager-size", -> (@fileinfo.length/1024).toFixed(2)+" KB (#{@fileinfo.length} Bytes)" dt "${width}" dd @fileinfo.width+"px" dt "${height}" dd @fileinfo.height+"px" if @fileinfo div ".filemanager-preview-content", -> a href:"\/files"+@filename, "data-milkbox":"single", title:@filename, -> img src:"\/files"+@filename, class:"preview", alt:"preview", style:"width: 220px; height: 220px;" content = ck.render( template, filename:fileDirectory+"\/"+values.file, fileinfo:fileinfo, filestats:filestats ) response = status:1 content:content path:basePath+fileDirectory+"\/"+values.file name:values.file date:filestats.mtime.toString() mime:fileinfo?.mimeType size:fileinfo?.length width:fileinfo?.width height:fileinfo?.height thumb250:"\/files"+fileDirectory+"\/"+values.file thumb250_width:220 thumb250_height:220 thumb48:"\/files"+fileDirectory+"\/"+values.file thumb48_width:120 thumb48_height:120 thumbs_deferred:true icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/jpg.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/jpg.png" metadata:null res.send response # # Retrieving modification date # getFileStat = (filename) -> fs.stat filename, (err, stats ) -> if err console.log "getFileStat error on ",filename, err else getFileInfos( filename, stats ) getFileInfos = (filename, filestats) -> if filestats.isDirectory() generateTemplate( null, filestats ) else fs.readFile filename, (err, filedata) -> if (err) console.log "getFileInfos error",err else generateTemplate( filedata, filestats ) # # Start process # values.directory = basePath+"/"+values.directory if values.directory.indexOf( basePath )<0 imageFile = values.directory + "/" + values.file getFileStat( imageFile ) # # Returning files & folders list # @post '/:lang?/admin/media/filemanager/view' : (req,res) -> values = req.body # # Get file list (folder "files" in /themes) # fs = require 'fs' path = require 'path' files = "" basePath = __applicationPath+'/themes/'+__nodizeTheme+"/public/files" filesFolder = basePath+values.directory getFolders = (dir, done) -> results = [] fs.readdir dir, (err, list) -> if (err) done(err) else done(null, list) path = require 'path' # # Get all files in a folder (recursive) # walk = (dir, done) -> files = [] folders = [] fs.readdir dir, (err, list) -> return done(err) if (err) pending = list.length return done(null, folders, files) if not pending list.forEach (file) -> file = dir + '/' + file fs.stat file, (err, stat) -> if (stat and stat.isDirectory()) folders.push(file) pending-- done(null, folders, files) if not pending else files.push(file) pending-- done(null, folders, files) if not pending # # We fill JSON structures to store folders & files # walk filesFolder, (err, folders, files) -> folders_json = [] # # Building file list JSON structure # files_json = [] try files = files.sort() for filename in files item = path : filename name : path.basename( filename ) mime :"image\/jpeg" thumbs_deferred :true icon48 :"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/jpg.png" icon :"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/jpg.png" files_json.push( item ) catch error console.log "files_json error : ",error # # Building folder list JSON structure # try for folder in folders item = path : folder.replace( basePath, '' ) name : path.basename( folder ) mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" folders_json.push( item ) catch error console.log error # # Adding access to parent folder # if values.directory not in ['/',''] item = path : path.join( values.directory, '..' ) name : ".." mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory_up.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory_up.png" folders_json.push( item ) # # Remove trailing slash # values.directory = values.directory.substr( 0, values.directory.length - 1 ) if values.directory.substr(-1) is "/" #values.directory = basePath+"/"+values.directory if values.directory.indexOf( basePath )<0 #console.log "this_dir path", basePath+values.directory #console.log "this_dir name", (if values.directory is "" then "/" else path.basename( values.directory )) #console.log "this_dir path", values.directory #console.log "this_dir name", path.basename( values.directory ) response = status:1 root:"files\/" this_dir: #path: basePath+values.directory path: values.directory name: path.basename( values.directory ) date:"20 Mar 2012 - 21:36" mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" preselect_index:0 preselect_name:null dirs:folders_json files:files_json res.send response # # Creating folder # @post '/:lang?/admin/media/filemanager/create' : (req, res) -> values = req.body # console.log values fs = require 'fs' fs.mkdir values.directory+'\/'+values.file, 0o0777, (err) -> if err console.log err response = status:0 else response = status:1 root:"files\/" this_dir: path:values.directory+"\/"+values.file name:values.file date:"20 Mar 2012 - 21:36" mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" preselect_index:0 preselect_name:null dirs:[ path: values.directory.replace( basePath, "" ) name:".." mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory_up.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory_up.png" ] files:[] res.send response
57222
# Controller for mediamanager # # Nodize CMS # https://github.com/nodize/nodizecms # # Copyright 2012, <NAME> # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # # Components used : # http://blueimp.github.com/jQuery-File-Upload/ # TinyMCE # ... @include = -> basePath = __applicationPath+'/themes/'+__nodizeTheme+"/public/files" # # Displaying MEDIA MANAGER # @get '/:lang/admin/media/get_media_manager' : -> renderPage = (user_groups) => @render "backend_mediamanager", layout : no hardcode : @helpers lang : @params.lang ion_lang : ion_lang[ @params.lang ] #user_groups : user_groups renderPage() # # Generating token # @post '/:lang?/admin/media/get_tokken' : -> response = tokken:"<KEY> <PASSWORD>" @send response # # Returning files & folders DETAIL # TODO: manage token # @post '/:lang?/admin/media/filemanager/detail' : (req, res) -> values = req.body # Params : # uploadTokken # directory # file # filter # mode (direct) # # console.log values fileDirectory = values.directory.replace( basePath, '' ) ck = require 'coffeecup' imageinfo = require 'imageinfo' fs = require 'fs' # # Generate template & send response # generateTemplate = (filedata, filestats) -> if filedata fileinfo = imageinfo( filedata ) fileinfo.length = filedata.length else fileinfo = null template = -> dl -> dt "${modified}" dd ".filemanager-modified", -> @filestats.mtime.toString() if @fileinfo dt "${type}" dd ".filemanager-type", -> @fileinfo.mimeType dt "${size}" dd ".filemanager-size", -> (@fileinfo.length/1024).toFixed(2)+" KB (#{@fileinfo.length} Bytes)" dt "${width}" dd @fileinfo.width+"px" dt "${height}" dd @fileinfo.height+"px" if @fileinfo div ".filemanager-preview-content", -> a href:"\/files"+@filename, "data-milkbox":"single", title:@filename, -> img src:"\/files"+@filename, class:"preview", alt:"preview", style:"width: 220px; height: 220px;" content = ck.render( template, filename:fileDirectory+"\/"+values.file, fileinfo:fileinfo, filestats:filestats ) response = status:1 content:content path:basePath+fileDirectory+"\/"+values.file name:values.file date:filestats.mtime.toString() mime:fileinfo?.mimeType size:fileinfo?.length width:fileinfo?.width height:fileinfo?.height thumb250:"\/files"+fileDirectory+"\/"+values.file thumb250_width:220 thumb250_height:220 thumb48:"\/files"+fileDirectory+"\/"+values.file thumb48_width:120 thumb48_height:120 thumbs_deferred:true icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/jpg.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/jpg.png" metadata:null res.send response # # Retrieving modification date # getFileStat = (filename) -> fs.stat filename, (err, stats ) -> if err console.log "getFileStat error on ",filename, err else getFileInfos( filename, stats ) getFileInfos = (filename, filestats) -> if filestats.isDirectory() generateTemplate( null, filestats ) else fs.readFile filename, (err, filedata) -> if (err) console.log "getFileInfos error",err else generateTemplate( filedata, filestats ) # # Start process # values.directory = basePath+"/"+values.directory if values.directory.indexOf( basePath )<0 imageFile = values.directory + "/" + values.file getFileStat( imageFile ) # # Returning files & folders list # @post '/:lang?/admin/media/filemanager/view' : (req,res) -> values = req.body # # Get file list (folder "files" in /themes) # fs = require 'fs' path = require 'path' files = "" basePath = __applicationPath+'/themes/'+__nodizeTheme+"/public/files" filesFolder = basePath+values.directory getFolders = (dir, done) -> results = [] fs.readdir dir, (err, list) -> if (err) done(err) else done(null, list) path = require 'path' # # Get all files in a folder (recursive) # walk = (dir, done) -> files = [] folders = [] fs.readdir dir, (err, list) -> return done(err) if (err) pending = list.length return done(null, folders, files) if not pending list.forEach (file) -> file = dir + '/' + file fs.stat file, (err, stat) -> if (stat and stat.isDirectory()) folders.push(file) pending-- done(null, folders, files) if not pending else files.push(file) pending-- done(null, folders, files) if not pending # # We fill JSON structures to store folders & files # walk filesFolder, (err, folders, files) -> folders_json = [] # # Building file list JSON structure # files_json = [] try files = files.sort() for filename in files item = path : filename name : path.basename( filename ) mime :"image\/jpeg" thumbs_deferred :true icon48 :"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/jpg.png" icon :"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/jpg.png" files_json.push( item ) catch error console.log "files_json error : ",error # # Building folder list JSON structure # try for folder in folders item = path : folder.replace( basePath, '' ) name : path.basename( folder ) mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" folders_json.push( item ) catch error console.log error # # Adding access to parent folder # if values.directory not in ['/',''] item = path : path.join( values.directory, '..' ) name : ".." mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory_up.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory_up.png" folders_json.push( item ) # # Remove trailing slash # values.directory = values.directory.substr( 0, values.directory.length - 1 ) if values.directory.substr(-1) is "/" #values.directory = basePath+"/"+values.directory if values.directory.indexOf( basePath )<0 #console.log "this_dir path", basePath+values.directory #console.log "this_dir name", (if values.directory is "" then "/" else path.basename( values.directory )) #console.log "this_dir path", values.directory #console.log "this_dir name", path.basename( values.directory ) response = status:1 root:"files\/" this_dir: #path: basePath+values.directory path: values.directory name: path.basename( values.directory ) date:"20 Mar 2012 - 21:36" mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" preselect_index:0 preselect_name:null dirs:folders_json files:files_json res.send response # # Creating folder # @post '/:lang?/admin/media/filemanager/create' : (req, res) -> values = req.body # console.log values fs = require 'fs' fs.mkdir values.directory+'\/'+values.file, 0o0777, (err) -> if err console.log err response = status:0 else response = status:1 root:"files\/" this_dir: path:values.directory+"\/"+values.file name:values.file date:"20 Mar 2012 - 21:36" mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" preselect_index:0 preselect_name:null dirs:[ path: values.directory.replace( basePath, "" ) name:".." mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory_up.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory_up.png" ] files:[] res.send response
true
# Controller for mediamanager # # Nodize CMS # https://github.com/nodize/nodizecms # # Copyright 2012, PI:NAME:<NAME>END_PI # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # # Components used : # http://blueimp.github.com/jQuery-File-Upload/ # TinyMCE # ... @include = -> basePath = __applicationPath+'/themes/'+__nodizeTheme+"/public/files" # # Displaying MEDIA MANAGER # @get '/:lang/admin/media/get_media_manager' : -> renderPage = (user_groups) => @render "backend_mediamanager", layout : no hardcode : @helpers lang : @params.lang ion_lang : ion_lang[ @params.lang ] #user_groups : user_groups renderPage() # # Generating token # @post '/:lang?/admin/media/get_tokken' : -> response = tokken:"PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" @send response # # Returning files & folders DETAIL # TODO: manage token # @post '/:lang?/admin/media/filemanager/detail' : (req, res) -> values = req.body # Params : # uploadTokken # directory # file # filter # mode (direct) # # console.log values fileDirectory = values.directory.replace( basePath, '' ) ck = require 'coffeecup' imageinfo = require 'imageinfo' fs = require 'fs' # # Generate template & send response # generateTemplate = (filedata, filestats) -> if filedata fileinfo = imageinfo( filedata ) fileinfo.length = filedata.length else fileinfo = null template = -> dl -> dt "${modified}" dd ".filemanager-modified", -> @filestats.mtime.toString() if @fileinfo dt "${type}" dd ".filemanager-type", -> @fileinfo.mimeType dt "${size}" dd ".filemanager-size", -> (@fileinfo.length/1024).toFixed(2)+" KB (#{@fileinfo.length} Bytes)" dt "${width}" dd @fileinfo.width+"px" dt "${height}" dd @fileinfo.height+"px" if @fileinfo div ".filemanager-preview-content", -> a href:"\/files"+@filename, "data-milkbox":"single", title:@filename, -> img src:"\/files"+@filename, class:"preview", alt:"preview", style:"width: 220px; height: 220px;" content = ck.render( template, filename:fileDirectory+"\/"+values.file, fileinfo:fileinfo, filestats:filestats ) response = status:1 content:content path:basePath+fileDirectory+"\/"+values.file name:values.file date:filestats.mtime.toString() mime:fileinfo?.mimeType size:fileinfo?.length width:fileinfo?.width height:fileinfo?.height thumb250:"\/files"+fileDirectory+"\/"+values.file thumb250_width:220 thumb250_height:220 thumb48:"\/files"+fileDirectory+"\/"+values.file thumb48_width:120 thumb48_height:120 thumbs_deferred:true icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/jpg.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/jpg.png" metadata:null res.send response # # Retrieving modification date # getFileStat = (filename) -> fs.stat filename, (err, stats ) -> if err console.log "getFileStat error on ",filename, err else getFileInfos( filename, stats ) getFileInfos = (filename, filestats) -> if filestats.isDirectory() generateTemplate( null, filestats ) else fs.readFile filename, (err, filedata) -> if (err) console.log "getFileInfos error",err else generateTemplate( filedata, filestats ) # # Start process # values.directory = basePath+"/"+values.directory if values.directory.indexOf( basePath )<0 imageFile = values.directory + "/" + values.file getFileStat( imageFile ) # # Returning files & folders list # @post '/:lang?/admin/media/filemanager/view' : (req,res) -> values = req.body # # Get file list (folder "files" in /themes) # fs = require 'fs' path = require 'path' files = "" basePath = __applicationPath+'/themes/'+__nodizeTheme+"/public/files" filesFolder = basePath+values.directory getFolders = (dir, done) -> results = [] fs.readdir dir, (err, list) -> if (err) done(err) else done(null, list) path = require 'path' # # Get all files in a folder (recursive) # walk = (dir, done) -> files = [] folders = [] fs.readdir dir, (err, list) -> return done(err) if (err) pending = list.length return done(null, folders, files) if not pending list.forEach (file) -> file = dir + '/' + file fs.stat file, (err, stat) -> if (stat and stat.isDirectory()) folders.push(file) pending-- done(null, folders, files) if not pending else files.push(file) pending-- done(null, folders, files) if not pending # # We fill JSON structures to store folders & files # walk filesFolder, (err, folders, files) -> folders_json = [] # # Building file list JSON structure # files_json = [] try files = files.sort() for filename in files item = path : filename name : path.basename( filename ) mime :"image\/jpeg" thumbs_deferred :true icon48 :"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/jpg.png" icon :"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/jpg.png" files_json.push( item ) catch error console.log "files_json error : ",error # # Building folder list JSON structure # try for folder in folders item = path : folder.replace( basePath, '' ) name : path.basename( folder ) mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" folders_json.push( item ) catch error console.log error # # Adding access to parent folder # if values.directory not in ['/',''] item = path : path.join( values.directory, '..' ) name : ".." mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory_up.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory_up.png" folders_json.push( item ) # # Remove trailing slash # values.directory = values.directory.substr( 0, values.directory.length - 1 ) if values.directory.substr(-1) is "/" #values.directory = basePath+"/"+values.directory if values.directory.indexOf( basePath )<0 #console.log "this_dir path", basePath+values.directory #console.log "this_dir name", (if values.directory is "" then "/" else path.basename( values.directory )) #console.log "this_dir path", values.directory #console.log "this_dir name", path.basename( values.directory ) response = status:1 root:"files\/" this_dir: #path: basePath+values.directory path: values.directory name: path.basename( values.directory ) date:"20 Mar 2012 - 21:36" mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" preselect_index:0 preselect_name:null dirs:folders_json files:files_json res.send response # # Creating folder # @post '/:lang?/admin/media/filemanager/create' : (req, res) -> values = req.body # console.log values fs = require 'fs' fs.mkdir values.directory+'\/'+values.file, 0o0777, (err) -> if err console.log err response = status:0 else response = status:1 root:"files\/" this_dir: path:values.directory+"\/"+values.file name:values.file date:"20 Mar 2012 - 21:36" mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory.png" preselect_index:0 preselect_name:null dirs:[ path: values.directory.replace( basePath, "" ) name:".." mime:"text\/directory" icon48:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/Large\/directory_up.png" icon:"\/backend\/javascript\/mootools-filemanager\/Assets\/Images\/Icons\/directory_up.png" ] files:[] res.send response
[ { "context": "t be blank'\n return\n if newPassword != cnfPassword\n @error 'Passwords do not match'", "end": 1114, "score": 0.5602576732635498, "start": 1113, "tag": "PASSWORD", "value": "c" }, { "context": " blank'\n return\n if newPassword != cnfPassword\n @error 'Passwords do not match'\n r", "end": 1124, "score": 0.5838024020195007, "start": 1116, "tag": "PASSWORD", "value": "Password" }, { "context": " current: currentPassword\n password: newPassword\n success: (res) =>\n if res.succes", "end": 1358, "score": 0.9870785474777222, "start": 1347, "tag": "PASSWORD", "value": "newPassword" } ]
public/scripts/backbone-schedule/views/settings/general/password.coffee
courseshark/courseshark
1
define(['jQuery' 'Underscore' 'Backbone' 'views/shark-view' 'models/user' 'text!tmpl/settings/general/password.ejs'], ($, _, Backbone, SharkView, User, templateText) -> class EmailSettingsView extends SharkView initialize: -> _.bindAll @ @template = _.template(templateText) @render() render: -> @$el.html $ @template user: Shark.session.get('user') @ events: 'click .cancel': 'emitClose' 'click .submit': 'submit' error: (message) -> @$el.find('.error').hide().html(message).fadeIn() emitClose: -> @trigger('close') submit: -> currentPassword = @$el.find('#inputCurrentPassword').val() newPassword = @$el.find('#inputNewPassword').val() cnfPassword = @$el.find('#inputConfirmPassword').val() user = Shark.session.get('user') if user.get('password') and not currentPassword @error 'Please enter your current password' return if newPassword == '' @error 'New password cannot be blank' return if newPassword != cnfPassword @error 'Passwords do not match' return $.ajax url: '/api/user/'+user.id type: 'post' data: changePassword: current: currentPassword password: newPassword success: (res) => if res.success Shark.session.get('user').trigger('setPassword') @emitClose() else @error res.error teardown: -> super() EmailSettingsView )
3355
define(['jQuery' 'Underscore' 'Backbone' 'views/shark-view' 'models/user' 'text!tmpl/settings/general/password.ejs'], ($, _, Backbone, SharkView, User, templateText) -> class EmailSettingsView extends SharkView initialize: -> _.bindAll @ @template = _.template(templateText) @render() render: -> @$el.html $ @template user: Shark.session.get('user') @ events: 'click .cancel': 'emitClose' 'click .submit': 'submit' error: (message) -> @$el.find('.error').hide().html(message).fadeIn() emitClose: -> @trigger('close') submit: -> currentPassword = @$el.find('#inputCurrentPassword').val() newPassword = @$el.find('#inputNewPassword').val() cnfPassword = @$el.find('#inputConfirmPassword').val() user = Shark.session.get('user') if user.get('password') and not currentPassword @error 'Please enter your current password' return if newPassword == '' @error 'New password cannot be blank' return if newPassword != <PASSWORD>nf<PASSWORD> @error 'Passwords do not match' return $.ajax url: '/api/user/'+user.id type: 'post' data: changePassword: current: currentPassword password: <PASSWORD> success: (res) => if res.success Shark.session.get('user').trigger('setPassword') @emitClose() else @error res.error teardown: -> super() EmailSettingsView )
true
define(['jQuery' 'Underscore' 'Backbone' 'views/shark-view' 'models/user' 'text!tmpl/settings/general/password.ejs'], ($, _, Backbone, SharkView, User, templateText) -> class EmailSettingsView extends SharkView initialize: -> _.bindAll @ @template = _.template(templateText) @render() render: -> @$el.html $ @template user: Shark.session.get('user') @ events: 'click .cancel': 'emitClose' 'click .submit': 'submit' error: (message) -> @$el.find('.error').hide().html(message).fadeIn() emitClose: -> @trigger('close') submit: -> currentPassword = @$el.find('#inputCurrentPassword').val() newPassword = @$el.find('#inputNewPassword').val() cnfPassword = @$el.find('#inputConfirmPassword').val() user = Shark.session.get('user') if user.get('password') and not currentPassword @error 'Please enter your current password' return if newPassword == '' @error 'New password cannot be blank' return if newPassword != PI:PASSWORD:<PASSWORD>END_PInfPI:PASSWORD:<PASSWORD>END_PI @error 'Passwords do not match' return $.ajax url: '/api/user/'+user.id type: 'post' data: changePassword: current: currentPassword password: PI:PASSWORD:<PASSWORD>END_PI success: (res) => if res.success Shark.session.get('user').trigger('setPassword') @emitClose() else @error res.error teardown: -> super() EmailSettingsView )
[ { "context": "e: process.env.CONOHA_USERNAME\n password: process.env.CONOHA_PASSWORD\n tenantId: process.env.CONOHA_TENANT_ID\n ", "end": 292, "score": 0.9975185394287109, "start": 265, "tag": "PASSWORD", "value": "process.env.CONOHA_PASSWORD" } ]
tests/conoha_test.spec.coffee
nukosuke/node-conoha-api
0
ConoHa = require '../src/conoha' describe 'ConoHa class', -> conoha = null before (done) -> conoha = new ConoHa process.env.CONOHA_IDENTITY_URL, auth: passwordCredentials: username: process.env.CONOHA_USERNAME password: process.env.CONOHA_PASSWORD tenantId: process.env.CONOHA_TENANT_ID done() describe 'credentials is set correctly', -> it 'username', -> expect(conoha.auth.auth.passwordCredentials.username) .to.not.be.undefined it 'password', -> expect(conoha.auth.auth.passwordCredentials.password) .to.not.be.undefined it 'tenant id', -> expect(conoha.auth.auth.tenantId) .to.not.be.undefined it 'identity service endpoint', -> expect(process.env.CONOHA_IDENTITY_URL) .to.not.be.undefined describe 'getService() method returns non undefined', -> [ 'account', 'compute', 'blockstorage', 'databasehosting', 'image', 'dns', 'objectstorage', 'mailhosting', 'identity', 'network' ] .forEach (service) -> it "#{service} service", -> expect(conoha.getService(service)).to.not.be.undefined
195904
ConoHa = require '../src/conoha' describe 'ConoHa class', -> conoha = null before (done) -> conoha = new ConoHa process.env.CONOHA_IDENTITY_URL, auth: passwordCredentials: username: process.env.CONOHA_USERNAME password: <PASSWORD> tenantId: process.env.CONOHA_TENANT_ID done() describe 'credentials is set correctly', -> it 'username', -> expect(conoha.auth.auth.passwordCredentials.username) .to.not.be.undefined it 'password', -> expect(conoha.auth.auth.passwordCredentials.password) .to.not.be.undefined it 'tenant id', -> expect(conoha.auth.auth.tenantId) .to.not.be.undefined it 'identity service endpoint', -> expect(process.env.CONOHA_IDENTITY_URL) .to.not.be.undefined describe 'getService() method returns non undefined', -> [ 'account', 'compute', 'blockstorage', 'databasehosting', 'image', 'dns', 'objectstorage', 'mailhosting', 'identity', 'network' ] .forEach (service) -> it "#{service} service", -> expect(conoha.getService(service)).to.not.be.undefined
true
ConoHa = require '../src/conoha' describe 'ConoHa class', -> conoha = null before (done) -> conoha = new ConoHa process.env.CONOHA_IDENTITY_URL, auth: passwordCredentials: username: process.env.CONOHA_USERNAME password: PI:PASSWORD:<PASSWORD>END_PI tenantId: process.env.CONOHA_TENANT_ID done() describe 'credentials is set correctly', -> it 'username', -> expect(conoha.auth.auth.passwordCredentials.username) .to.not.be.undefined it 'password', -> expect(conoha.auth.auth.passwordCredentials.password) .to.not.be.undefined it 'tenant id', -> expect(conoha.auth.auth.tenantId) .to.not.be.undefined it 'identity service endpoint', -> expect(process.env.CONOHA_IDENTITY_URL) .to.not.be.undefined describe 'getService() method returns non undefined', -> [ 'account', 'compute', 'blockstorage', 'databasehosting', 'image', 'dns', 'objectstorage', 'mailhosting', 'identity', 'network' ] .forEach (service) -> it "#{service} service", -> expect(conoha.getService(service)).to.not.be.undefined
[ { "context": "in pres\n parts = pre.split \"</pre>\"\n key = \"code#{ i }\"\n lang = null\n code = parts[ 0 ]\n ", "end": 977, "score": 0.9073674082756042, "start": 973, "tag": "KEY", "value": "code" } ]
lib/react-transform.coffee
PaulLeCam/voila
1
transform = require("react-tools").transform jsdom = require "jsdom" # Lib from https://github.com/facebook/react/blob/master/docs/_js/html-jsx-lib.js html2jsxlib = require("fs").readFileSync __dirname + "/html-jsx-lib.js" html2jsx = (html, cb) -> jsdom.env html: "<html><body></body></html>" src: [html2jsxlib] done: (err, window) -> return cb err if err converter = new window.HTMLtoJSX createClass: no jsx = converter.convert html window.close() cb null, jsx jsx2component = (jsx) -> transform "/** @jsx React.DOM */#{ jsx }" .replace "/** @jsx React.DOM */", "" html2component = (html, mappings = {}, cb) -> # Terrible hack to make <pre> code render properly # It is processed by highlight.js in the gulpfile, but jsdom will break spacing # There must be a better way to do this... pres = html.split "<pre>" prepared = pres.shift() codes = {} for pre, i in pres parts = pre.split "</pre>" key = "code#{ i }" lang = null code = parts[ 0 ] # Extract code class and remove tag .replace /<code class="([-_\w\s]*)">/, (match, lng) -> lang = lng "" # Remove closing code tag .replace "</code>", "" # Replace \n by <br/> - must be done before \s .replace /\n/g, "<br/>" # Replace \t by 2 &nbsp; - must be done before \s .replace /\t/g, "&nbsp;&nbsp;" # Replace \s by &nbsp; .replace /\s/g, "&nbsp;" # Remove added &nbsp; in spans .replace /<span&nbsp;class/g, "<span class" codes[ key ] = {lang, code} prepared += "<pre><code data-replace='#{ key }'></code></pre>#{ parts[ 1 ] }" html2jsx prepared, (err, jsx) -> if err then cb err else jsx = jsx.replace /<code data-replace="(code\d)+" \/>/gi, (match, id) -> if res = codes[ id ] "<code className='#{ res.lang }' highlight='#{ res.code }'></code>" jsx = jsx.replace new RegExp(from, "g"), to for from, to of mappings cb null, jsx2component jsx module.exports = {html2jsx, jsx2component, html2component}
118692
transform = require("react-tools").transform jsdom = require "jsdom" # Lib from https://github.com/facebook/react/blob/master/docs/_js/html-jsx-lib.js html2jsxlib = require("fs").readFileSync __dirname + "/html-jsx-lib.js" html2jsx = (html, cb) -> jsdom.env html: "<html><body></body></html>" src: [html2jsxlib] done: (err, window) -> return cb err if err converter = new window.HTMLtoJSX createClass: no jsx = converter.convert html window.close() cb null, jsx jsx2component = (jsx) -> transform "/** @jsx React.DOM */#{ jsx }" .replace "/** @jsx React.DOM */", "" html2component = (html, mappings = {}, cb) -> # Terrible hack to make <pre> code render properly # It is processed by highlight.js in the gulpfile, but jsdom will break spacing # There must be a better way to do this... pres = html.split "<pre>" prepared = pres.shift() codes = {} for pre, i in pres parts = pre.split "</pre>" key = "<KEY>#{ i }" lang = null code = parts[ 0 ] # Extract code class and remove tag .replace /<code class="([-_\w\s]*)">/, (match, lng) -> lang = lng "" # Remove closing code tag .replace "</code>", "" # Replace \n by <br/> - must be done before \s .replace /\n/g, "<br/>" # Replace \t by 2 &nbsp; - must be done before \s .replace /\t/g, "&nbsp;&nbsp;" # Replace \s by &nbsp; .replace /\s/g, "&nbsp;" # Remove added &nbsp; in spans .replace /<span&nbsp;class/g, "<span class" codes[ key ] = {lang, code} prepared += "<pre><code data-replace='#{ key }'></code></pre>#{ parts[ 1 ] }" html2jsx prepared, (err, jsx) -> if err then cb err else jsx = jsx.replace /<code data-replace="(code\d)+" \/>/gi, (match, id) -> if res = codes[ id ] "<code className='#{ res.lang }' highlight='#{ res.code }'></code>" jsx = jsx.replace new RegExp(from, "g"), to for from, to of mappings cb null, jsx2component jsx module.exports = {html2jsx, jsx2component, html2component}
true
transform = require("react-tools").transform jsdom = require "jsdom" # Lib from https://github.com/facebook/react/blob/master/docs/_js/html-jsx-lib.js html2jsxlib = require("fs").readFileSync __dirname + "/html-jsx-lib.js" html2jsx = (html, cb) -> jsdom.env html: "<html><body></body></html>" src: [html2jsxlib] done: (err, window) -> return cb err if err converter = new window.HTMLtoJSX createClass: no jsx = converter.convert html window.close() cb null, jsx jsx2component = (jsx) -> transform "/** @jsx React.DOM */#{ jsx }" .replace "/** @jsx React.DOM */", "" html2component = (html, mappings = {}, cb) -> # Terrible hack to make <pre> code render properly # It is processed by highlight.js in the gulpfile, but jsdom will break spacing # There must be a better way to do this... pres = html.split "<pre>" prepared = pres.shift() codes = {} for pre, i in pres parts = pre.split "</pre>" key = "PI:KEY:<KEY>END_PI#{ i }" lang = null code = parts[ 0 ] # Extract code class and remove tag .replace /<code class="([-_\w\s]*)">/, (match, lng) -> lang = lng "" # Remove closing code tag .replace "</code>", "" # Replace \n by <br/> - must be done before \s .replace /\n/g, "<br/>" # Replace \t by 2 &nbsp; - must be done before \s .replace /\t/g, "&nbsp;&nbsp;" # Replace \s by &nbsp; .replace /\s/g, "&nbsp;" # Remove added &nbsp; in spans .replace /<span&nbsp;class/g, "<span class" codes[ key ] = {lang, code} prepared += "<pre><code data-replace='#{ key }'></code></pre>#{ parts[ 1 ] }" html2jsx prepared, (err, jsx) -> if err then cb err else jsx = jsx.replace /<code data-replace="(code\d)+" \/>/gi, (match, id) -> if res = codes[ id ] "<code className='#{ res.lang }' highlight='#{ res.code }'></code>" jsx = jsx.replace new RegExp(from, "g"), to for from, to of mappings cb null, jsx2component jsx module.exports = {html2jsx, jsx2component, html2component}
[ { "context": " ->\n Backbone.history.start()\n\nParse.initialize(\"uwdostKJHj59UqMPm8pS6XO6OspSXBOy7s1IHkJo\", \"o0IPafacxdIuNIbsirAkULxMn2p28fBMbu7l0abY\")", "end": 377, "score": 0.9995355010032654, "start": 337, "tag": "KEY", "value": "uwdostKJHj59UqMPm8pS6XO6OspSXBOy7s1IHkJo" }, { "context": "lize(\"uwdostKJHj59UqMPm8pS6XO6OspSXBOy7s1IHkJo\", \"o0IPafacxdIuNIbsirAkULxMn2p28fBMbu7l0abY\")", "end": 421, "score": 0.9994028806686401, "start": 381, "tag": "KEY", "value": "o0IPafacxdIuNIbsirAkULxMn2p28fBMbu7l0abY" } ]
source/javascripts/app/index.coffee
iic-ninjas/shakespear
0
#= require_self #= require_tree ./models #= require_tree ./views #= require_tree ./controllers window.Shake = new Marionette.Application() window.Shake.addRegions( top: '.top' main: '.main' ) Shake.Models = {} Shake.Views = {} Shake.Controllers = {} Shake.addInitializer (options) -> Backbone.history.start() Parse.initialize("uwdostKJHj59UqMPm8pS6XO6OspSXBOy7s1IHkJo", "o0IPafacxdIuNIbsirAkULxMn2p28fBMbu7l0abY")
53595
#= require_self #= require_tree ./models #= require_tree ./views #= require_tree ./controllers window.Shake = new Marionette.Application() window.Shake.addRegions( top: '.top' main: '.main' ) Shake.Models = {} Shake.Views = {} Shake.Controllers = {} Shake.addInitializer (options) -> Backbone.history.start() Parse.initialize("<KEY>", "<KEY>")
true
#= require_self #= require_tree ./models #= require_tree ./views #= require_tree ./controllers window.Shake = new Marionette.Application() window.Shake.addRegions( top: '.top' main: '.main' ) Shake.Models = {} Shake.Views = {} Shake.Controllers = {} Shake.addInitializer (options) -> Backbone.history.start() Parse.initialize("PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI")
[ { "context": "ort')[0].value\n conf.proxy.shadowsocks.password = $('#shadowsocks-password')[0].value\n conf.proxy.shadowsocks.method = $('#", "end": 2540, "score": 0.8733566403388977, "start": 2516, "tag": "PASSWORD", "value": "$('#shadowsocks-password" } ]
modules/settingsUi.coffee
Magimagi/poi
3
config = require('./config') proxy = config.config.proxy util = require('./util') fs = require('fs') $ = global.settingsWin.window.$ exports.updatePacPath = (path) -> $('#pac-path')[0].value = "file://#{path}" exports.showModal = (title, content) -> $('#modal-message-title').text title $('#modal-message-content').text content $('#modal-message').modal() exports.showModalHtml = (title, content) -> $('#modal-message-title').html title $('#modal-message-content').html content $('#modal-message').modal() exports.initConfig = -> # Update tab state console.log 'in initConfig' console.log proxy $('#shadowsocks-tab-li').removeClass 'am-active' $('#shadowsocks-tab').removeClass 'am-in am-active' $('#http-tab-li').removeClass 'am-active' $('#http-tab').removeClass 'am-in am-active' $('#socks-tab-li').removeClass 'am-active' $('#socks-tab').removeClass 'am-in am-active' $('#none-tab-li').removeClass 'am-active' $('#none-tab').removeClass 'am-in am-active' if proxy.useShadowsocks $('#current-proxy').text 'shadowsocks' $('#shadowsocks-tab-li').addClass 'am-active' $('#shadowsocks-tab').addClass 'am-in am-active' else if proxy.useHttpProxy $('#current-proxy').text 'http' $('#http-tab-li').addClass 'am-active' $('#http-tab').addClass 'am-in am-active' else if proxy.useSocksProxy $('#current-proxy').text 'socks' $('#socks-tab-li').addClass 'am-active' $('#socks-tab').addClass 'am-in am-active' else $('#current-proxy').text 'none' $('#none-tab-li').addClass 'am-active' $('#none-tab').addClass 'am-in am-active' # Shadowsocks $('#shadowsocks-server-ip')[0].value = proxy.shadowsocks.serverIp $('#shadowsocks-server-port')[0].value = proxy.shadowsocks.serverPort $('#shadowsocks-password')[0].value = proxy.shadowsocks.password $('#shadowsocks-method')[0].value = proxy.shadowsocks.method # HTTP Proxy $('#httpproxy-ip')[0].value = proxy.httpProxy.httpProxyIp $('#httpproxy-port')[0].value = proxy.httpProxy.httpProxyPort # Socks Proxy $('#socksproxy-ip')[0].value = proxy.socksProxy.socksProxyIp $('#socksproxy-port')[0].value = proxy.socksProxy.socksProxyPort exports.saveConfig = -> conf = config.config # Shadowsocks conf.proxy.useShadowsocks = $('#current-proxy').text() == 'shadowsocks' conf.proxy.shadowsocks.serverIp = $('#shadowsocks-server-ip')[0].value conf.proxy.shadowsocks.serverPort = $('#shadowsocks-server-port')[0].value conf.proxy.shadowsocks.password = $('#shadowsocks-password')[0].value conf.proxy.shadowsocks.method = $('#shadowsocks-method')[0].value # HTTP conf.proxy.useHttpProxy = $('#current-proxy').text() == 'http' conf.proxy.httpProxy.httpProxyIp = $('#httpproxy-ip')[0].value conf.proxy.httpProxy.httpProxyPort = $('#httpproxy-port')[0].value # Socks conf.proxy.useSocksProxy = $('#current-proxy').text() == 'socks' conf.proxy.socksProxy.socksProxyIp = $('#socksproxy-ip')[0].value conf.proxy.socksProxy.socksProxyPort = $('#socksproxy-port')[0].value if config.updateConfig conf exports.showModal '保存设置', '保存成功,重新启动软件后生效。' else exports.showModal '保存设置', '保存失败…'
86858
config = require('./config') proxy = config.config.proxy util = require('./util') fs = require('fs') $ = global.settingsWin.window.$ exports.updatePacPath = (path) -> $('#pac-path')[0].value = "file://#{path}" exports.showModal = (title, content) -> $('#modal-message-title').text title $('#modal-message-content').text content $('#modal-message').modal() exports.showModalHtml = (title, content) -> $('#modal-message-title').html title $('#modal-message-content').html content $('#modal-message').modal() exports.initConfig = -> # Update tab state console.log 'in initConfig' console.log proxy $('#shadowsocks-tab-li').removeClass 'am-active' $('#shadowsocks-tab').removeClass 'am-in am-active' $('#http-tab-li').removeClass 'am-active' $('#http-tab').removeClass 'am-in am-active' $('#socks-tab-li').removeClass 'am-active' $('#socks-tab').removeClass 'am-in am-active' $('#none-tab-li').removeClass 'am-active' $('#none-tab').removeClass 'am-in am-active' if proxy.useShadowsocks $('#current-proxy').text 'shadowsocks' $('#shadowsocks-tab-li').addClass 'am-active' $('#shadowsocks-tab').addClass 'am-in am-active' else if proxy.useHttpProxy $('#current-proxy').text 'http' $('#http-tab-li').addClass 'am-active' $('#http-tab').addClass 'am-in am-active' else if proxy.useSocksProxy $('#current-proxy').text 'socks' $('#socks-tab-li').addClass 'am-active' $('#socks-tab').addClass 'am-in am-active' else $('#current-proxy').text 'none' $('#none-tab-li').addClass 'am-active' $('#none-tab').addClass 'am-in am-active' # Shadowsocks $('#shadowsocks-server-ip')[0].value = proxy.shadowsocks.serverIp $('#shadowsocks-server-port')[0].value = proxy.shadowsocks.serverPort $('#shadowsocks-password')[0].value = proxy.shadowsocks.password $('#shadowsocks-method')[0].value = proxy.shadowsocks.method # HTTP Proxy $('#httpproxy-ip')[0].value = proxy.httpProxy.httpProxyIp $('#httpproxy-port')[0].value = proxy.httpProxy.httpProxyPort # Socks Proxy $('#socksproxy-ip')[0].value = proxy.socksProxy.socksProxyIp $('#socksproxy-port')[0].value = proxy.socksProxy.socksProxyPort exports.saveConfig = -> conf = config.config # Shadowsocks conf.proxy.useShadowsocks = $('#current-proxy').text() == 'shadowsocks' conf.proxy.shadowsocks.serverIp = $('#shadowsocks-server-ip')[0].value conf.proxy.shadowsocks.serverPort = $('#shadowsocks-server-port')[0].value conf.proxy.shadowsocks.password = <PASSWORD>')[0].value conf.proxy.shadowsocks.method = $('#shadowsocks-method')[0].value # HTTP conf.proxy.useHttpProxy = $('#current-proxy').text() == 'http' conf.proxy.httpProxy.httpProxyIp = $('#httpproxy-ip')[0].value conf.proxy.httpProxy.httpProxyPort = $('#httpproxy-port')[0].value # Socks conf.proxy.useSocksProxy = $('#current-proxy').text() == 'socks' conf.proxy.socksProxy.socksProxyIp = $('#socksproxy-ip')[0].value conf.proxy.socksProxy.socksProxyPort = $('#socksproxy-port')[0].value if config.updateConfig conf exports.showModal '保存设置', '保存成功,重新启动软件后生效。' else exports.showModal '保存设置', '保存失败…'
true
config = require('./config') proxy = config.config.proxy util = require('./util') fs = require('fs') $ = global.settingsWin.window.$ exports.updatePacPath = (path) -> $('#pac-path')[0].value = "file://#{path}" exports.showModal = (title, content) -> $('#modal-message-title').text title $('#modal-message-content').text content $('#modal-message').modal() exports.showModalHtml = (title, content) -> $('#modal-message-title').html title $('#modal-message-content').html content $('#modal-message').modal() exports.initConfig = -> # Update tab state console.log 'in initConfig' console.log proxy $('#shadowsocks-tab-li').removeClass 'am-active' $('#shadowsocks-tab').removeClass 'am-in am-active' $('#http-tab-li').removeClass 'am-active' $('#http-tab').removeClass 'am-in am-active' $('#socks-tab-li').removeClass 'am-active' $('#socks-tab').removeClass 'am-in am-active' $('#none-tab-li').removeClass 'am-active' $('#none-tab').removeClass 'am-in am-active' if proxy.useShadowsocks $('#current-proxy').text 'shadowsocks' $('#shadowsocks-tab-li').addClass 'am-active' $('#shadowsocks-tab').addClass 'am-in am-active' else if proxy.useHttpProxy $('#current-proxy').text 'http' $('#http-tab-li').addClass 'am-active' $('#http-tab').addClass 'am-in am-active' else if proxy.useSocksProxy $('#current-proxy').text 'socks' $('#socks-tab-li').addClass 'am-active' $('#socks-tab').addClass 'am-in am-active' else $('#current-proxy').text 'none' $('#none-tab-li').addClass 'am-active' $('#none-tab').addClass 'am-in am-active' # Shadowsocks $('#shadowsocks-server-ip')[0].value = proxy.shadowsocks.serverIp $('#shadowsocks-server-port')[0].value = proxy.shadowsocks.serverPort $('#shadowsocks-password')[0].value = proxy.shadowsocks.password $('#shadowsocks-method')[0].value = proxy.shadowsocks.method # HTTP Proxy $('#httpproxy-ip')[0].value = proxy.httpProxy.httpProxyIp $('#httpproxy-port')[0].value = proxy.httpProxy.httpProxyPort # Socks Proxy $('#socksproxy-ip')[0].value = proxy.socksProxy.socksProxyIp $('#socksproxy-port')[0].value = proxy.socksProxy.socksProxyPort exports.saveConfig = -> conf = config.config # Shadowsocks conf.proxy.useShadowsocks = $('#current-proxy').text() == 'shadowsocks' conf.proxy.shadowsocks.serverIp = $('#shadowsocks-server-ip')[0].value conf.proxy.shadowsocks.serverPort = $('#shadowsocks-server-port')[0].value conf.proxy.shadowsocks.password = PI:PASSWORD:<PASSWORD>END_PI')[0].value conf.proxy.shadowsocks.method = $('#shadowsocks-method')[0].value # HTTP conf.proxy.useHttpProxy = $('#current-proxy').text() == 'http' conf.proxy.httpProxy.httpProxyIp = $('#httpproxy-ip')[0].value conf.proxy.httpProxy.httpProxyPort = $('#httpproxy-port')[0].value # Socks conf.proxy.useSocksProxy = $('#current-proxy').text() == 'socks' conf.proxy.socksProxy.socksProxyIp = $('#socksproxy-ip')[0].value conf.proxy.socksProxy.socksProxyPort = $('#socksproxy-port')[0].value if config.updateConfig conf exports.showModal '保存设置', '保存成功,重新启动软件后生效。' else exports.showModal '保存设置', '保存失败…'
[ { "context": "file), destFile)\n\n queue.push({\n name: name\n num: num\n lucky: 0\n image: ", "end": 942, "score": 0.9979379773139954, "start": 938, "tag": "NAME", "value": "name" } ]
init-data.coffee
huyinghuan/lottery-2016
113
_fs = require 'fs' _fse = require 'fs-extra' _path = require 'path' _Coal = require('./connection').getConnection() _config = require './config' _Employee = _Coal.Model('employee') _dest = _config.dest _img_source = _config.img_source doInit = -> _fs.readdir(_img_source, (err, files)-> queue = [] for file, index in files prefix = file.split(".")[0] name = prefix.split("_")[0] num = prefix.split("_")[1] if not num? console.log("照片格式不符合规范,应该以 姓名_唯一工号.png 或 姓名_唯一工号.jpg 命名:", file) continue num = num.replace(/\s/g, "") if index > 1 and (index % 30) is 1 console.log "本次插入#{queue.length}" _Employee.table().insert(queue).then(-> console.log(arguments, "成功!")).catch((e)-> console.log(e)) queue = [] destFile = _path.join(_dest, "#{num}.jpg") _fse.copySync(_path.join(_img_source, file), destFile) queue.push({ name: name num: num lucky: 0 image: "#{num}.jpg" }) console.log "本次插入#{queue.length}" _Employee.table().insert(queue) .then(-> console.log "所有数据插入成功!" _Employee.sql("SELECT count(*) from employee").then((data)-> console.log(data)) ).catch((e)-> console.log(e)) ) #取消下面三行才会进行数据初始化,数据初始化后 记得把注释加上,避免每次数据都还原。 #setTimeout(-> # doInit() #, 3000)
1797
_fs = require 'fs' _fse = require 'fs-extra' _path = require 'path' _Coal = require('./connection').getConnection() _config = require './config' _Employee = _Coal.Model('employee') _dest = _config.dest _img_source = _config.img_source doInit = -> _fs.readdir(_img_source, (err, files)-> queue = [] for file, index in files prefix = file.split(".")[0] name = prefix.split("_")[0] num = prefix.split("_")[1] if not num? console.log("照片格式不符合规范,应该以 姓名_唯一工号.png 或 姓名_唯一工号.jpg 命名:", file) continue num = num.replace(/\s/g, "") if index > 1 and (index % 30) is 1 console.log "本次插入#{queue.length}" _Employee.table().insert(queue).then(-> console.log(arguments, "成功!")).catch((e)-> console.log(e)) queue = [] destFile = _path.join(_dest, "#{num}.jpg") _fse.copySync(_path.join(_img_source, file), destFile) queue.push({ name: <NAME> num: num lucky: 0 image: "#{num}.jpg" }) console.log "本次插入#{queue.length}" _Employee.table().insert(queue) .then(-> console.log "所有数据插入成功!" _Employee.sql("SELECT count(*) from employee").then((data)-> console.log(data)) ).catch((e)-> console.log(e)) ) #取消下面三行才会进行数据初始化,数据初始化后 记得把注释加上,避免每次数据都还原。 #setTimeout(-> # doInit() #, 3000)
true
_fs = require 'fs' _fse = require 'fs-extra' _path = require 'path' _Coal = require('./connection').getConnection() _config = require './config' _Employee = _Coal.Model('employee') _dest = _config.dest _img_source = _config.img_source doInit = -> _fs.readdir(_img_source, (err, files)-> queue = [] for file, index in files prefix = file.split(".")[0] name = prefix.split("_")[0] num = prefix.split("_")[1] if not num? console.log("照片格式不符合规范,应该以 姓名_唯一工号.png 或 姓名_唯一工号.jpg 命名:", file) continue num = num.replace(/\s/g, "") if index > 1 and (index % 30) is 1 console.log "本次插入#{queue.length}" _Employee.table().insert(queue).then(-> console.log(arguments, "成功!")).catch((e)-> console.log(e)) queue = [] destFile = _path.join(_dest, "#{num}.jpg") _fse.copySync(_path.join(_img_source, file), destFile) queue.push({ name: PI:NAME:<NAME>END_PI num: num lucky: 0 image: "#{num}.jpg" }) console.log "本次插入#{queue.length}" _Employee.table().insert(queue) .then(-> console.log "所有数据插入成功!" _Employee.sql("SELECT count(*) from employee").then((data)-> console.log(data)) ).catch((e)-> console.log(e)) ) #取消下面三行才会进行数据初始化,数据初始化后 记得把注释加上,避免每次数据都还原。 #setTimeout(-> # doInit() #, 3000)
[ { "context": " #\n # Category.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http:/", "end": 45, "score": 0.9646839499473572, "start": 35, "tag": "NAME", "value": "hector spc" }, { "context": " #\n # Category.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http://www.aerstudio.com\n #\n", "end": 67, "score": 0.9999329447746277, "start": 47, "tag": "EMAIL", "value": "hector@aerstudio.com" } ]
src/collections/categories_collection.coffee
aerstudio/Phallanxpress
1
# # Category. # # Created by hector spc <hector@aerstudio.com> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # collections/categories_collection.js.coffee # class Phallanxpress.Categories extends Phallanxpress.Collection model: Phallanxpress.Category parseTag: 'categories' categoryList: (options)-> @_wpAPI('get_category_index', options) topCategories: ()-> top = @filter( (model)-> model.get('parent') is 0 ) tops = new Phallanxpress.Categories(top) tops.api = @api tops.apiUrl = @apiUrl tops
212488
# # Category. # # Created by <NAME> <<EMAIL>> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # collections/categories_collection.js.coffee # class Phallanxpress.Categories extends Phallanxpress.Collection model: Phallanxpress.Category parseTag: 'categories' categoryList: (options)-> @_wpAPI('get_category_index', options) topCategories: ()-> top = @filter( (model)-> model.get('parent') is 0 ) tops = new Phallanxpress.Categories(top) tops.api = @api tops.apiUrl = @apiUrl tops
true
# # Category. # # Created by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # collections/categories_collection.js.coffee # class Phallanxpress.Categories extends Phallanxpress.Collection model: Phallanxpress.Category parseTag: 'categories' categoryList: (options)-> @_wpAPI('get_category_index', options) topCategories: ()-> top = @filter( (model)-> model.get('parent') is 0 ) tops = new Phallanxpress.Categories(top) tops.api = @api tops.apiUrl = @apiUrl tops
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993050694465637, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-child-process-internal.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") #messages PREFIX = "NODE_" normal = cmd: "foo" + PREFIX internal = cmd: PREFIX + "bar" if process.argv[2] is "child" #send non-internal message containing PREFIX at a non prefix position process.send normal #send inernal message process.send internal process.exit 0 else fork = require("child_process").fork child = fork(process.argv[1], ["child"]) gotNormal = undefined child.once "message", (data) -> gotNormal = data return gotInternal = undefined child.once "internalMessage", (data) -> gotInternal = data return process.on "exit", -> assert.deepEqual gotNormal, normal assert.deepEqual gotInternal, internal return
170913
# 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") #messages PREFIX = "NODE_" normal = cmd: "foo" + PREFIX internal = cmd: PREFIX + "bar" if process.argv[2] is "child" #send non-internal message containing PREFIX at a non prefix position process.send normal #send inernal message process.send internal process.exit 0 else fork = require("child_process").fork child = fork(process.argv[1], ["child"]) gotNormal = undefined child.once "message", (data) -> gotNormal = data return gotInternal = undefined child.once "internalMessage", (data) -> gotInternal = data return process.on "exit", -> assert.deepEqual gotNormal, normal assert.deepEqual gotInternal, internal 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") #messages PREFIX = "NODE_" normal = cmd: "foo" + PREFIX internal = cmd: PREFIX + "bar" if process.argv[2] is "child" #send non-internal message containing PREFIX at a non prefix position process.send normal #send inernal message process.send internal process.exit 0 else fork = require("child_process").fork child = fork(process.argv[1], ["child"]) gotNormal = undefined child.once "message", (data) -> gotNormal = data return gotInternal = undefined child.once "internalMessage", (data) -> gotInternal = data return process.on "exit", -> assert.deepEqual gotNormal, normal assert.deepEqual gotInternal, internal return
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9991295337677002, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-repl-end-emits-exit.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. # create a dummy stream that does nothing testTerminalMode = -> r1 = repl.start( input: stream output: stream terminal: true ) process.nextTick -> # manually fire a ^D keypress stream.emit "data", "\u0004" return r1.on "exit", -> # should be fired from the simulated ^D keypress terminalExit++ testRegularMode() return return testRegularMode = -> r2 = repl.start( input: stream output: stream terminal: false ) process.nextTick -> stream.emit "end" return r2.on "exit", -> # should be fired from the simulated 'end' event regularExit++ return return common = require("../common") assert = require("assert") Stream = require("stream") repl = require("repl") terminalExit = 0 regularExit = 0 stream = new Stream() stream.write = stream.pause = stream.resume = -> stream.readable = stream.writable = true process.on "exit", -> assert.equal terminalExit, 1 assert.equal regularExit, 1 return # start testTerminalMode()
8402
# 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. # create a dummy stream that does nothing testTerminalMode = -> r1 = repl.start( input: stream output: stream terminal: true ) process.nextTick -> # manually fire a ^D keypress stream.emit "data", "\u0004" return r1.on "exit", -> # should be fired from the simulated ^D keypress terminalExit++ testRegularMode() return return testRegularMode = -> r2 = repl.start( input: stream output: stream terminal: false ) process.nextTick -> stream.emit "end" return r2.on "exit", -> # should be fired from the simulated 'end' event regularExit++ return return common = require("../common") assert = require("assert") Stream = require("stream") repl = require("repl") terminalExit = 0 regularExit = 0 stream = new Stream() stream.write = stream.pause = stream.resume = -> stream.readable = stream.writable = true process.on "exit", -> assert.equal terminalExit, 1 assert.equal regularExit, 1 return # start testTerminalMode()
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. # create a dummy stream that does nothing testTerminalMode = -> r1 = repl.start( input: stream output: stream terminal: true ) process.nextTick -> # manually fire a ^D keypress stream.emit "data", "\u0004" return r1.on "exit", -> # should be fired from the simulated ^D keypress terminalExit++ testRegularMode() return return testRegularMode = -> r2 = repl.start( input: stream output: stream terminal: false ) process.nextTick -> stream.emit "end" return r2.on "exit", -> # should be fired from the simulated 'end' event regularExit++ return return common = require("../common") assert = require("assert") Stream = require("stream") repl = require("repl") terminalExit = 0 regularExit = 0 stream = new Stream() stream.write = stream.pause = stream.resume = -> stream.readable = stream.writable = true process.on "exit", -> assert.equal terminalExit, 1 assert.equal regularExit, 1 return # start testTerminalMode()
[ { "context": "\"Recorda-m'ho més tard\"\n \"Escriure una ressenya ara\"\n\t\t]\n\tcs:\n\t\ttitle: \"Ohodnotit %@\"\n\t\tmessage: \"Pok", "end": 885, "score": 0.6791742444038391, "start": 879, "tag": "NAME", "value": "ya ara" }, { "context": "r!\"\n\t\tbuttonLabels: [\n\t\t\t\"Teşekkürler, Hayır\"\n\t\t\t\"Şimdi Oyla\"\n\t\t\t\"Sonra Hatırlat\"\n\t\t]\n\tuk:\n\t\ttitle: \"Оцінити %", "end": 6882, "score": 0.8698986172676086, "start": 6872, "tag": "NAME", "value": "Şimdi Oyla" }, { "context": " [\n\t\t\t\"Teşekkürler, Hayır\"\n\t\t\t\"Şimdi Oyla\"\n\t\t\t\"Sonra Hatırlat\"\n\t\t]\n\tuk:\n\t\ttitle: \"Оцінити %@\"\n\t\tmessage: \"Якщо ", "end": 6902, "score": 0.9342222213745117, "start": 6891, "tag": "NAME", "value": "ra Hatırlat" } ]
www_src/locales.coffee
Abine/cordova-plugin-apprate
0
### ar: displayAppName: "localized application name" title: "Window title" message: "Info message" buttonLabels: [ "no - 1" "later - 2" "yes - 3" ] ### AppRateLocales = ar: title: "قيِّم %@" message: "ذا أعجبك برنامج %@، هل تمانع من أخذ دقيقة لتقييمه؟ شكرا لدعمك!" buttonLabels: [ "لا، شكرا" "قيم البرنامج الآن" "ذكرني لاحقا" ] bn: title: "রেট %@" message: "আপনি %@ ব্যবহার করে ভোগ, আপনি এটি রেট একটি মুহূর্ত গ্রহণ কিছু মনে করবে? এটি একটি মিনিট চেয়ে বেশি গ্রহণ করা হবে না. আপনার সমর্থনের জন্য ধন্যবাদ!" buttonLabels: [ "না, ধন্যবাদ" "এখন এটি রেটিং করুন" "পরে আমাকে মনে করিয়ে দিন" ] ca: title: "Ressenya %@", message: "Si t'agrada %@, podries escriure una ressenya? No et prendrà més d'un minut. Gràcies pel teu suport!", buttonLabels: [ "No, gràcies" "Recorda-m'ho més tard" "Escriure una ressenya ara" ] cs: title: "Ohodnotit %@" message: "Pokud se vám líbí %@, našli byste si chvilku na ohodnocení aplikace? Nebude to trvat víc než minutu.\nDěkujeme za vaši podporu!" buttonLabels: [ "Ne, děkuji" "Ohodnotit nyní" "Připomenout později" ] da: title: "Vurdér %@" message: "Hvis du kan lide at bruge %@, vil du så ikke bruge et øjeblik på at give en vurdering? Det tager ikke mere end et minut. Mange tak for hjælpen!" buttonLabels: [ "Nej tak" "Vurdér nu" "Påmind mig senere" ] de: title: "Bewerte %@" message: "Wenn dir %@ gefällt, würdest Du es bitte bewerten? Dies wird nicht länger als eine Minute dauern. Danke für die Unterstützung!" buttonLabels: [ "Nein, danke" "Später erinnern" "Jetzt bewerten" ] el: title: "Αξιολόγησε %@" message: "Αν σ' αρέσει η εφαρμογή %@, θα μπορούσες να αφιερώσεις ένα δευτερόλεπτο για να την αξιολογήσεις; Ευχαριστούμε για την υποστήριξη!" buttonLabels: [ "Όχι, ευχαριστώ" "Αξιολόγησε τώρα" "Υπενθύμιση αργότερα" ] en: title: "Rate %@" message: "If you enjoy using %@, would you mind taking a moment to rate it? It won’t take more than a minute. Thanks for your support!" buttonLabels: [ "No, Thanks" "Remind Me Later" "Rate It Now" ] es: title: "Reseña %@" message: "Si te gusta %@, ¿podrías escribirnos una reseña? No te tomará más de un minuto. ¡Gracias por tu apoyo!" buttonLabels: [ "No, gracias" "Recordarme más tarde" "Escribir reseña ahora" ] fa: title: "نرخ %@" message: "اگر شما با استفاده از %@ لذت بردن از، اشکالی ندارد یک لحظه به امتیاز دهی هستند؟ آن را نمی خواهد بیشتر از یک دقیقه طول بکشد. با تشکر از حمایت شما!" buttonLabels: [ "نه، با تشکر" "آن را دوست ندارم حالا" "یادآوری من بعد" ] fr: title: "Notez %@" message: "Si vous aimez utiliser %@, n’oubliez pas de voter sur l’App Store. Cela ne prend qu’une minute. Merci d’avance pour votre soutien !" buttonLabels: [ "Non, merci" "Votez maintenant" "Me le rappeler ultérieurement" ] he: title: "דרג את %@" message: "אם אתה נהנה להשתמש ב- %@, אתה מוכן לקחת רגע כדי לדרג את את התוכנה? זה לא ייקח יותר מדקה. תודה על התמיכה!" buttonLabels: [ "לא, תודה" "דרג עכשיו" "הזכר לי מאוחר יותר" ] hi: title: "दर %@" message: "आप %@ उपयोग का आनंद ले, तो आप यह दर क्षण ले मन होगा? यह एक मिनट से अधिक नहीं ले जाएगा. आपके समर्थन के लिए धन्यवाद!" buttonLabels: [ "नहीं, धन्यवाद" "अब यह दर" "मुझे बाद में याद दिलाएं" ] id: title: "Beri Nilai %@" message: "Jika anda senang menggunakan %@, maukah anda memberikan nilai? Ini Hanya Sebentar. Terima kasih atas dukungan Anda!" buttonLabels: [ "Tidak, Terimakasih" "Berikan nilai sekarang!" "Ingatkan saya lagi" ] il: title: "Vota %@" message: "Se ti piace utilizzare %@, ti dispiacerebbe darle un voto? Non ci vorrà più di un minuto. Grazie per il vostro supporto!" buttonLabels: [ "No, grazie" "Vota ora" "Ricordamelo dopo" ] ja: title: "%@の評価" message: "%@をお使いいただき大変ありがとうございます。もしよろしければ1分程で済みますので、このアプリの評価をお願いします。ご協力感謝いたします!" buttonLabels: [ "いえ、結構です" "今すぐ評価する" "後でする" ] ko: title: "%@ 평가하기" message: "%@ 앱을 사용해 보신 소감이 어떠신가요? 리뷰 작성을 부탁 드립니다. 길어도 1분이면 작성하실 수 있을 것입니다. 도움 감사 드립니다." buttonLabels: [ "괜찮습니다" "지금 평가하기" "나중에 다시 알림" ] nl: title: "Beoordeel %@" message: "Als het gebruik van %@ je bevalt, wil je dan een moment nemen om het te beoordelen? Het duurt nog geen minuut. Bedankt voor je steun!" buttonLabels: [ "Nee, bedankt" "Beoordeel nu" "Herinner me er later aan" ] no: title: "Vurder %@" message: "Hvis du liker å bruke %@, ville du vært grei å vurdere appen? Det vil ikke ta mer enn et minutt. Takk for hjelpen!" buttonLabels: [ "Ellers takk" "Vurder nå" "Påminn meg senere" ] pa: title: "ਦਰ %@" message: "ਤੁਹਾਨੂੰ %@ ਵਰਤ ਆਨੰਦ ਹੋ, ਤੁਹਾਨੂੰ ਇਸ ਨੂੰ ਦਾ ਦਰਜਾ ਦਿੰਦੇ ਹਨ ਕਰਨ ਲਈ ਇੱਕ ਪਲ ਲੈ ਕੇ ਯਾਦ ਹੋਵੇਗਾ? ਇਸ ਨੂੰ ਇੱਕ ਮਿੰਟ ਵੀ ਵੱਧ ਲੱਗ ਨਹ ਹੋਵੇਗਾ. ਤੁਹਾਡੇ ਸਹਿਯੋਗ ਲਈ ਲਈ ਧੰਨਵਾਦ!" buttonLabels: [ "ਕੋਈ, ਦਾ ਧੰਨਵਾਦ ਹੈ" "ਹੁਣ ਇਹ ਦਰ ਨੂੰ" "ਮੈਨੂੰ ਬਾਅਦ ਵਿੱਚ ਯਾਦ" ] pl: title: "Oceń %@" message: "Jeśli lubisz %@, czy mógłbyś poświęcić chwilę na ocenienie? To nie zajmie więcej niż minutę. Dziękujemy za wsparcie!" buttonLabels: [ "Nie, dziękuję" "Oceń teraz" "Przypomnij później" ] pt: title: "Avaliar %@" message: "Se você gosta de usar o %@, você se importaria de avaliá-lo? Não vai demorar mais de um minuto. Obrigado por seu apoio!" buttonLabels: [ "Não, Obrigado" "Avaliar Agora" "Lembrar mais tarde" ] ru: title: "Оцените %@" message: "Если вам нравится пользоваться %@, не будете ли вы возражать против того, чтобы уделить минуту и оценить его?\nСпасибо вам за поддержку!" buttonLabels: [ "Нет, спасибо" "Напомнить позже" "Оценить сейчас" ] sk: title: "Ohodnotiť %@" message: "Ak sa vám páči %@, našli by ste si chvíľku na ohodnotenie aplikácie? Nebude to trvať viac ako minútu.\nĎakujeme za vašu podporu!" buttonLabels: [ "Nie, Ďakujem" "Ohodnotiť teraz" "Pripomenúť neskôr" ] sl: title: "Oceni %@" message: "Če vam je %@ všeč, bi vas prosili, da si vzamete moment in ocenite? Ne bo vam vzelo več kot minuto. Hvala za vašo podporo!" buttonLabels: [ "Ne, hvala" "Oceni zdaj" "Spomni me kasneje" ] sv: title: "Betygsätt %@" message: "Gillar du %@ och kan tänka dig att betygsätta den? Det tar inte mer än en minut. Tack för ditt stöd!" buttonLabels: [ "Nej tack" "Betygsätt nu!" "Påminn mig senare" ] th: title: "อัตรา %@" message: "หากคุณเพลิดเพลินกับการใช้ %@ คุณจะคิดสละเวลาให้คะแนนมันได้หรือไม่ มันจะไม่ใช้เวลานานกว่าหนึ่งนาที ขอบคุณสำหรับการสนับสนุนของคุณ" buttonLabels: [ "ไม่ขอบคุณ" "ให้คะแนนตอนนี้" "กรุณาเตือนผมมา" ] tr: title: "Oy %@" message: "Eğer %@ uygulamamız hoşunuza gittiyse, oy vermek ister misiniz? Bir dakikadan fazla sürmeyecektir. Desteğiniz için teşekkürler!" buttonLabels: [ "Teşekkürler, Hayır" "Şimdi Oyla" "Sonra Hatırlat" ] uk: title: "Оцінити %@" message: "Якщо вам подобається користуватися %@, чи не будете ви заперечувати проти того, щоб приділити хвилинку та оцінити її? Спасибі вам за підтримку!" buttonLabels: [ "Ні, дякую" "Оцінити зараз" "Нагадати пізніше" ] ur: title: "شرح %@" message: "اگر آپ نے %@ کا استعمال کرتے ہوئے سے لطف اندوز ہوتے، تو آپ کو ایک درجہ لمحے لینے میں کوئی اعتراض کریں گے؟ یہ ایک منٹ سے زیادہ نہیں لگے گا. آپ کی حمایت کے لئے شکریہ!" buttonLabels: [ "نہیں، شکریہ" "شرح اب یہ" "مجھے بعد میں یاد دلائیں" ] vi: title: "Đánh giá %@" message: "Nếu thích sử dụng %@, bạn có muốn giành một chút thời gian để đánh giá nó? Sẽ không lâu hơn một phút. Cảm ơn sự hỗ trợ của bạn!" buttonLabels: [ "Không, Cảm ơn" "Đánh Giá Ngay" "Nhắc Tôi Sau" ] module.exports = AppRateLocales
205815
### ar: displayAppName: "localized application name" title: "Window title" message: "Info message" buttonLabels: [ "no - 1" "later - 2" "yes - 3" ] ### AppRateLocales = ar: title: "قيِّم %@" message: "ذا أعجبك برنامج %@، هل تمانع من أخذ دقيقة لتقييمه؟ شكرا لدعمك!" buttonLabels: [ "لا، شكرا" "قيم البرنامج الآن" "ذكرني لاحقا" ] bn: title: "রেট %@" message: "আপনি %@ ব্যবহার করে ভোগ, আপনি এটি রেট একটি মুহূর্ত গ্রহণ কিছু মনে করবে? এটি একটি মিনিট চেয়ে বেশি গ্রহণ করা হবে না. আপনার সমর্থনের জন্য ধন্যবাদ!" buttonLabels: [ "না, ধন্যবাদ" "এখন এটি রেটিং করুন" "পরে আমাকে মনে করিয়ে দিন" ] ca: title: "Ressenya %@", message: "Si t'agrada %@, podries escriure una ressenya? No et prendrà més d'un minut. Gràcies pel teu suport!", buttonLabels: [ "No, gràcies" "Recorda-m'ho més tard" "Escriure una ressen<NAME>" ] cs: title: "Ohodnotit %@" message: "Pokud se vám líbí %@, našli byste si chvilku na ohodnocení aplikace? Nebude to trvat víc než minutu.\nDěkujeme za vaši podporu!" buttonLabels: [ "Ne, děkuji" "Ohodnotit nyní" "Připomenout později" ] da: title: "Vurdér %@" message: "Hvis du kan lide at bruge %@, vil du så ikke bruge et øjeblik på at give en vurdering? Det tager ikke mere end et minut. Mange tak for hjælpen!" buttonLabels: [ "Nej tak" "Vurdér nu" "Påmind mig senere" ] de: title: "Bewerte %@" message: "Wenn dir %@ gefällt, würdest Du es bitte bewerten? Dies wird nicht länger als eine Minute dauern. Danke für die Unterstützung!" buttonLabels: [ "Nein, danke" "Später erinnern" "Jetzt bewerten" ] el: title: "Αξιολόγησε %@" message: "Αν σ' αρέσει η εφαρμογή %@, θα μπορούσες να αφιερώσεις ένα δευτερόλεπτο για να την αξιολογήσεις; Ευχαριστούμε για την υποστήριξη!" buttonLabels: [ "Όχι, ευχαριστώ" "Αξιολόγησε τώρα" "Υπενθύμιση αργότερα" ] en: title: "Rate %@" message: "If you enjoy using %@, would you mind taking a moment to rate it? It won’t take more than a minute. Thanks for your support!" buttonLabels: [ "No, Thanks" "Remind Me Later" "Rate It Now" ] es: title: "Reseña %@" message: "Si te gusta %@, ¿podrías escribirnos una reseña? No te tomará más de un minuto. ¡Gracias por tu apoyo!" buttonLabels: [ "No, gracias" "Recordarme más tarde" "Escribir reseña ahora" ] fa: title: "نرخ %@" message: "اگر شما با استفاده از %@ لذت بردن از، اشکالی ندارد یک لحظه به امتیاز دهی هستند؟ آن را نمی خواهد بیشتر از یک دقیقه طول بکشد. با تشکر از حمایت شما!" buttonLabels: [ "نه، با تشکر" "آن را دوست ندارم حالا" "یادآوری من بعد" ] fr: title: "Notez %@" message: "Si vous aimez utiliser %@, n’oubliez pas de voter sur l’App Store. Cela ne prend qu’une minute. Merci d’avance pour votre soutien !" buttonLabels: [ "Non, merci" "Votez maintenant" "Me le rappeler ultérieurement" ] he: title: "דרג את %@" message: "אם אתה נהנה להשתמש ב- %@, אתה מוכן לקחת רגע כדי לדרג את את התוכנה? זה לא ייקח יותר מדקה. תודה על התמיכה!" buttonLabels: [ "לא, תודה" "דרג עכשיו" "הזכר לי מאוחר יותר" ] hi: title: "दर %@" message: "आप %@ उपयोग का आनंद ले, तो आप यह दर क्षण ले मन होगा? यह एक मिनट से अधिक नहीं ले जाएगा. आपके समर्थन के लिए धन्यवाद!" buttonLabels: [ "नहीं, धन्यवाद" "अब यह दर" "मुझे बाद में याद दिलाएं" ] id: title: "Beri Nilai %@" message: "Jika anda senang menggunakan %@, maukah anda memberikan nilai? Ini Hanya Sebentar. Terima kasih atas dukungan Anda!" buttonLabels: [ "Tidak, Terimakasih" "Berikan nilai sekarang!" "Ingatkan saya lagi" ] il: title: "Vota %@" message: "Se ti piace utilizzare %@, ti dispiacerebbe darle un voto? Non ci vorrà più di un minuto. Grazie per il vostro supporto!" buttonLabels: [ "No, grazie" "Vota ora" "Ricordamelo dopo" ] ja: title: "%@の評価" message: "%@をお使いいただき大変ありがとうございます。もしよろしければ1分程で済みますので、このアプリの評価をお願いします。ご協力感謝いたします!" buttonLabels: [ "いえ、結構です" "今すぐ評価する" "後でする" ] ko: title: "%@ 평가하기" message: "%@ 앱을 사용해 보신 소감이 어떠신가요? 리뷰 작성을 부탁 드립니다. 길어도 1분이면 작성하실 수 있을 것입니다. 도움 감사 드립니다." buttonLabels: [ "괜찮습니다" "지금 평가하기" "나중에 다시 알림" ] nl: title: "Beoordeel %@" message: "Als het gebruik van %@ je bevalt, wil je dan een moment nemen om het te beoordelen? Het duurt nog geen minuut. Bedankt voor je steun!" buttonLabels: [ "Nee, bedankt" "Beoordeel nu" "Herinner me er later aan" ] no: title: "Vurder %@" message: "Hvis du liker å bruke %@, ville du vært grei å vurdere appen? Det vil ikke ta mer enn et minutt. Takk for hjelpen!" buttonLabels: [ "Ellers takk" "Vurder nå" "Påminn meg senere" ] pa: title: "ਦਰ %@" message: "ਤੁਹਾਨੂੰ %@ ਵਰਤ ਆਨੰਦ ਹੋ, ਤੁਹਾਨੂੰ ਇਸ ਨੂੰ ਦਾ ਦਰਜਾ ਦਿੰਦੇ ਹਨ ਕਰਨ ਲਈ ਇੱਕ ਪਲ ਲੈ ਕੇ ਯਾਦ ਹੋਵੇਗਾ? ਇਸ ਨੂੰ ਇੱਕ ਮਿੰਟ ਵੀ ਵੱਧ ਲੱਗ ਨਹ ਹੋਵੇਗਾ. ਤੁਹਾਡੇ ਸਹਿਯੋਗ ਲਈ ਲਈ ਧੰਨਵਾਦ!" buttonLabels: [ "ਕੋਈ, ਦਾ ਧੰਨਵਾਦ ਹੈ" "ਹੁਣ ਇਹ ਦਰ ਨੂੰ" "ਮੈਨੂੰ ਬਾਅਦ ਵਿੱਚ ਯਾਦ" ] pl: title: "Oceń %@" message: "Jeśli lubisz %@, czy mógłbyś poświęcić chwilę na ocenienie? To nie zajmie więcej niż minutę. Dziękujemy za wsparcie!" buttonLabels: [ "Nie, dziękuję" "Oceń teraz" "Przypomnij później" ] pt: title: "Avaliar %@" message: "Se você gosta de usar o %@, você se importaria de avaliá-lo? Não vai demorar mais de um minuto. Obrigado por seu apoio!" buttonLabels: [ "Não, Obrigado" "Avaliar Agora" "Lembrar mais tarde" ] ru: title: "Оцените %@" message: "Если вам нравится пользоваться %@, не будете ли вы возражать против того, чтобы уделить минуту и оценить его?\nСпасибо вам за поддержку!" buttonLabels: [ "Нет, спасибо" "Напомнить позже" "Оценить сейчас" ] sk: title: "Ohodnotiť %@" message: "Ak sa vám páči %@, našli by ste si chvíľku na ohodnotenie aplikácie? Nebude to trvať viac ako minútu.\nĎakujeme za vašu podporu!" buttonLabels: [ "Nie, Ďakujem" "Ohodnotiť teraz" "Pripomenúť neskôr" ] sl: title: "Oceni %@" message: "Če vam je %@ všeč, bi vas prosili, da si vzamete moment in ocenite? Ne bo vam vzelo več kot minuto. Hvala za vašo podporo!" buttonLabels: [ "Ne, hvala" "Oceni zdaj" "Spomni me kasneje" ] sv: title: "Betygsätt %@" message: "Gillar du %@ och kan tänka dig att betygsätta den? Det tar inte mer än en minut. Tack för ditt stöd!" buttonLabels: [ "Nej tack" "Betygsätt nu!" "Påminn mig senare" ] th: title: "อัตรา %@" message: "หากคุณเพลิดเพลินกับการใช้ %@ คุณจะคิดสละเวลาให้คะแนนมันได้หรือไม่ มันจะไม่ใช้เวลานานกว่าหนึ่งนาที ขอบคุณสำหรับการสนับสนุนของคุณ" buttonLabels: [ "ไม่ขอบคุณ" "ให้คะแนนตอนนี้" "กรุณาเตือนผมมา" ] tr: title: "Oy %@" message: "Eğer %@ uygulamamız hoşunuza gittiyse, oy vermek ister misiniz? Bir dakikadan fazla sürmeyecektir. Desteğiniz için teşekkürler!" buttonLabels: [ "Teşekkürler, Hayır" "<NAME>" "Son<NAME>" ] uk: title: "Оцінити %@" message: "Якщо вам подобається користуватися %@, чи не будете ви заперечувати проти того, щоб приділити хвилинку та оцінити її? Спасибі вам за підтримку!" buttonLabels: [ "Ні, дякую" "Оцінити зараз" "Нагадати пізніше" ] ur: title: "شرح %@" message: "اگر آپ نے %@ کا استعمال کرتے ہوئے سے لطف اندوز ہوتے، تو آپ کو ایک درجہ لمحے لینے میں کوئی اعتراض کریں گے؟ یہ ایک منٹ سے زیادہ نہیں لگے گا. آپ کی حمایت کے لئے شکریہ!" buttonLabels: [ "نہیں، شکریہ" "شرح اب یہ" "مجھے بعد میں یاد دلائیں" ] vi: title: "Đánh giá %@" message: "Nếu thích sử dụng %@, bạn có muốn giành một chút thời gian để đánh giá nó? Sẽ không lâu hơn một phút. Cảm ơn sự hỗ trợ của bạn!" buttonLabels: [ "Không, Cảm ơn" "Đánh Giá Ngay" "Nhắc Tôi Sau" ] module.exports = AppRateLocales
true
### ar: displayAppName: "localized application name" title: "Window title" message: "Info message" buttonLabels: [ "no - 1" "later - 2" "yes - 3" ] ### AppRateLocales = ar: title: "قيِّم %@" message: "ذا أعجبك برنامج %@، هل تمانع من أخذ دقيقة لتقييمه؟ شكرا لدعمك!" buttonLabels: [ "لا، شكرا" "قيم البرنامج الآن" "ذكرني لاحقا" ] bn: title: "রেট %@" message: "আপনি %@ ব্যবহার করে ভোগ, আপনি এটি রেট একটি মুহূর্ত গ্রহণ কিছু মনে করবে? এটি একটি মিনিট চেয়ে বেশি গ্রহণ করা হবে না. আপনার সমর্থনের জন্য ধন্যবাদ!" buttonLabels: [ "না, ধন্যবাদ" "এখন এটি রেটিং করুন" "পরে আমাকে মনে করিয়ে দিন" ] ca: title: "Ressenya %@", message: "Si t'agrada %@, podries escriure una ressenya? No et prendrà més d'un minut. Gràcies pel teu suport!", buttonLabels: [ "No, gràcies" "Recorda-m'ho més tard" "Escriure una ressenPI:NAME:<NAME>END_PI" ] cs: title: "Ohodnotit %@" message: "Pokud se vám líbí %@, našli byste si chvilku na ohodnocení aplikace? Nebude to trvat víc než minutu.\nDěkujeme za vaši podporu!" buttonLabels: [ "Ne, děkuji" "Ohodnotit nyní" "Připomenout později" ] da: title: "Vurdér %@" message: "Hvis du kan lide at bruge %@, vil du så ikke bruge et øjeblik på at give en vurdering? Det tager ikke mere end et minut. Mange tak for hjælpen!" buttonLabels: [ "Nej tak" "Vurdér nu" "Påmind mig senere" ] de: title: "Bewerte %@" message: "Wenn dir %@ gefällt, würdest Du es bitte bewerten? Dies wird nicht länger als eine Minute dauern. Danke für die Unterstützung!" buttonLabels: [ "Nein, danke" "Später erinnern" "Jetzt bewerten" ] el: title: "Αξιολόγησε %@" message: "Αν σ' αρέσει η εφαρμογή %@, θα μπορούσες να αφιερώσεις ένα δευτερόλεπτο για να την αξιολογήσεις; Ευχαριστούμε για την υποστήριξη!" buttonLabels: [ "Όχι, ευχαριστώ" "Αξιολόγησε τώρα" "Υπενθύμιση αργότερα" ] en: title: "Rate %@" message: "If you enjoy using %@, would you mind taking a moment to rate it? It won’t take more than a minute. Thanks for your support!" buttonLabels: [ "No, Thanks" "Remind Me Later" "Rate It Now" ] es: title: "Reseña %@" message: "Si te gusta %@, ¿podrías escribirnos una reseña? No te tomará más de un minuto. ¡Gracias por tu apoyo!" buttonLabels: [ "No, gracias" "Recordarme más tarde" "Escribir reseña ahora" ] fa: title: "نرخ %@" message: "اگر شما با استفاده از %@ لذت بردن از، اشکالی ندارد یک لحظه به امتیاز دهی هستند؟ آن را نمی خواهد بیشتر از یک دقیقه طول بکشد. با تشکر از حمایت شما!" buttonLabels: [ "نه، با تشکر" "آن را دوست ندارم حالا" "یادآوری من بعد" ] fr: title: "Notez %@" message: "Si vous aimez utiliser %@, n’oubliez pas de voter sur l’App Store. Cela ne prend qu’une minute. Merci d’avance pour votre soutien !" buttonLabels: [ "Non, merci" "Votez maintenant" "Me le rappeler ultérieurement" ] he: title: "דרג את %@" message: "אם אתה נהנה להשתמש ב- %@, אתה מוכן לקחת רגע כדי לדרג את את התוכנה? זה לא ייקח יותר מדקה. תודה על התמיכה!" buttonLabels: [ "לא, תודה" "דרג עכשיו" "הזכר לי מאוחר יותר" ] hi: title: "दर %@" message: "आप %@ उपयोग का आनंद ले, तो आप यह दर क्षण ले मन होगा? यह एक मिनट से अधिक नहीं ले जाएगा. आपके समर्थन के लिए धन्यवाद!" buttonLabels: [ "नहीं, धन्यवाद" "अब यह दर" "मुझे बाद में याद दिलाएं" ] id: title: "Beri Nilai %@" message: "Jika anda senang menggunakan %@, maukah anda memberikan nilai? Ini Hanya Sebentar. Terima kasih atas dukungan Anda!" buttonLabels: [ "Tidak, Terimakasih" "Berikan nilai sekarang!" "Ingatkan saya lagi" ] il: title: "Vota %@" message: "Se ti piace utilizzare %@, ti dispiacerebbe darle un voto? Non ci vorrà più di un minuto. Grazie per il vostro supporto!" buttonLabels: [ "No, grazie" "Vota ora" "Ricordamelo dopo" ] ja: title: "%@の評価" message: "%@をお使いいただき大変ありがとうございます。もしよろしければ1分程で済みますので、このアプリの評価をお願いします。ご協力感謝いたします!" buttonLabels: [ "いえ、結構です" "今すぐ評価する" "後でする" ] ko: title: "%@ 평가하기" message: "%@ 앱을 사용해 보신 소감이 어떠신가요? 리뷰 작성을 부탁 드립니다. 길어도 1분이면 작성하실 수 있을 것입니다. 도움 감사 드립니다." buttonLabels: [ "괜찮습니다" "지금 평가하기" "나중에 다시 알림" ] nl: title: "Beoordeel %@" message: "Als het gebruik van %@ je bevalt, wil je dan een moment nemen om het te beoordelen? Het duurt nog geen minuut. Bedankt voor je steun!" buttonLabels: [ "Nee, bedankt" "Beoordeel nu" "Herinner me er later aan" ] no: title: "Vurder %@" message: "Hvis du liker å bruke %@, ville du vært grei å vurdere appen? Det vil ikke ta mer enn et minutt. Takk for hjelpen!" buttonLabels: [ "Ellers takk" "Vurder nå" "Påminn meg senere" ] pa: title: "ਦਰ %@" message: "ਤੁਹਾਨੂੰ %@ ਵਰਤ ਆਨੰਦ ਹੋ, ਤੁਹਾਨੂੰ ਇਸ ਨੂੰ ਦਾ ਦਰਜਾ ਦਿੰਦੇ ਹਨ ਕਰਨ ਲਈ ਇੱਕ ਪਲ ਲੈ ਕੇ ਯਾਦ ਹੋਵੇਗਾ? ਇਸ ਨੂੰ ਇੱਕ ਮਿੰਟ ਵੀ ਵੱਧ ਲੱਗ ਨਹ ਹੋਵੇਗਾ. ਤੁਹਾਡੇ ਸਹਿਯੋਗ ਲਈ ਲਈ ਧੰਨਵਾਦ!" buttonLabels: [ "ਕੋਈ, ਦਾ ਧੰਨਵਾਦ ਹੈ" "ਹੁਣ ਇਹ ਦਰ ਨੂੰ" "ਮੈਨੂੰ ਬਾਅਦ ਵਿੱਚ ਯਾਦ" ] pl: title: "Oceń %@" message: "Jeśli lubisz %@, czy mógłbyś poświęcić chwilę na ocenienie? To nie zajmie więcej niż minutę. Dziękujemy za wsparcie!" buttonLabels: [ "Nie, dziękuję" "Oceń teraz" "Przypomnij później" ] pt: title: "Avaliar %@" message: "Se você gosta de usar o %@, você se importaria de avaliá-lo? Não vai demorar mais de um minuto. Obrigado por seu apoio!" buttonLabels: [ "Não, Obrigado" "Avaliar Agora" "Lembrar mais tarde" ] ru: title: "Оцените %@" message: "Если вам нравится пользоваться %@, не будете ли вы возражать против того, чтобы уделить минуту и оценить его?\nСпасибо вам за поддержку!" buttonLabels: [ "Нет, спасибо" "Напомнить позже" "Оценить сейчас" ] sk: title: "Ohodnotiť %@" message: "Ak sa vám páči %@, našli by ste si chvíľku na ohodnotenie aplikácie? Nebude to trvať viac ako minútu.\nĎakujeme za vašu podporu!" buttonLabels: [ "Nie, Ďakujem" "Ohodnotiť teraz" "Pripomenúť neskôr" ] sl: title: "Oceni %@" message: "Če vam je %@ všeč, bi vas prosili, da si vzamete moment in ocenite? Ne bo vam vzelo več kot minuto. Hvala za vašo podporo!" buttonLabels: [ "Ne, hvala" "Oceni zdaj" "Spomni me kasneje" ] sv: title: "Betygsätt %@" message: "Gillar du %@ och kan tänka dig att betygsätta den? Det tar inte mer än en minut. Tack för ditt stöd!" buttonLabels: [ "Nej tack" "Betygsätt nu!" "Påminn mig senare" ] th: title: "อัตรา %@" message: "หากคุณเพลิดเพลินกับการใช้ %@ คุณจะคิดสละเวลาให้คะแนนมันได้หรือไม่ มันจะไม่ใช้เวลานานกว่าหนึ่งนาที ขอบคุณสำหรับการสนับสนุนของคุณ" buttonLabels: [ "ไม่ขอบคุณ" "ให้คะแนนตอนนี้" "กรุณาเตือนผมมา" ] tr: title: "Oy %@" message: "Eğer %@ uygulamamız hoşunuza gittiyse, oy vermek ister misiniz? Bir dakikadan fazla sürmeyecektir. Desteğiniz için teşekkürler!" buttonLabels: [ "Teşekkürler, Hayır" "PI:NAME:<NAME>END_PI" "SonPI:NAME:<NAME>END_PI" ] uk: title: "Оцінити %@" message: "Якщо вам подобається користуватися %@, чи не будете ви заперечувати проти того, щоб приділити хвилинку та оцінити її? Спасибі вам за підтримку!" buttonLabels: [ "Ні, дякую" "Оцінити зараз" "Нагадати пізніше" ] ur: title: "شرح %@" message: "اگر آپ نے %@ کا استعمال کرتے ہوئے سے لطف اندوز ہوتے، تو آپ کو ایک درجہ لمحے لینے میں کوئی اعتراض کریں گے؟ یہ ایک منٹ سے زیادہ نہیں لگے گا. آپ کی حمایت کے لئے شکریہ!" buttonLabels: [ "نہیں، شکریہ" "شرح اب یہ" "مجھے بعد میں یاد دلائیں" ] vi: title: "Đánh giá %@" message: "Nếu thích sử dụng %@, bạn có muốn giành một chút thời gian để đánh giá nó? Sẽ không lâu hơn một phút. Cảm ơn sự hỗ trợ của bạn!" buttonLabels: [ "Không, Cảm ơn" "Đánh Giá Ngay" "Nhắc Tôi Sau" ] module.exports = AppRateLocales
[ { "context": "###!\n@author Branko Vukelic <branko@brankovukelic.com>\n@license MIT\n###\n\n# # ", "end": 27, "score": 0.9998807907104492, "start": 13, "tag": "NAME", "value": "Branko Vukelic" }, { "context": "###!\n@author Branko Vukelic <branko@brankovukelic.com>\n@license MIT\n###\n\n# # Soap collection\n#\n# This m", "end": 53, "score": 0.999930202960968, "start": 29, "tag": "EMAIL", "value": "branko@brankovukelic.com" } ]
src/lib/collection.coffee
foxbunny/ribcage-soap
0
###! @author Branko Vukelic <branko@brankovukelic.com> @license MIT ### # # Soap collection # # This module implements a soap-based collection. Since making Soap requests # per model can be expensive in some cases, this collection will make a SOAP # request and instantiate appropriate models. # # This module is in UMD format and will export `ribcgeSoap.Collection` global # if not used with an AMD loader such as RequireJS. if typeof define isnt 'function' or not define.amd @require = (dep) => (() => switch dep when 'ribcage' then @Ribcage when './mixin' then @ribcageSoap.mixin else null )() or throw new Error "Unmet dependency #{dep}" @define = (factory) => @ribcageSoap.Collection = factory @require # This module depends on `ribcage-soap.mixin` module and Ribcage define (require) -> ribcage = require 'ribcage' soapMixin = require './mixin' # ## `SoapCollection` # # Please see the documentation on `soapMixin` for more information on the API # for this collection. SoapCollection = ribcage.collections.BaseCollection.extend soapMixin # Add the mixin and collection to ribcage object ribcage.collectionMixins.SoapCollection = soapMixin ribcage.collections.SoapCollection = SoapCollection
93330
###! @author <NAME> <<EMAIL>> @license MIT ### # # Soap collection # # This module implements a soap-based collection. Since making Soap requests # per model can be expensive in some cases, this collection will make a SOAP # request and instantiate appropriate models. # # This module is in UMD format and will export `ribcgeSoap.Collection` global # if not used with an AMD loader such as RequireJS. if typeof define isnt 'function' or not define.amd @require = (dep) => (() => switch dep when 'ribcage' then @Ribcage when './mixin' then @ribcageSoap.mixin else null )() or throw new Error "Unmet dependency #{dep}" @define = (factory) => @ribcageSoap.Collection = factory @require # This module depends on `ribcage-soap.mixin` module and Ribcage define (require) -> ribcage = require 'ribcage' soapMixin = require './mixin' # ## `SoapCollection` # # Please see the documentation on `soapMixin` for more information on the API # for this collection. SoapCollection = ribcage.collections.BaseCollection.extend soapMixin # Add the mixin and collection to ribcage object ribcage.collectionMixins.SoapCollection = soapMixin ribcage.collections.SoapCollection = SoapCollection
true
###! @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @license MIT ### # # Soap collection # # This module implements a soap-based collection. Since making Soap requests # per model can be expensive in some cases, this collection will make a SOAP # request and instantiate appropriate models. # # This module is in UMD format and will export `ribcgeSoap.Collection` global # if not used with an AMD loader such as RequireJS. if typeof define isnt 'function' or not define.amd @require = (dep) => (() => switch dep when 'ribcage' then @Ribcage when './mixin' then @ribcageSoap.mixin else null )() or throw new Error "Unmet dependency #{dep}" @define = (factory) => @ribcageSoap.Collection = factory @require # This module depends on `ribcage-soap.mixin` module and Ribcage define (require) -> ribcage = require 'ribcage' soapMixin = require './mixin' # ## `SoapCollection` # # Please see the documentation on `soapMixin` for more information on the API # for this collection. SoapCollection = ribcage.collections.BaseCollection.extend soapMixin # Add the mixin and collection to ribcage object ribcage.collectionMixins.SoapCollection = soapMixin ribcage.collections.SoapCollection = SoapCollection
[ { "context": "rrors.push errorMsg\n\n # \"a.en,a.de,a.it\"\n # \"hi,Hallo,ciao\"\n # values:\n # de: 'Hallo'\n # en: 'hi", "end": 16265, "score": 0.9910492897033691, "start": 16260, "tag": "NAME", "value": "Hallo" }, { "context": "push errorMsg\n\n # \"a.en,a.de,a.it\"\n # \"hi,Hallo,ciao\"\n # values:\n # de: 'Hallo'\n # en: 'hi'\n #", "end": 16270, "score": 0.9649405479431152, "start": 16266, "tag": "NAME", "value": "ciao" }, { "context": ",a.it\"\n # \"hi,Hallo,ciao\"\n # values:\n # de: 'Hallo'\n # en: 'hi'\n # it: 'ciao'\n mapLocalizedAt", "end": 16300, "score": 0.9993659257888794, "start": 16295, "tag": "NAME", "value": "Hallo" }, { "context": "y values\n values\n\n # \"a.en,a.de,a.it\"\n # \"hi,Hallo,ciao\"\n # values:\n # de: 'Hallo'\n # en: 'hi", "end": 16877, "score": 0.9826900959014893, "start": 16872, "tag": "NAME", "value": "Hallo" }, { "context": "es\n values\n\n # \"a.en,a.de,a.it\"\n # \"hi,Hallo,ciao\"\n # values:\n # de: 'Hallo'\n # en: 'hi'\n #", "end": 16882, "score": 0.917851448059082, "start": 16878, "tag": "NAME", "value": "ciao" }, { "context": ",a.it\"\n # \"hi,Hallo,ciao\"\n # values:\n # de: 'Hallo'\n # en: 'hi'\n # it: 'ciao'\n mapSearchKeywo", "end": 16912, "score": 0.9992319345474243, "start": 16907, "tag": "NAME", "value": "Hallo" } ]
src/coffee/mapping.coffee
easybi-vv/sphere-node-product-csv-sync-1
0
_ = require 'underscore' _.mixin require('underscore.string').exports() CONS = require './constants' GLOBALS = require './globals' # TODO: # - JSDoc # - no services!!! # - utils only class Mapping constructor: (options = {}) -> @types = options.types @customerGroups = options.customerGroups @categories = options.categories @taxes = options.taxes @states = options.states @channels = options.channels @continueOnProblems = options.continueOnProblems @errors = [] mapProduct: (raw, productType) -> productType or= raw.master[@header.toIndex CONS.HEADER_PRODUCT_TYPE] rowIndex = raw.startRow product = @mapBaseProduct raw.master, productType, rowIndex product.masterVariant = @mapVariant raw.master, 1, productType, rowIndex, product _.each raw.variants, (entry, index) => product.variants.push @mapVariant entry.variant, index + 2, productType, entry.rowIndex, product data = product: product rowIndex: raw.startRow header: @header publish: raw.publish data mapBaseProduct: (rawMaster, productType, rowIndex) -> product = productType: typeId: 'product-type' id: productType.id masterVariant: {} variants: [] if @header.has(CONS.HEADER_ID) product.id = rawMaster[@header.toIndex CONS.HEADER_ID] if @header.has(CONS.HEADER_KEY) product.key = rawMaster[@header.toIndex CONS.HEADER_KEY] if @header.has(CONS.HEADER_META_TITLE) product.metaTitle = rawMaster[@header.toIndex CONS.HEADER_META_TITLE] or {} if @header.has(CONS.HEADER_META_DESCRIPTION) product.metaDescription = rawMaster[@header.toIndex CONS.HEADER_META_DESCRIPTION] or {} if @header.has(CONS.HEADER_META_KEYWORDS) product.metaKeywords = rawMaster[@header.toIndex CONS.HEADER_META_KEYWORDS] or {} if @header.has(CONS.HEADER_SEARCH_KEYWORDS) product.searchKeywords = rawMaster[@header.toIndex CONS.HEADER_SEARCH_KEYWORDS] or {} product.categories = @mapCategories rawMaster, rowIndex tax = @mapTaxCategory rawMaster, rowIndex product.taxCategory = tax if tax state = @mapState rawMaster, rowIndex product.state = state if state product.categoryOrderHints = @mapCategoryOrderHints rawMaster, rowIndex for attribName in CONS.BASE_LOCALIZED_HEADERS if attribName is CONS.HEADER_SEARCH_KEYWORDS val = @mapSearchKeywords rawMaster, attribName, @header.toLanguageIndex() else val = @mapLocalizedAttrib rawMaster, attribName, @header.toLanguageIndex() product[attribName] = val if val unless product.slug product.slug = {} if product.name? and product.name[GLOBALS.DEFAULT_LANGUAGE]? product.slug[GLOBALS.DEFAULT_LANGUAGE] = @ensureValidSlug(_.slugify product.name[GLOBALS.DEFAULT_LANGUAGE], rowIndex) product ensureValidSlug: (slug, rowIndex, appendix = '') -> unless _.isString(slug) and slug.length > 2 @errors.push "[row #{rowIndex}:#{CONS.HEADER_SLUG}] Can't generate valid slug out of '#{slug}'! If you did not provide slug in your file, please do so as slug could not be auto-generated from the product name given." return @slugs or= [] currentSlug = "#{slug}#{appendix}" unless _.contains(@slugs, currentSlug) @slugs.push currentSlug return currentSlug @ensureValidSlug slug, rowIndex, Math.floor((Math.random() * 89999) + 10001) # five digets hasValidValueForHeader: (row, headerName) -> return false unless @header.has(headerName) @isValidValue(row[@header.toIndex headerName]) isValidValue: (rawValue) -> return _.isString(rawValue) and rawValue.length > 0 mapCategories: (rawMaster, rowIndex) -> categories = [] return categories unless @hasValidValueForHeader(rawMaster, CONS.HEADER_CATEGORIES) rawCategories = rawMaster[@header.toIndex CONS.HEADER_CATEGORIES].split GLOBALS.DELIM_MULTI_VALUE for rawCategory in rawCategories cat = typeId: 'category' if _.has(@categories.externalId2id, rawCategory) cat.id = @categories.externalId2id[rawCategory] else if _.has(@categories.fqName2id, rawCategory) cat.id = @categories.fqName2id[rawCategory] else if _.has(@categories.name2id, rawCategory) if _.contains(@categories.duplicateNames, rawCategory) msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORIES}] The category '#{rawCategory}' is not unqiue!" if @continueOnProblems console.warn msg else @errors.push msg else cat.id = @categories.name2id[rawCategory] if cat.id categories.push cat else msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORIES}] Can not find category for '#{rawCategory}'!" if @continueOnProblems console.warn msg else @errors.push msg categories # parses the categoryOrderHints column for a given row mapCategoryOrderHints: (rawMaster, rowIndex) -> catOrderHints = {} # check if there actually is something to parse in the column return catOrderHints unless @hasValidValueForHeader(rawMaster, CONS.HEADER_CATEGORY_ORDER_HINTS) # parse the value to get a list of all catOrderHints rawCatOrderHints = rawMaster[@header.toIndex CONS.HEADER_CATEGORY_ORDER_HINTS].split GLOBALS.DELIM_MULTI_VALUE _.each rawCatOrderHints, (rawCatOrderHint) => # extract the category id and the order hint from the raw value [rawCatId, rawOrderHint] = rawCatOrderHint.split ':' orderHint = parseFloat(rawOrderHint) # check if the product is actually assigned to the category catId = if _.has(@categories.id2fqName, rawCatId) rawCatId else if _.has(@categories.externalId2id, rawCatId) @categories.externalId2id[rawCatId] # in case the category was provided as the category name # check if the product is actually assigend to the category else if _.has(@categories.name2id, rawCatId) # get the actual category id instead of the category name @categories.name2id[rawCatId] # in case the category was provided using the category slug else if _.contains(@categories.id2slug, rawCatId) # get the actual category id instead of the category name _.findKey @categories.id2slug, (slug) -> slug == rawCatId else msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Can not find category for ID '#{rawCatId}'!" if @continueOnProblems console.warn msg else @errors.push msg null if orderHint == NaN msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Order hint has to be a valid number!" if @continueOnProblems console.warn msg else @errors.push msg else if !(orderHint > 0 && orderHint < 1) msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Order hint has to be < 1 and > 0 but was '#{orderHint}'!" if @continueOnProblems console.warn msg else @errors.push msg else if catId # orderHint and catId are ensured to be valid catOrderHints[catId] = orderHint.toString() catOrderHints mapTaxCategory: (rawMaster, rowIndex) -> return unless @hasValidValueForHeader(rawMaster, CONS.HEADER_TAX) rawTax = rawMaster[@header.toIndex CONS.HEADER_TAX] if _.contains(@taxes.duplicateNames, rawTax) @errors.push "[row #{rowIndex}:#{CONS.HEADER_TAX}] The tax category '#{rawTax}' is not unqiue!" return unless _.has(@taxes.name2id, rawTax) @errors.push "[row #{rowIndex}:#{CONS.HEADER_TAX}] The tax category '#{rawTax}' is unknown!" return tax = typeId: 'tax-category' id: @taxes.name2id[rawTax] mapState: (rawMaster, rowIndex) -> return unless @hasValidValueForHeader(rawMaster, CONS.HEADER_STATE) rawState = rawMaster[@header.toIndex CONS.HEADER_STATE] if _.contains(@states.duplicateKeys, rawState) @errors.push "[row #{rowIndex}:#{CONS.HEADER_STATE}] The state '#{rawState}' is not unqiue!" return unless _.has(@states.key2id, rawState) @errors.push "[row #{rowIndex}:#{CONS.HEADER_STATE}] The state '#{rawState}' is unknown!" return state = typeId: 'state' id: @states.key2id[rawState] mapVariant: (rawVariant, variantId, productType, rowIndex, product) -> if variantId > 2 and @header.has(CONS.HEADER_VARIANT_ID) vId = @mapInteger rawVariant[@header.toIndex CONS.HEADER_VARIANT_ID], CONS.HEADER_VARIANT_ID, rowIndex if vId? and not _.isNaN vId variantId = vId else # we have no valid variant id - mapInteger already mentioned this as error return variant = id: variantId attributes: [] if @header.has(CONS.HEADER_VARIANT_KEY) variant.key = rawVariant[@header.toIndex CONS.HEADER_VARIANT_KEY] variant.sku = rawVariant[@header.toIndex CONS.HEADER_SKU] if @header.has CONS.HEADER_SKU languageHeader2Index = @header._productTypeLanguageIndexes productType if productType.attributes for attribute in productType.attributes attrib = if attribute.attributeConstraint is CONS.ATTRIBUTE_CONSTRAINT_SAME_FOR_ALL and variantId > 1 _.find product.masterVariant.attributes, (a) -> a.name is attribute.name else @mapAttribute rawVariant, attribute, languageHeader2Index, rowIndex variant.attributes.push attrib if attrib variant.prices = @mapPrices rawVariant[@header.toIndex CONS.HEADER_PRICES], rowIndex variant.images = @mapImages rawVariant, variantId, rowIndex variant mapAttribute: (rawVariant, attribute, languageHeader2Index, rowIndex) -> # if attribute conflicts with some base product property prefix it with "attribute." string prefixedAttributeName = if attribute.name in CONS.PRODUCT_LEVEL_PROPERTIES.concat(CONS.ALL_HEADERS) "attribute.#{attribute.name}" else attribute.name value = @mapValue rawVariant, prefixedAttributeName, attribute, languageHeader2Index, rowIndex return undefined if _.isUndefined(value) or (_.isObject(value) and _.isEmpty(value)) or (_.isString(value) and _.isEmpty(value)) attribute = name: attribute.name value: value attribute mapValue: (rawVariant, attributeName, attribute, languageHeader2Index, rowIndex) -> switch attribute.type.name when CONS.ATTRIBUTE_TYPE_SET then @mapSetAttribute rawVariant, attributeName, attribute.type.elementType, languageHeader2Index, rowIndex when CONS.ATTRIBUTE_TYPE_LTEXT then @mapLocalizedAttrib rawVariant, attributeName, languageHeader2Index when CONS.ATTRIBUTE_TYPE_NUMBER then @mapNumber rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_BOOLEAN then @mapBoolean rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_MONEY then @mapMoney rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_REFERENCE then @mapReference rawVariant[@header.toIndex attributeName], attribute.type when CONS.ATTRIBUTE_TYPE_ENUM then @mapEnumAttribute rawVariant[@header.toIndex attributeName], attribute.type.values when CONS.ATTRIBUTE_TYPE_LENUM then @mapEnumAttribute rawVariant[@header.toIndex attributeName], attribute.type.values else rawVariant[@header.toIndex attributeName] # works for text mapEnumAttribute: (enumKey, enumValues) -> if enumKey _.find enumValues, (value) -> value.key is enumKey mapSetAttribute: (rawVariant, attributeName, elementType, languageHeader2Index, rowIndex) -> if elementType.name is CONS.ATTRIBUTE_TYPE_LTEXT multiValObj = @mapLocalizedAttrib rawVariant, attributeName, languageHeader2Index value = [] _.each multiValObj, (raw, lang) => if @isValidValue(raw) languageVals = raw.split GLOBALS.DELIM_MULTI_VALUE _.each languageVals, (v, index) -> localized = {} localized[lang] = v value[index] = _.extend (value[index] or {}), localized value else raw = rawVariant[@header.toIndex attributeName] if @isValidValue(raw) rawValues = raw.split GLOBALS.DELIM_MULTI_VALUE _.map rawValues, (rawValue) => switch elementType.name when CONS.ATTRIBUTE_TYPE_MONEY @mapMoney rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_NUMBER @mapNumber rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_BOOLEAN @mapBoolean rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_ENUM @mapEnumAttribute rawValue, elementType.values when CONS.ATTRIBUTE_TYPE_LENUM @mapEnumAttribute rawValue, elementType.values when CONS.ATTRIBUTE_TYPE_REFERENCE @mapReference rawValue, elementType else rawValue mapPrices: (raw, rowIndex) -> prices = [] return prices unless @isValidValue(raw) rawPrices = raw.split GLOBALS.DELIM_MULTI_VALUE for rawPrice in rawPrices matchedPrice = CONS.REGEX_PRICE.exec rawPrice unless matchedPrice @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not parse price '#{rawPrice}'!" continue country = matchedPrice[2] currencyCode = matchedPrice[3] centAmount = matchedPrice[4] customerGroupName = matchedPrice[8] channelKey = matchedPrice[10] validFrom = matchedPrice[12] validUntil = matchedPrice[14] price = value: @mapMoney "#{currencyCode} #{centAmount}", CONS.HEADER_PRICES, rowIndex price.validFrom = validFrom if validFrom price.validUntil = validUntil if validUntil price.country = country if country if customerGroupName unless _.has(@customerGroups.name2id, customerGroupName) @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not find customer group '#{customerGroupName}'!" return [] price.customerGroup = typeId: 'customer-group' id: @customerGroups.name2id[customerGroupName] if channelKey unless _.has(@channels.key2id, channelKey) @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not find channel with key '#{channelKey}'!" return [] price.channel = typeId: 'channel' id: @channels.key2id[channelKey] prices.push price prices # EUR 300 # USD 999 mapMoney: (rawMoney, attribName, rowIndex) -> return unless @isValidValue(rawMoney) matchedMoney = CONS.REGEX_MONEY.exec rawMoney unless matchedMoney @errors.push "[row #{rowIndex}:#{attribName}] Can not parse money '#{rawMoney}'!" return # TODO: check for correct currencyCode money = currencyCode: matchedMoney[1] centAmount: parseInt matchedMoney[2] mapReference: (rawReference, attributeType) -> return undefined unless rawReference ref = id: rawReference typeId: attributeType.referenceTypeId mapInteger: (rawNumber, attribName, rowIndex) -> parseInt @mapNumber(rawNumber, attribName, rowIndex, CONS.REGEX_INTEGER) mapNumber: (rawNumber, attribName, rowIndex, regEx = CONS.REGEX_FLOAT) -> return unless @isValidValue(rawNumber) matchedNumber = regEx.exec rawNumber unless matchedNumber @errors.push "[row #{rowIndex}:#{attribName}] The number '#{rawNumber}' isn't valid!" return parseFloat matchedNumber[0] mapBoolean: (rawBoolean, attribName, rowIndex) -> if _.isUndefined(rawBoolean) or (_.isString(rawBoolean) and _.isEmpty(rawBoolean)) return errorMsg = "[row #{rowIndex}:#{attribName}] The value '#{rawBoolean}' isn't a valid boolean!" try b = JSON.parse(rawBoolean.toLowerCase()) if _.isBoolean(b) or b == 0 or b == 1 return Boolean(b) else @errors.push errorMsg return catch @errors.push errorMsg # "a.en,a.de,a.it" # "hi,Hallo,ciao" # values: # de: 'Hallo' # en: 'hi' # it: 'ciao' mapLocalizedAttrib: (row, attribName, langH2i) -> values = {} if _.has langH2i, attribName _.each langH2i[attribName], (index, language) -> val = row[index] values[language] = val if val # fall back to non localized column if language columns could not be found if _.size(values) is 0 return unless @header.has(attribName) val = row[@header.toIndex attribName] values[GLOBALS.DEFAULT_LANGUAGE] = val if val return if _.isEmpty values values # "a.en,a.de,a.it" # "hi,Hallo,ciao" # values: # de: 'Hallo' # en: 'hi' # it: 'ciao' mapSearchKeywords: (row, attribName, langH2i) -> values = {} if _.has langH2i, attribName _.each langH2i[attribName], (index, language) -> val = row[index] if not _.isString(val) || val == "" return singleValues = val.split GLOBALS.DELIM_MULTI_VALUE texts = [] _.each singleValues, (v, index) -> texts.push { text: v} values[language] = texts # fall back to non localized column if language columns could not be found if _.size(values) is 0 return unless @header.has(attribName) val = row[@header.toIndex attribName] values[GLOBALS.DEFAULT_LANGUAGE].text = val if val return if _.isEmpty values values mapImages: (rawVariant, variantId, rowIndex) -> images = [] return images unless @hasValidValueForHeader(rawVariant, CONS.HEADER_IMAGES) rawImages = rawVariant[@header.toIndex CONS.HEADER_IMAGES].split GLOBALS.DELIM_MULTI_VALUE for rawImage in rawImages image = url: rawImage # TODO: get dimensions from CSV - format idea: 200x400;90x90 dimensions: w: 0 h: 0 # label: 'TODO' images.push image images module.exports = Mapping
223143
_ = require 'underscore' _.mixin require('underscore.string').exports() CONS = require './constants' GLOBALS = require './globals' # TODO: # - JSDoc # - no services!!! # - utils only class Mapping constructor: (options = {}) -> @types = options.types @customerGroups = options.customerGroups @categories = options.categories @taxes = options.taxes @states = options.states @channels = options.channels @continueOnProblems = options.continueOnProblems @errors = [] mapProduct: (raw, productType) -> productType or= raw.master[@header.toIndex CONS.HEADER_PRODUCT_TYPE] rowIndex = raw.startRow product = @mapBaseProduct raw.master, productType, rowIndex product.masterVariant = @mapVariant raw.master, 1, productType, rowIndex, product _.each raw.variants, (entry, index) => product.variants.push @mapVariant entry.variant, index + 2, productType, entry.rowIndex, product data = product: product rowIndex: raw.startRow header: @header publish: raw.publish data mapBaseProduct: (rawMaster, productType, rowIndex) -> product = productType: typeId: 'product-type' id: productType.id masterVariant: {} variants: [] if @header.has(CONS.HEADER_ID) product.id = rawMaster[@header.toIndex CONS.HEADER_ID] if @header.has(CONS.HEADER_KEY) product.key = rawMaster[@header.toIndex CONS.HEADER_KEY] if @header.has(CONS.HEADER_META_TITLE) product.metaTitle = rawMaster[@header.toIndex CONS.HEADER_META_TITLE] or {} if @header.has(CONS.HEADER_META_DESCRIPTION) product.metaDescription = rawMaster[@header.toIndex CONS.HEADER_META_DESCRIPTION] or {} if @header.has(CONS.HEADER_META_KEYWORDS) product.metaKeywords = rawMaster[@header.toIndex CONS.HEADER_META_KEYWORDS] or {} if @header.has(CONS.HEADER_SEARCH_KEYWORDS) product.searchKeywords = rawMaster[@header.toIndex CONS.HEADER_SEARCH_KEYWORDS] or {} product.categories = @mapCategories rawMaster, rowIndex tax = @mapTaxCategory rawMaster, rowIndex product.taxCategory = tax if tax state = @mapState rawMaster, rowIndex product.state = state if state product.categoryOrderHints = @mapCategoryOrderHints rawMaster, rowIndex for attribName in CONS.BASE_LOCALIZED_HEADERS if attribName is CONS.HEADER_SEARCH_KEYWORDS val = @mapSearchKeywords rawMaster, attribName, @header.toLanguageIndex() else val = @mapLocalizedAttrib rawMaster, attribName, @header.toLanguageIndex() product[attribName] = val if val unless product.slug product.slug = {} if product.name? and product.name[GLOBALS.DEFAULT_LANGUAGE]? product.slug[GLOBALS.DEFAULT_LANGUAGE] = @ensureValidSlug(_.slugify product.name[GLOBALS.DEFAULT_LANGUAGE], rowIndex) product ensureValidSlug: (slug, rowIndex, appendix = '') -> unless _.isString(slug) and slug.length > 2 @errors.push "[row #{rowIndex}:#{CONS.HEADER_SLUG}] Can't generate valid slug out of '#{slug}'! If you did not provide slug in your file, please do so as slug could not be auto-generated from the product name given." return @slugs or= [] currentSlug = "#{slug}#{appendix}" unless _.contains(@slugs, currentSlug) @slugs.push currentSlug return currentSlug @ensureValidSlug slug, rowIndex, Math.floor((Math.random() * 89999) + 10001) # five digets hasValidValueForHeader: (row, headerName) -> return false unless @header.has(headerName) @isValidValue(row[@header.toIndex headerName]) isValidValue: (rawValue) -> return _.isString(rawValue) and rawValue.length > 0 mapCategories: (rawMaster, rowIndex) -> categories = [] return categories unless @hasValidValueForHeader(rawMaster, CONS.HEADER_CATEGORIES) rawCategories = rawMaster[@header.toIndex CONS.HEADER_CATEGORIES].split GLOBALS.DELIM_MULTI_VALUE for rawCategory in rawCategories cat = typeId: 'category' if _.has(@categories.externalId2id, rawCategory) cat.id = @categories.externalId2id[rawCategory] else if _.has(@categories.fqName2id, rawCategory) cat.id = @categories.fqName2id[rawCategory] else if _.has(@categories.name2id, rawCategory) if _.contains(@categories.duplicateNames, rawCategory) msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORIES}] The category '#{rawCategory}' is not unqiue!" if @continueOnProblems console.warn msg else @errors.push msg else cat.id = @categories.name2id[rawCategory] if cat.id categories.push cat else msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORIES}] Can not find category for '#{rawCategory}'!" if @continueOnProblems console.warn msg else @errors.push msg categories # parses the categoryOrderHints column for a given row mapCategoryOrderHints: (rawMaster, rowIndex) -> catOrderHints = {} # check if there actually is something to parse in the column return catOrderHints unless @hasValidValueForHeader(rawMaster, CONS.HEADER_CATEGORY_ORDER_HINTS) # parse the value to get a list of all catOrderHints rawCatOrderHints = rawMaster[@header.toIndex CONS.HEADER_CATEGORY_ORDER_HINTS].split GLOBALS.DELIM_MULTI_VALUE _.each rawCatOrderHints, (rawCatOrderHint) => # extract the category id and the order hint from the raw value [rawCatId, rawOrderHint] = rawCatOrderHint.split ':' orderHint = parseFloat(rawOrderHint) # check if the product is actually assigned to the category catId = if _.has(@categories.id2fqName, rawCatId) rawCatId else if _.has(@categories.externalId2id, rawCatId) @categories.externalId2id[rawCatId] # in case the category was provided as the category name # check if the product is actually assigend to the category else if _.has(@categories.name2id, rawCatId) # get the actual category id instead of the category name @categories.name2id[rawCatId] # in case the category was provided using the category slug else if _.contains(@categories.id2slug, rawCatId) # get the actual category id instead of the category name _.findKey @categories.id2slug, (slug) -> slug == rawCatId else msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Can not find category for ID '#{rawCatId}'!" if @continueOnProblems console.warn msg else @errors.push msg null if orderHint == NaN msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Order hint has to be a valid number!" if @continueOnProblems console.warn msg else @errors.push msg else if !(orderHint > 0 && orderHint < 1) msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Order hint has to be < 1 and > 0 but was '#{orderHint}'!" if @continueOnProblems console.warn msg else @errors.push msg else if catId # orderHint and catId are ensured to be valid catOrderHints[catId] = orderHint.toString() catOrderHints mapTaxCategory: (rawMaster, rowIndex) -> return unless @hasValidValueForHeader(rawMaster, CONS.HEADER_TAX) rawTax = rawMaster[@header.toIndex CONS.HEADER_TAX] if _.contains(@taxes.duplicateNames, rawTax) @errors.push "[row #{rowIndex}:#{CONS.HEADER_TAX}] The tax category '#{rawTax}' is not unqiue!" return unless _.has(@taxes.name2id, rawTax) @errors.push "[row #{rowIndex}:#{CONS.HEADER_TAX}] The tax category '#{rawTax}' is unknown!" return tax = typeId: 'tax-category' id: @taxes.name2id[rawTax] mapState: (rawMaster, rowIndex) -> return unless @hasValidValueForHeader(rawMaster, CONS.HEADER_STATE) rawState = rawMaster[@header.toIndex CONS.HEADER_STATE] if _.contains(@states.duplicateKeys, rawState) @errors.push "[row #{rowIndex}:#{CONS.HEADER_STATE}] The state '#{rawState}' is not unqiue!" return unless _.has(@states.key2id, rawState) @errors.push "[row #{rowIndex}:#{CONS.HEADER_STATE}] The state '#{rawState}' is unknown!" return state = typeId: 'state' id: @states.key2id[rawState] mapVariant: (rawVariant, variantId, productType, rowIndex, product) -> if variantId > 2 and @header.has(CONS.HEADER_VARIANT_ID) vId = @mapInteger rawVariant[@header.toIndex CONS.HEADER_VARIANT_ID], CONS.HEADER_VARIANT_ID, rowIndex if vId? and not _.isNaN vId variantId = vId else # we have no valid variant id - mapInteger already mentioned this as error return variant = id: variantId attributes: [] if @header.has(CONS.HEADER_VARIANT_KEY) variant.key = rawVariant[@header.toIndex CONS.HEADER_VARIANT_KEY] variant.sku = rawVariant[@header.toIndex CONS.HEADER_SKU] if @header.has CONS.HEADER_SKU languageHeader2Index = @header._productTypeLanguageIndexes productType if productType.attributes for attribute in productType.attributes attrib = if attribute.attributeConstraint is CONS.ATTRIBUTE_CONSTRAINT_SAME_FOR_ALL and variantId > 1 _.find product.masterVariant.attributes, (a) -> a.name is attribute.name else @mapAttribute rawVariant, attribute, languageHeader2Index, rowIndex variant.attributes.push attrib if attrib variant.prices = @mapPrices rawVariant[@header.toIndex CONS.HEADER_PRICES], rowIndex variant.images = @mapImages rawVariant, variantId, rowIndex variant mapAttribute: (rawVariant, attribute, languageHeader2Index, rowIndex) -> # if attribute conflicts with some base product property prefix it with "attribute." string prefixedAttributeName = if attribute.name in CONS.PRODUCT_LEVEL_PROPERTIES.concat(CONS.ALL_HEADERS) "attribute.#{attribute.name}" else attribute.name value = @mapValue rawVariant, prefixedAttributeName, attribute, languageHeader2Index, rowIndex return undefined if _.isUndefined(value) or (_.isObject(value) and _.isEmpty(value)) or (_.isString(value) and _.isEmpty(value)) attribute = name: attribute.name value: value attribute mapValue: (rawVariant, attributeName, attribute, languageHeader2Index, rowIndex) -> switch attribute.type.name when CONS.ATTRIBUTE_TYPE_SET then @mapSetAttribute rawVariant, attributeName, attribute.type.elementType, languageHeader2Index, rowIndex when CONS.ATTRIBUTE_TYPE_LTEXT then @mapLocalizedAttrib rawVariant, attributeName, languageHeader2Index when CONS.ATTRIBUTE_TYPE_NUMBER then @mapNumber rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_BOOLEAN then @mapBoolean rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_MONEY then @mapMoney rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_REFERENCE then @mapReference rawVariant[@header.toIndex attributeName], attribute.type when CONS.ATTRIBUTE_TYPE_ENUM then @mapEnumAttribute rawVariant[@header.toIndex attributeName], attribute.type.values when CONS.ATTRIBUTE_TYPE_LENUM then @mapEnumAttribute rawVariant[@header.toIndex attributeName], attribute.type.values else rawVariant[@header.toIndex attributeName] # works for text mapEnumAttribute: (enumKey, enumValues) -> if enumKey _.find enumValues, (value) -> value.key is enumKey mapSetAttribute: (rawVariant, attributeName, elementType, languageHeader2Index, rowIndex) -> if elementType.name is CONS.ATTRIBUTE_TYPE_LTEXT multiValObj = @mapLocalizedAttrib rawVariant, attributeName, languageHeader2Index value = [] _.each multiValObj, (raw, lang) => if @isValidValue(raw) languageVals = raw.split GLOBALS.DELIM_MULTI_VALUE _.each languageVals, (v, index) -> localized = {} localized[lang] = v value[index] = _.extend (value[index] or {}), localized value else raw = rawVariant[@header.toIndex attributeName] if @isValidValue(raw) rawValues = raw.split GLOBALS.DELIM_MULTI_VALUE _.map rawValues, (rawValue) => switch elementType.name when CONS.ATTRIBUTE_TYPE_MONEY @mapMoney rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_NUMBER @mapNumber rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_BOOLEAN @mapBoolean rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_ENUM @mapEnumAttribute rawValue, elementType.values when CONS.ATTRIBUTE_TYPE_LENUM @mapEnumAttribute rawValue, elementType.values when CONS.ATTRIBUTE_TYPE_REFERENCE @mapReference rawValue, elementType else rawValue mapPrices: (raw, rowIndex) -> prices = [] return prices unless @isValidValue(raw) rawPrices = raw.split GLOBALS.DELIM_MULTI_VALUE for rawPrice in rawPrices matchedPrice = CONS.REGEX_PRICE.exec rawPrice unless matchedPrice @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not parse price '#{rawPrice}'!" continue country = matchedPrice[2] currencyCode = matchedPrice[3] centAmount = matchedPrice[4] customerGroupName = matchedPrice[8] channelKey = matchedPrice[10] validFrom = matchedPrice[12] validUntil = matchedPrice[14] price = value: @mapMoney "#{currencyCode} #{centAmount}", CONS.HEADER_PRICES, rowIndex price.validFrom = validFrom if validFrom price.validUntil = validUntil if validUntil price.country = country if country if customerGroupName unless _.has(@customerGroups.name2id, customerGroupName) @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not find customer group '#{customerGroupName}'!" return [] price.customerGroup = typeId: 'customer-group' id: @customerGroups.name2id[customerGroupName] if channelKey unless _.has(@channels.key2id, channelKey) @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not find channel with key '#{channelKey}'!" return [] price.channel = typeId: 'channel' id: @channels.key2id[channelKey] prices.push price prices # EUR 300 # USD 999 mapMoney: (rawMoney, attribName, rowIndex) -> return unless @isValidValue(rawMoney) matchedMoney = CONS.REGEX_MONEY.exec rawMoney unless matchedMoney @errors.push "[row #{rowIndex}:#{attribName}] Can not parse money '#{rawMoney}'!" return # TODO: check for correct currencyCode money = currencyCode: matchedMoney[1] centAmount: parseInt matchedMoney[2] mapReference: (rawReference, attributeType) -> return undefined unless rawReference ref = id: rawReference typeId: attributeType.referenceTypeId mapInteger: (rawNumber, attribName, rowIndex) -> parseInt @mapNumber(rawNumber, attribName, rowIndex, CONS.REGEX_INTEGER) mapNumber: (rawNumber, attribName, rowIndex, regEx = CONS.REGEX_FLOAT) -> return unless @isValidValue(rawNumber) matchedNumber = regEx.exec rawNumber unless matchedNumber @errors.push "[row #{rowIndex}:#{attribName}] The number '#{rawNumber}' isn't valid!" return parseFloat matchedNumber[0] mapBoolean: (rawBoolean, attribName, rowIndex) -> if _.isUndefined(rawBoolean) or (_.isString(rawBoolean) and _.isEmpty(rawBoolean)) return errorMsg = "[row #{rowIndex}:#{attribName}] The value '#{rawBoolean}' isn't a valid boolean!" try b = JSON.parse(rawBoolean.toLowerCase()) if _.isBoolean(b) or b == 0 or b == 1 return Boolean(b) else @errors.push errorMsg return catch @errors.push errorMsg # "a.en,a.de,a.it" # "hi,<NAME>,<NAME>" # values: # de: '<NAME>' # en: 'hi' # it: 'ciao' mapLocalizedAttrib: (row, attribName, langH2i) -> values = {} if _.has langH2i, attribName _.each langH2i[attribName], (index, language) -> val = row[index] values[language] = val if val # fall back to non localized column if language columns could not be found if _.size(values) is 0 return unless @header.has(attribName) val = row[@header.toIndex attribName] values[GLOBALS.DEFAULT_LANGUAGE] = val if val return if _.isEmpty values values # "a.en,a.de,a.it" # "hi,<NAME>,<NAME>" # values: # de: '<NAME>' # en: 'hi' # it: 'ciao' mapSearchKeywords: (row, attribName, langH2i) -> values = {} if _.has langH2i, attribName _.each langH2i[attribName], (index, language) -> val = row[index] if not _.isString(val) || val == "" return singleValues = val.split GLOBALS.DELIM_MULTI_VALUE texts = [] _.each singleValues, (v, index) -> texts.push { text: v} values[language] = texts # fall back to non localized column if language columns could not be found if _.size(values) is 0 return unless @header.has(attribName) val = row[@header.toIndex attribName] values[GLOBALS.DEFAULT_LANGUAGE].text = val if val return if _.isEmpty values values mapImages: (rawVariant, variantId, rowIndex) -> images = [] return images unless @hasValidValueForHeader(rawVariant, CONS.HEADER_IMAGES) rawImages = rawVariant[@header.toIndex CONS.HEADER_IMAGES].split GLOBALS.DELIM_MULTI_VALUE for rawImage in rawImages image = url: rawImage # TODO: get dimensions from CSV - format idea: 200x400;90x90 dimensions: w: 0 h: 0 # label: 'TODO' images.push image images module.exports = Mapping
true
_ = require 'underscore' _.mixin require('underscore.string').exports() CONS = require './constants' GLOBALS = require './globals' # TODO: # - JSDoc # - no services!!! # - utils only class Mapping constructor: (options = {}) -> @types = options.types @customerGroups = options.customerGroups @categories = options.categories @taxes = options.taxes @states = options.states @channels = options.channels @continueOnProblems = options.continueOnProblems @errors = [] mapProduct: (raw, productType) -> productType or= raw.master[@header.toIndex CONS.HEADER_PRODUCT_TYPE] rowIndex = raw.startRow product = @mapBaseProduct raw.master, productType, rowIndex product.masterVariant = @mapVariant raw.master, 1, productType, rowIndex, product _.each raw.variants, (entry, index) => product.variants.push @mapVariant entry.variant, index + 2, productType, entry.rowIndex, product data = product: product rowIndex: raw.startRow header: @header publish: raw.publish data mapBaseProduct: (rawMaster, productType, rowIndex) -> product = productType: typeId: 'product-type' id: productType.id masterVariant: {} variants: [] if @header.has(CONS.HEADER_ID) product.id = rawMaster[@header.toIndex CONS.HEADER_ID] if @header.has(CONS.HEADER_KEY) product.key = rawMaster[@header.toIndex CONS.HEADER_KEY] if @header.has(CONS.HEADER_META_TITLE) product.metaTitle = rawMaster[@header.toIndex CONS.HEADER_META_TITLE] or {} if @header.has(CONS.HEADER_META_DESCRIPTION) product.metaDescription = rawMaster[@header.toIndex CONS.HEADER_META_DESCRIPTION] or {} if @header.has(CONS.HEADER_META_KEYWORDS) product.metaKeywords = rawMaster[@header.toIndex CONS.HEADER_META_KEYWORDS] or {} if @header.has(CONS.HEADER_SEARCH_KEYWORDS) product.searchKeywords = rawMaster[@header.toIndex CONS.HEADER_SEARCH_KEYWORDS] or {} product.categories = @mapCategories rawMaster, rowIndex tax = @mapTaxCategory rawMaster, rowIndex product.taxCategory = tax if tax state = @mapState rawMaster, rowIndex product.state = state if state product.categoryOrderHints = @mapCategoryOrderHints rawMaster, rowIndex for attribName in CONS.BASE_LOCALIZED_HEADERS if attribName is CONS.HEADER_SEARCH_KEYWORDS val = @mapSearchKeywords rawMaster, attribName, @header.toLanguageIndex() else val = @mapLocalizedAttrib rawMaster, attribName, @header.toLanguageIndex() product[attribName] = val if val unless product.slug product.slug = {} if product.name? and product.name[GLOBALS.DEFAULT_LANGUAGE]? product.slug[GLOBALS.DEFAULT_LANGUAGE] = @ensureValidSlug(_.slugify product.name[GLOBALS.DEFAULT_LANGUAGE], rowIndex) product ensureValidSlug: (slug, rowIndex, appendix = '') -> unless _.isString(slug) and slug.length > 2 @errors.push "[row #{rowIndex}:#{CONS.HEADER_SLUG}] Can't generate valid slug out of '#{slug}'! If you did not provide slug in your file, please do so as slug could not be auto-generated from the product name given." return @slugs or= [] currentSlug = "#{slug}#{appendix}" unless _.contains(@slugs, currentSlug) @slugs.push currentSlug return currentSlug @ensureValidSlug slug, rowIndex, Math.floor((Math.random() * 89999) + 10001) # five digets hasValidValueForHeader: (row, headerName) -> return false unless @header.has(headerName) @isValidValue(row[@header.toIndex headerName]) isValidValue: (rawValue) -> return _.isString(rawValue) and rawValue.length > 0 mapCategories: (rawMaster, rowIndex) -> categories = [] return categories unless @hasValidValueForHeader(rawMaster, CONS.HEADER_CATEGORIES) rawCategories = rawMaster[@header.toIndex CONS.HEADER_CATEGORIES].split GLOBALS.DELIM_MULTI_VALUE for rawCategory in rawCategories cat = typeId: 'category' if _.has(@categories.externalId2id, rawCategory) cat.id = @categories.externalId2id[rawCategory] else if _.has(@categories.fqName2id, rawCategory) cat.id = @categories.fqName2id[rawCategory] else if _.has(@categories.name2id, rawCategory) if _.contains(@categories.duplicateNames, rawCategory) msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORIES}] The category '#{rawCategory}' is not unqiue!" if @continueOnProblems console.warn msg else @errors.push msg else cat.id = @categories.name2id[rawCategory] if cat.id categories.push cat else msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORIES}] Can not find category for '#{rawCategory}'!" if @continueOnProblems console.warn msg else @errors.push msg categories # parses the categoryOrderHints column for a given row mapCategoryOrderHints: (rawMaster, rowIndex) -> catOrderHints = {} # check if there actually is something to parse in the column return catOrderHints unless @hasValidValueForHeader(rawMaster, CONS.HEADER_CATEGORY_ORDER_HINTS) # parse the value to get a list of all catOrderHints rawCatOrderHints = rawMaster[@header.toIndex CONS.HEADER_CATEGORY_ORDER_HINTS].split GLOBALS.DELIM_MULTI_VALUE _.each rawCatOrderHints, (rawCatOrderHint) => # extract the category id and the order hint from the raw value [rawCatId, rawOrderHint] = rawCatOrderHint.split ':' orderHint = parseFloat(rawOrderHint) # check if the product is actually assigned to the category catId = if _.has(@categories.id2fqName, rawCatId) rawCatId else if _.has(@categories.externalId2id, rawCatId) @categories.externalId2id[rawCatId] # in case the category was provided as the category name # check if the product is actually assigend to the category else if _.has(@categories.name2id, rawCatId) # get the actual category id instead of the category name @categories.name2id[rawCatId] # in case the category was provided using the category slug else if _.contains(@categories.id2slug, rawCatId) # get the actual category id instead of the category name _.findKey @categories.id2slug, (slug) -> slug == rawCatId else msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Can not find category for ID '#{rawCatId}'!" if @continueOnProblems console.warn msg else @errors.push msg null if orderHint == NaN msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Order hint has to be a valid number!" if @continueOnProblems console.warn msg else @errors.push msg else if !(orderHint > 0 && orderHint < 1) msg = "[row #{rowIndex}:#{CONS.HEADER_CATEGORY_ORDER_HINTS}] Order hint has to be < 1 and > 0 but was '#{orderHint}'!" if @continueOnProblems console.warn msg else @errors.push msg else if catId # orderHint and catId are ensured to be valid catOrderHints[catId] = orderHint.toString() catOrderHints mapTaxCategory: (rawMaster, rowIndex) -> return unless @hasValidValueForHeader(rawMaster, CONS.HEADER_TAX) rawTax = rawMaster[@header.toIndex CONS.HEADER_TAX] if _.contains(@taxes.duplicateNames, rawTax) @errors.push "[row #{rowIndex}:#{CONS.HEADER_TAX}] The tax category '#{rawTax}' is not unqiue!" return unless _.has(@taxes.name2id, rawTax) @errors.push "[row #{rowIndex}:#{CONS.HEADER_TAX}] The tax category '#{rawTax}' is unknown!" return tax = typeId: 'tax-category' id: @taxes.name2id[rawTax] mapState: (rawMaster, rowIndex) -> return unless @hasValidValueForHeader(rawMaster, CONS.HEADER_STATE) rawState = rawMaster[@header.toIndex CONS.HEADER_STATE] if _.contains(@states.duplicateKeys, rawState) @errors.push "[row #{rowIndex}:#{CONS.HEADER_STATE}] The state '#{rawState}' is not unqiue!" return unless _.has(@states.key2id, rawState) @errors.push "[row #{rowIndex}:#{CONS.HEADER_STATE}] The state '#{rawState}' is unknown!" return state = typeId: 'state' id: @states.key2id[rawState] mapVariant: (rawVariant, variantId, productType, rowIndex, product) -> if variantId > 2 and @header.has(CONS.HEADER_VARIANT_ID) vId = @mapInteger rawVariant[@header.toIndex CONS.HEADER_VARIANT_ID], CONS.HEADER_VARIANT_ID, rowIndex if vId? and not _.isNaN vId variantId = vId else # we have no valid variant id - mapInteger already mentioned this as error return variant = id: variantId attributes: [] if @header.has(CONS.HEADER_VARIANT_KEY) variant.key = rawVariant[@header.toIndex CONS.HEADER_VARIANT_KEY] variant.sku = rawVariant[@header.toIndex CONS.HEADER_SKU] if @header.has CONS.HEADER_SKU languageHeader2Index = @header._productTypeLanguageIndexes productType if productType.attributes for attribute in productType.attributes attrib = if attribute.attributeConstraint is CONS.ATTRIBUTE_CONSTRAINT_SAME_FOR_ALL and variantId > 1 _.find product.masterVariant.attributes, (a) -> a.name is attribute.name else @mapAttribute rawVariant, attribute, languageHeader2Index, rowIndex variant.attributes.push attrib if attrib variant.prices = @mapPrices rawVariant[@header.toIndex CONS.HEADER_PRICES], rowIndex variant.images = @mapImages rawVariant, variantId, rowIndex variant mapAttribute: (rawVariant, attribute, languageHeader2Index, rowIndex) -> # if attribute conflicts with some base product property prefix it with "attribute." string prefixedAttributeName = if attribute.name in CONS.PRODUCT_LEVEL_PROPERTIES.concat(CONS.ALL_HEADERS) "attribute.#{attribute.name}" else attribute.name value = @mapValue rawVariant, prefixedAttributeName, attribute, languageHeader2Index, rowIndex return undefined if _.isUndefined(value) or (_.isObject(value) and _.isEmpty(value)) or (_.isString(value) and _.isEmpty(value)) attribute = name: attribute.name value: value attribute mapValue: (rawVariant, attributeName, attribute, languageHeader2Index, rowIndex) -> switch attribute.type.name when CONS.ATTRIBUTE_TYPE_SET then @mapSetAttribute rawVariant, attributeName, attribute.type.elementType, languageHeader2Index, rowIndex when CONS.ATTRIBUTE_TYPE_LTEXT then @mapLocalizedAttrib rawVariant, attributeName, languageHeader2Index when CONS.ATTRIBUTE_TYPE_NUMBER then @mapNumber rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_BOOLEAN then @mapBoolean rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_MONEY then @mapMoney rawVariant[@header.toIndex attributeName], attribute.name, rowIndex when CONS.ATTRIBUTE_TYPE_REFERENCE then @mapReference rawVariant[@header.toIndex attributeName], attribute.type when CONS.ATTRIBUTE_TYPE_ENUM then @mapEnumAttribute rawVariant[@header.toIndex attributeName], attribute.type.values when CONS.ATTRIBUTE_TYPE_LENUM then @mapEnumAttribute rawVariant[@header.toIndex attributeName], attribute.type.values else rawVariant[@header.toIndex attributeName] # works for text mapEnumAttribute: (enumKey, enumValues) -> if enumKey _.find enumValues, (value) -> value.key is enumKey mapSetAttribute: (rawVariant, attributeName, elementType, languageHeader2Index, rowIndex) -> if elementType.name is CONS.ATTRIBUTE_TYPE_LTEXT multiValObj = @mapLocalizedAttrib rawVariant, attributeName, languageHeader2Index value = [] _.each multiValObj, (raw, lang) => if @isValidValue(raw) languageVals = raw.split GLOBALS.DELIM_MULTI_VALUE _.each languageVals, (v, index) -> localized = {} localized[lang] = v value[index] = _.extend (value[index] or {}), localized value else raw = rawVariant[@header.toIndex attributeName] if @isValidValue(raw) rawValues = raw.split GLOBALS.DELIM_MULTI_VALUE _.map rawValues, (rawValue) => switch elementType.name when CONS.ATTRIBUTE_TYPE_MONEY @mapMoney rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_NUMBER @mapNumber rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_BOOLEAN @mapBoolean rawValue, attributeName, rowIndex when CONS.ATTRIBUTE_TYPE_ENUM @mapEnumAttribute rawValue, elementType.values when CONS.ATTRIBUTE_TYPE_LENUM @mapEnumAttribute rawValue, elementType.values when CONS.ATTRIBUTE_TYPE_REFERENCE @mapReference rawValue, elementType else rawValue mapPrices: (raw, rowIndex) -> prices = [] return prices unless @isValidValue(raw) rawPrices = raw.split GLOBALS.DELIM_MULTI_VALUE for rawPrice in rawPrices matchedPrice = CONS.REGEX_PRICE.exec rawPrice unless matchedPrice @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not parse price '#{rawPrice}'!" continue country = matchedPrice[2] currencyCode = matchedPrice[3] centAmount = matchedPrice[4] customerGroupName = matchedPrice[8] channelKey = matchedPrice[10] validFrom = matchedPrice[12] validUntil = matchedPrice[14] price = value: @mapMoney "#{currencyCode} #{centAmount}", CONS.HEADER_PRICES, rowIndex price.validFrom = validFrom if validFrom price.validUntil = validUntil if validUntil price.country = country if country if customerGroupName unless _.has(@customerGroups.name2id, customerGroupName) @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not find customer group '#{customerGroupName}'!" return [] price.customerGroup = typeId: 'customer-group' id: @customerGroups.name2id[customerGroupName] if channelKey unless _.has(@channels.key2id, channelKey) @errors.push "[row #{rowIndex}:#{CONS.HEADER_PRICES}] Can not find channel with key '#{channelKey}'!" return [] price.channel = typeId: 'channel' id: @channels.key2id[channelKey] prices.push price prices # EUR 300 # USD 999 mapMoney: (rawMoney, attribName, rowIndex) -> return unless @isValidValue(rawMoney) matchedMoney = CONS.REGEX_MONEY.exec rawMoney unless matchedMoney @errors.push "[row #{rowIndex}:#{attribName}] Can not parse money '#{rawMoney}'!" return # TODO: check for correct currencyCode money = currencyCode: matchedMoney[1] centAmount: parseInt matchedMoney[2] mapReference: (rawReference, attributeType) -> return undefined unless rawReference ref = id: rawReference typeId: attributeType.referenceTypeId mapInteger: (rawNumber, attribName, rowIndex) -> parseInt @mapNumber(rawNumber, attribName, rowIndex, CONS.REGEX_INTEGER) mapNumber: (rawNumber, attribName, rowIndex, regEx = CONS.REGEX_FLOAT) -> return unless @isValidValue(rawNumber) matchedNumber = regEx.exec rawNumber unless matchedNumber @errors.push "[row #{rowIndex}:#{attribName}] The number '#{rawNumber}' isn't valid!" return parseFloat matchedNumber[0] mapBoolean: (rawBoolean, attribName, rowIndex) -> if _.isUndefined(rawBoolean) or (_.isString(rawBoolean) and _.isEmpty(rawBoolean)) return errorMsg = "[row #{rowIndex}:#{attribName}] The value '#{rawBoolean}' isn't a valid boolean!" try b = JSON.parse(rawBoolean.toLowerCase()) if _.isBoolean(b) or b == 0 or b == 1 return Boolean(b) else @errors.push errorMsg return catch @errors.push errorMsg # "a.en,a.de,a.it" # "hi,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI" # values: # de: 'PI:NAME:<NAME>END_PI' # en: 'hi' # it: 'ciao' mapLocalizedAttrib: (row, attribName, langH2i) -> values = {} if _.has langH2i, attribName _.each langH2i[attribName], (index, language) -> val = row[index] values[language] = val if val # fall back to non localized column if language columns could not be found if _.size(values) is 0 return unless @header.has(attribName) val = row[@header.toIndex attribName] values[GLOBALS.DEFAULT_LANGUAGE] = val if val return if _.isEmpty values values # "a.en,a.de,a.it" # "hi,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI" # values: # de: 'PI:NAME:<NAME>END_PI' # en: 'hi' # it: 'ciao' mapSearchKeywords: (row, attribName, langH2i) -> values = {} if _.has langH2i, attribName _.each langH2i[attribName], (index, language) -> val = row[index] if not _.isString(val) || val == "" return singleValues = val.split GLOBALS.DELIM_MULTI_VALUE texts = [] _.each singleValues, (v, index) -> texts.push { text: v} values[language] = texts # fall back to non localized column if language columns could not be found if _.size(values) is 0 return unless @header.has(attribName) val = row[@header.toIndex attribName] values[GLOBALS.DEFAULT_LANGUAGE].text = val if val return if _.isEmpty values values mapImages: (rawVariant, variantId, rowIndex) -> images = [] return images unless @hasValidValueForHeader(rawVariant, CONS.HEADER_IMAGES) rawImages = rawVariant[@header.toIndex CONS.HEADER_IMAGES].split GLOBALS.DELIM_MULTI_VALUE for rawImage in rawImages image = url: rawImage # TODO: get dimensions from CSV - format idea: 200x400;90x90 dimensions: w: 0 h: 0 # label: 'TODO' images.push image images module.exports = Mapping
[ { "context": "#\n# batman.js\n#\n# Created by Nick Small\n# Copyright 2011, Shopify\n#\n\n# The global namespa", "end": 39, "score": 0.999626874923706, "start": 29, "tag": "NAME", "value": "Nick Small" }, { "context": "n.Hash::hashKeyFor(@base)}, key: \\\"#{Batman.Hash::hashKeyFor(@key)}\\\">\"\n\n addHandler: (handler) ->\n ", "end": 13400, "score": 0.513894259929657, "start": 13396, "tag": "KEY", "value": "hash" }, { "context": "y\n hashKey: ->\n @hashKey = -> key\n key = \"<Batman.Property base: #{Batman.Hash::hashKeyFor(@base)},", "end": 17222, "score": 0.7187252044677734, "start": 17216, "tag": "KEY", "value": "Batman" }, { "context": "Key = -> key\n key = \"<Batman.Property base: #{Batman.Hash::hashKeyFor(@base)}, key: \\\"#{Batman.Hash::h", "end": 17246, "score": 0.863603413105011, "start": 17241, "tag": "KEY", "value": "atman" }, { "context": "-> key\n key = \"<Batman.Property base: #{Batman.Hash::hashKeyFor(@base)}, key: \\\"#{Batman.Hash::hashKeyFor(@key)}\\", "end": 17263, "score": 0.8906537890434265, "start": 17247, "tag": "KEY", "value": "Hash::hashKeyFor" }, { "context": "y base: #{Batman.Hash::hashKeyFor(@base)}, key: \\\"#{Batman.Hash::hashKeyFor(@key)}\\\">\"\n\n changeEvent: ->\n event = @event('change')\n ", "end": 17316, "score": 0.8880119919776917, "start": 17280, "tag": "KEY", "value": "#{Batman.Hash::hashKeyFor(@key)}\\\">\"" }, { "context": " super\n @primaryKey = @options.primaryKey or \"id\"\n @foreignKey = @options.foreignKey or \"#{help", "end": 104729, "score": 0.6331667900085449, "start": 104727, "tag": "KEY", "value": "id" }, { "context": " or \"#{helpers.underscore($functionName(@model))}_id\"\n\n apply: (baseSaveError, base) ->\n unless ba", "end": 104820, "score": 0.5984191298484802, "start": 104818, "tag": "KEY", "value": "id" }, { "context": "options ||= {}\n env = {options}\n if key == 'readAll'\n env.proto = recordOrProto\n else\n e", "end": 112270, "score": 0.9796947240829468, "start": 112263, "tag": "KEY", "value": "readAll" }, { "context": "e: (key, value) =>\n return unless key\n key = helpers.camelize(key.trim(), true)\n @oldStyles[key] = @node.sty", "end": 164926, "score": 0.8836968541145325, "start": 164910, "tag": "KEY", "value": "helpers.camelize" }, { "context": " return unless key\n key = helpers.camelize(key.trim(), true)\n @oldStyles[key] = @node.style[key]\n @node", "end": 164943, "score": 0.8435057997703552, "start": 164931, "tag": "KEY", "value": "trim(), true" } ]
data/coffeescript/0569016f3e1a9ec6aeace62190287183_batman.coffee
maxim5/code-inspector
5
# # batman.js # # Created by Nick Small # Copyright 2011, Shopify # # The global namespace, the `Batman` function will also create also create a new # instance of Batman.Object and mixin all arguments to it. Batman = (mixins...) -> new Batman.Object mixins... Batman.version = '0.8.0' Batman.config = pathPrefix: '/' usePushState: no Batman.container = if exports? module.exports = Batman global else window.Batman = Batman window # Global Helpers # ------- # `$typeOf` returns a string that contains the built-in class of an object # like `String`, `Array`, or `Object`. Note that only `Object` will be returned for # the entire prototype chain. Batman.typeOf = $typeOf = (object) -> return "Undefined" if typeof object == 'undefined' _objectToString.call(object).slice(8, -1) # Cache this function to skip property lookups. _objectToString = Object.prototype.toString # `$mixin` applies every key from every argument after the first to the # first argument. If a mixin has an `initialize` method, it will be called in # the context of the `to` object, and it's key/values won't be applied. Batman.mixin = $mixin = (to, mixins...) -> hasSet = typeof to.set is 'function' for mixin in mixins continue if $typeOf(mixin) isnt 'Object' for own key, value of mixin continue if key in ['initialize', 'uninitialize', 'prototype'] if hasSet to.set(key, value) else if to.nodeName? Batman.data to, key, value else to[key] = value if typeof mixin.initialize is 'function' mixin.initialize.call to to # `$unmixin` removes every key/value from every argument after the first # from the first argument. If a mixin has a `deinitialize` method, it will be # called in the context of the `from` object and won't be removed. Batman.unmixin = $unmixin = (from, mixins...) -> for mixin in mixins for key of mixin continue if key in ['initialize', 'uninitialize'] delete from[key] if typeof mixin.uninitialize is 'function' mixin.uninitialize.call from from # `$functionName` returns the name of a given function, if any # Used to deal with functions not having the `name` property in IE Batman._functionName = $functionName = (f) -> return f.__name__ if f.__name__ return f.name if f.name f.toString().match(/\W*function\s+([\w\$]+)\(/)?[1] # `$preventDefault` checks for preventDefault, since it's not # always available across all browsers Batman._preventDefault = $preventDefault = (e) -> if typeof e.preventDefault is "function" then e.preventDefault() else e.returnValue = false Batman._isChildOf = $isChildOf = (parentNode, childNode) -> node = childNode.parentNode while node return true if node == parentNode node = node.parentNode false $setImmediate = $clearImmediate = null _implementImmediates = (container) -> canUsePostMessage = -> return false unless container.postMessage async = true oldMessage = container.onmessage container.onmessage = -> async = false container.postMessage("","*") container.onmessage = oldMessage async tasks = new Batman.SimpleHash count = 0 getHandle = -> "go#{++count}" if container.setImmediate $setImmediate = container.setImmediate $clearImmediate = container.clearImmediate else if container.msSetImmediate $setImmediate = msSetImmediate $clearImmediate = msClearImmediate else if canUsePostMessage() prefix = 'com.batman.' functions = new Batman.SimpleHash handler = (e) -> return unless ~e.data.search(prefix) handle = e.data.substring(prefix.length) tasks.unset(handle)?() if container.addEventListener container.addEventListener('message', handler, false) else container.attachEvent('onmessage', handler) $setImmediate = (f) -> tasks.set(handle = getHandle(), f) container.postMessage(prefix+handle, "*") handle $clearImmediate = (handle) -> tasks.unset(handle) else if typeof document isnt 'undefined' && "onreadystatechange" in document.createElement("script") $setImmediate = (f) -> handle = getHandle() script = document.createElement("script") script.onreadystatechange = -> tasks.get(handle)?() script.onreadystatechange = null script.parentNode.removeChild(script) script = null document.documentElement.appendChild(script) handle $clearImmediate = (handle) -> tasks.unset(handle) else $setImmediate = (f) -> setTimeout(f, 0) $clearImmediate = (handle) -> clearTimeout(handle) Batman.setImmediate = $setImmediate Batman.clearImmediate = $clearImmediate Batman.setImmediate = $setImmediate = -> _implementImmediates(Batman.container) Batman.setImmediate.apply(@, arguments) Batman.clearImmediate = $clearImmediate = -> _implementImmediates(Batman.container) Batman.clearImmediate.apply(@, arguments) Batman.forEach = $forEach = (container, iterator, ctx) -> if container.forEach container.forEach(iterator, ctx) else if container.indexOf iterator.call(ctx, e, i, container) for e,i in container else iterator.call(ctx, k, v, container) for k,v of container Batman.objectHasKey = $objectHasKey = (object, key) -> if typeof object.hasKey is 'function' object.hasKey(key) else key of object Batman.contains = $contains = (container, item) -> if container.indexOf item in container else if typeof container.has is 'function' container.has(item) else $objectHasKey(container, item) Batman.get = $get = (base, key) -> if typeof base.get is 'function' base.get(key) else Batman.Property.forBaseAndKey(base, key).getValue() Batman.escapeHTML = $escapeHTML = do -> replacements = "&": "&amp;" "<": "&lt;" ">": "&gt;" "\"": "&#34;" "'": "&#39;" return (s) -> (""+s).replace(/[&<>'"]/g, (c) -> replacements[c]) # `translate` is hook for the i18n extra to override and implemnent. All strings which might # be shown to the user pass through this method. `translate` is aliased to `t` internally. Batman.translate = (x, values = {}) -> helpers.interpolate($get(Batman.translate.messages, x), values) Batman.translate.messages = {} t = -> Batman.translate(arguments...) # Developer Tooling # ----------------- Batman.developer = suppressed: false DevelopmentError: (-> DevelopmentError = (@message) -> @name = "DevelopmentError" DevelopmentError:: = Error:: DevelopmentError )() _ie_console: (f, args) -> console?[f] "...#{f} of #{args.length} items..." unless args.length == 1 console?[f] arg for arg in args suppress: (f) -> developer.suppressed = true if f f() developer.suppressed = false unsuppress: -> developer.suppressed = false log: -> return if developer.suppressed or !(console?.log?) if console.log.apply then console.log(arguments...) else developer._ie_console "log", arguments warn: -> return if developer.suppressed or !(console?.warn?) if console.warn.apply then console.warn(arguments...) else developer._ie_console "warn", arguments error: (message) -> throw new developer.DevelopmentError(message) assert: (result, message) -> developer.error(message) unless result do: (f) -> f() unless developer.suppressed addFilters: -> $mixin Batman.Filters, log: (value, key) -> console?.log? arguments value logStack: (value) -> console?.log? developer.currentFilterStack value developer = Batman.developer developer.assert (->).bind, "Error! Batman needs Function.bind to work! Please shim it using something like es5-shim or augmentjs!" # Helpers # ------- # Just a few random Rails-style string helpers. You can add more # to the Batman.helpers object. class Batman.Inflector plural: [] singular: [] uncountable: [] @plural: (regex, replacement) -> @::plural.unshift [regex, replacement] @singular: (regex, replacement) -> @::singular.unshift [regex, replacement] @irregular: (singular, plural) -> if singular.charAt(0) == plural.charAt(0) @plural new RegExp("(#{singular.charAt(0)})#{singular.slice(1)}$", "i"), "$1" + plural.slice(1) @plural new RegExp("(#{singular.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + plural.slice(1) @singular new RegExp("(#{plural.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + singular.slice(1) else @plural new RegExp("#{singular}$", 'i'), plural @plural new RegExp("#{plural}$", 'i'), plural @singular new RegExp("#{plural}$", 'i'), singular @uncountable: (strings...) -> @::uncountable = @::uncountable.concat(strings.map((x) -> new RegExp("#{x}$", 'i'))) @plural(/$/, 's') @plural(/s$/i, 's') @plural(/(ax|test)is$/i, '$1es') @plural(/(octop|vir)us$/i, '$1i') @plural(/(octop|vir)i$/i, '$1i') @plural(/(alias|status)$/i, '$1es') @plural(/(bu)s$/i, '$1ses') @plural(/(buffal|tomat)o$/i, '$1oes') @plural(/([ti])um$/i, '$1a') @plural(/([ti])a$/i, '$1a') @plural(/sis$/i, 'ses') @plural(/(?:([^f])fe|([lr])f)$/i, '$1$2ves') @plural(/(hive)$/i, '$1s') @plural(/([^aeiouy]|qu)y$/i, '$1ies') @plural(/(x|ch|ss|sh)$/i, '$1es') @plural(/(matr|vert|ind)(?:ix|ex)$/i, '$1ices') @plural(/([m|l])ouse$/i, '$1ice') @plural(/([m|l])ice$/i, '$1ice') @plural(/^(ox)$/i, '$1en') @plural(/^(oxen)$/i, '$1') @plural(/(quiz)$/i, '$1zes') @singular(/s$/i, '') @singular(/(n)ews$/i, '$1ews') @singular(/([ti])a$/i, '$1um') @singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '$1$2sis') @singular(/(^analy)ses$/i, '$1sis') @singular(/([^f])ves$/i, '$1fe') @singular(/(hive)s$/i, '$1') @singular(/(tive)s$/i, '$1') @singular(/([lr])ves$/i, '$1f') @singular(/([^aeiouy]|qu)ies$/i, '$1y') @singular(/(s)eries$/i, '$1eries') @singular(/(m)ovies$/i, '$1ovie') @singular(/(x|ch|ss|sh)es$/i, '$1') @singular(/([m|l])ice$/i, '$1ouse') @singular(/(bus)es$/i, '$1') @singular(/(o)es$/i, '$1') @singular(/(shoe)s$/i, '$1') @singular(/(cris|ax|test)es$/i, '$1is') @singular(/(octop|vir)i$/i, '$1us') @singular(/(alias|status)es$/i, '$1') @singular(/^(ox)en/i, '$1') @singular(/(vert|ind)ices$/i, '$1ex') @singular(/(matr)ices$/i, '$1ix') @singular(/(quiz)zes$/i, '$1') @singular(/(database)s$/i, '$1') @irregular('person', 'people') @irregular('man', 'men') @irregular('child', 'children') @irregular('sex', 'sexes') @irregular('move', 'moves') @irregular('cow', 'kine') @irregular('zombie', 'zombies') @uncountable('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans') ordinalize: (number) -> absNumber = Math.abs(parseInt(number)) if absNumber % 100 in [11..13] number + "th" else switch absNumber % 10 when 1 number + "st" when 2 number + "nd" when 3 number + "rd" else number + "th" pluralize: (word) -> for uncountableRegex in @uncountable return word if uncountableRegex.test(word) for [regex, replace_string] in @plural return word.replace(regex, replace_string) if regex.test(word) word singularize: (word) -> for uncountableRegex in @uncountable return word if uncountableRegex.test(word) for [regex, replace_string] in @singular return word.replace(regex, replace_string) if regex.test(word) word camelize_rx = /(?:^|_|\-)(.)/g capitalize_rx = /(^|\s)([a-z])/g underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g underscore_rx2 = /([a-z\d])([A-Z])/g helpers = Batman.helpers = inflector: new Batman.Inflector ordinalize: -> helpers.inflector.ordinalize.apply helpers.inflector, arguments singularize: -> helpers.inflector.singularize.apply helpers.inflector, arguments pluralize: (count, singular, plural) -> if arguments.length < 2 helpers.inflector.pluralize count else "#{count || 0} " + if +count is 1 then singular else (plural || helpers.inflector.pluralize(singular)) camelize: (string, firstLetterLower) -> string = string.replace camelize_rx, (str, p1) -> p1.toUpperCase() if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string underscore: (string) -> string.replace(underscore_rx1, '$1_$2') .replace(underscore_rx2, '$1_$2') .replace('-', '_').toLowerCase() capitalize: (string) -> string.replace capitalize_rx, (m,p1,p2) -> p1 + p2.toUpperCase() trim: (string) -> if string then string.trim() else "" interpolate: (stringOrObject, keys) -> if typeof stringOrObject is 'object' string = stringOrObject[keys.count] unless string string = stringOrObject['other'] else string = stringOrObject for key, value of keys string = string.replace(new RegExp("%\\{#{key}\\}", "g"), value) string class Batman.Event @forBaseAndKey: (base, key) -> if base.isEventEmitter base.event(key) else new Batman.Event(base, key) constructor: (@base, @key) -> @handlers = new Batman.SimpleSet @_preventCount = 0 isEvent: true isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key hashKey: -> @hashKey = -> key key = "<Batman.Event base: #{Batman.Hash::hashKeyFor(@base)}, key: \"#{Batman.Hash::hashKeyFor(@key)}\">" addHandler: (handler) -> @handlers.add(handler) @autofireHandler(handler) if @oneShot this removeHandler: (handler) -> @handlers.remove(handler) this eachHandler: (iterator) -> @handlers.forEach(iterator) if @base?.isEventEmitter key = @key @base._batman.ancestors (ancestor) -> if ancestor.isEventEmitter and ancestor.hasEvent(key) handlers = ancestor.event(key).handlers handlers.forEach(iterator) handlerContext: -> @base prevent: -> ++@_preventCount allow: -> --@_preventCount if @_preventCount @_preventCount isPrevented: -> @_preventCount > 0 autofireHandler: (handler) -> if @_oneShotFired and @_oneShotArgs? handler.apply(@handlerContext(), @_oneShotArgs) resetOneShot: -> @_oneShotFired = false @_oneShotArgs = null fire: -> return false if @isPrevented() or @_oneShotFired context = @handlerContext() args = arguments if @oneShot @_oneShotFired = true @_oneShotArgs = arguments @eachHandler (handler) -> handler.apply(context, args) allowAndFire: -> @allow() @fire(arguments...) Batman.EventEmitter = isEventEmitter: true hasEvent: (key) -> @_batman?.get?('events')?.hasKey(key) event: (key) -> Batman.initializeObject @ eventClass = @eventClass or Batman.Event events = @_batman.events ||= new Batman.SimpleHash if events.hasKey(key) existingEvent = events.get(key) else existingEvents = @_batman.get('events') newEvent = events.set(key, new eventClass(this, key)) newEvent.oneShot = existingEvents?.get(key)?.oneShot newEvent on: (key, handler) -> @event(key).addHandler(handler) registerAsMutableSource: -> Batman.Property.registerSource(@) mutation: (wrappedFunction) -> -> result = wrappedFunction.apply(this, arguments) @event('change').fire(this, this) result prevent: (key) -> @event(key).prevent() @ allow: (key) -> @event(key).allow() @ isPrevented: (key) -> @event(key).isPrevented() fire: (key, args...) -> @event(key).fire(args...) allowAndFire: (key, args...) -> @event(key).allowAndFire(args...) class Batman.PropertyEvent extends Batman.Event eachHandler: (iterator) -> @base.eachObserver(iterator) handlerContext: -> @base.base class Batman.Property $mixin @prototype, Batman.EventEmitter @_sourceTrackerStack: [] @sourceTracker: -> (stack = @_sourceTrackerStack)[stack.length - 1] @defaultAccessor: get: (key) -> @[key] set: (key, val) -> @[key] = val unset: (key) -> x = @[key]; delete @[key]; x cachable: no @forBaseAndKey: (base, key) -> if base.isObservable base.property(key) else new Batman.Keypath(base, key) @withoutTracking: (block) -> @pushDummySourceTracker() try block() finally @popSourceTracker() @registerSource: (obj) -> return unless obj.isEventEmitter @sourceTracker()?.add(obj) @pushSourceTracker: -> Batman.Property._sourceTrackerStack.push(new Batman.SimpleSet) @pushDummySourceTracker: -> Batman.Property._sourceTrackerStack.push(null) @popSourceTracker: -> Batman.Property._sourceTrackerStack.pop() constructor: (@base, @key) -> developer.do => keyType = $typeOf(@key) if keyType in ['Array', 'Object'] developer.log "Accessing a property with an #{keyType} key. This is okay, but could be a source of memory leaks if you aren't careful." _isolationCount: 0 cached: no value: null sources: null isProperty: true isDead: false eventClass: Batman.PropertyEvent isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key hashKey: -> @hashKey = -> key key = "<Batman.Property base: #{Batman.Hash::hashKeyFor(@base)}, key: \"#{Batman.Hash::hashKeyFor(@key)}\">" changeEvent: -> event = @event('change') @changeEvent = -> event event accessor: -> keyAccessors = @base._batman?.get('keyAccessors') accessor = if keyAccessors && (val = keyAccessors.get(@key)) val else @base._batman?.getFirst('defaultAccessor') or Batman.Property.defaultAccessor @accessor = -> accessor accessor eachObserver: (iterator) -> key = @key @changeEvent().handlers.forEach(iterator) if @base.isObservable @base._batman.ancestors (ancestor) -> if ancestor.isObservable and ancestor.hasProperty(key) property = ancestor.property(key) handlers = property.changeEvent().handlers handlers.forEach(iterator) observers: -> results = [] @eachObserver (observer) -> results.push(observer) results hasObservers: -> @observers().length > 0 updateSourcesFromTracker: -> newSources = @constructor.popSourceTracker() handler = @sourceChangeHandler() @_eachSourceChangeEvent (e) -> e.removeHandler(handler) @sources = newSources @_eachSourceChangeEvent (e) -> e.addHandler(handler) _eachSourceChangeEvent: (iterator) -> return unless @sources? @sources.forEach (source) -> iterator(source.event('change')) getValue: -> @registerAsMutableSource() unless @isCached() @constructor.pushSourceTracker() try @value = @valueFromAccessor() @cached = yes finally @updateSourcesFromTracker() @value isCachable: -> return true if @isFinal() cachable = @accessor().cachable if cachable? then !!cachable else true isCached: -> @isCachable() and @cached isFinal: -> !!@accessor()['final'] refresh: -> @cached = no previousValue = @value value = @getValue() if value isnt previousValue and not @isIsolated() @fire(value, previousValue) @lockValue() if @value isnt undefined and @isFinal() sourceChangeHandler: -> handler = => @_handleSourceChange() @sourceChangeHandler = -> handler handler _handleSourceChange: -> if @isIsolated() @_needsRefresh = yes else if not @isFinal() && not @hasObservers() @cached = no else @refresh() valueFromAccessor: -> @accessor().get?.call(@base, @key) setValue: (val) -> return unless set = @accessor().set @_changeValue -> set.call(@base, @key, val) unsetValue: -> return unless unset = @accessor().unset @_changeValue -> unset.call(@base, @key) _changeValue: (block) -> @cached = no @constructor.pushDummySourceTracker() try result = block.apply(this) @refresh() finally @constructor.popSourceTracker() @die() unless @isCached() or @hasObservers() result forget: (handler) -> if handler? @changeEvent().removeHandler(handler) else @changeEvent().handlers.clear() observeAndFire: (handler) -> @observe(handler) handler.call(@base, @value, @value) observe: (handler) -> @changeEvent().addHandler(handler) @getValue() unless @sources? this _removeHandlers: -> handler = @sourceChangeHandler() @_eachSourceChangeEvent (e) -> e.removeHandler(handler) delete @sources @changeEvent().handlers.clear() lockValue: -> @_removeHandlers() @getValue = -> @value @setValue = @unsetValue = @refresh = @observe = -> die: -> @_removeHandlers() @base._batman?.properties?.unset(@key) @isDead = true fire: -> @changeEvent().fire(arguments...) isolate: -> if @_isolationCount is 0 @_preIsolationValue = @getValue() @_isolationCount++ expose: -> if @_isolationCount is 1 @_isolationCount-- if @_needsRefresh @value = @_preIsolationValue @refresh() else if @value isnt @_preIsolationValue @fire(@value, @_preIsolationValue) @_preIsolationValue = null else if @_isolationCount > 0 @_isolationCount-- isIsolated: -> @_isolationCount > 0 # Keypaths # -------- class Batman.Keypath extends Batman.Property constructor: (base, key) -> if $typeOf(key) is 'String' @segments = key.split('.') @depth = @segments.length else @segments = [key] @depth = 1 super slice: (begin, end=@depth) -> base = @base for segment in @segments.slice(0, begin) return unless base? and base = $get(base, segment) propertyClass = base.propertyClass or Batman.Keypath remainingSegments = @segments.slice(begin, end) remainingPath = remainingSegments.join('.') if propertyClass is Batman.Keypath or remainingSegments.length is 1 Batman.Keypath.forBaseAndKey(base, remainingPath) else new Batman.Keypath(base, remainingPath) terminalProperty: -> @slice -1 valueFromAccessor: -> if @depth is 1 then super else @terminalProperty()?.getValue() setValue: (val) -> if @depth is 1 then super else @terminalProperty()?.setValue(val) unsetValue: -> if @depth is 1 then super else @terminalProperty()?.unsetValue() # Observable # ---------- # Batman.Observable is a generic mixin that can be applied to any object to allow it to be bound to. # It is applied by default to every instance of `Batman.Object` and subclasses. Batman.Observable = isObservable: true hasProperty: (key) -> @_batman?.properties?.hasKey?(key) property: (key) -> Batman.initializeObject @ propertyClass = @propertyClass or Batman.Keypath properties = @_batman.properties ||= new Batman.SimpleHash properties.get(key) or properties.set(key, new propertyClass(this, key)) get: (key) -> @property(key).getValue() set: (key, val) -> @property(key).setValue(val) unset: (key) -> @property(key).unsetValue() getOrSet: (key, valueFunction) -> currentValue = @get(key) unless currentValue currentValue = valueFunction() @set(key, currentValue) currentValue # `forget` removes an observer from an object. If the callback is passed in, # its removed. If no callback but a key is passed in, all the observers on # that key are removed. If no key is passed in, all observers are removed. forget: (key, observer) -> if key @property(key).forget(observer) else @_batman.properties?.forEach (key, property) -> property.forget() @ # `fire` tells any observers attached to a key to fire, manually. # `prevent` stops of a given binding from firing. `prevent` calls can be repeated such that # the same number of calls to allow are needed before observers can be fired. # `allow` unblocks a property for firing observers. Every call to prevent # must have a matching call to allow later if observers are to be fired. # `observe` takes a key and a callback. Whenever the value for that key changes, your # callback will be called in the context of the original object. observe: (key, args...) -> @property(key).observe(args...) @ observeAndFire: (key, args...) -> @property(key).observeAndFire(args...) @ # Objects # ------- # `Batman.initializeObject` is called by all the methods in Batman.Object to ensure that the # object's `_batman` property is initialized and it's own. Classes extending Batman.Object inherit # methods like `get`, `set`, and `observe` by default on the class and prototype levels, such that # both instances and the class respond to them and can be bound to. However, CoffeeScript's static # class inheritance copies over all class level properties indiscriminately, so a parent class' # `_batman` object will get copied to its subclasses, transferring all the information stored there and # allowing subclasses to mutate parent state. This method prevents this undesirable behaviour by tracking # which object the `_batman_` object was initialized upon, and reinitializing if that has changed since # initialization. Batman.initializeObject = (object) -> if object._batman? object._batman.check(object) else object._batman = new _Batman(object) # _Batman provides a convienient, parent class and prototype aware place to store hidden # object state. Things like observers, accessors, and states belong in the `_batman` object # attached to every Batman.Object subclass and subclass instance. Batman._Batman = class _Batman constructor: (@object, mixins...) -> $mixin(@, mixins...) if mixins.length > 0 # Used by `Batman.initializeObject` to ensure that this `_batman` was created referencing # the object it is pointing to. check: (object) -> if object != @object object._batman = new _Batman(object) return false return true # `get` is a prototype and class aware property access method. `get` will traverse the prototype chain, asking # for the passed key at each step, and then attempting to merge the results into one object. # It can only do this if at each level an `Array`, `Hash`, or `Set` is found, so try to use # those if you need `_batman` inhertiance. get: (key) -> # Get all the keys from the ancestor chain results = @getAll(key) switch results.length when 0 undefined when 1 results[0] else # And then try to merge them if there is more than one. Use `concat` on arrays, and `merge` on # sets and hashes. if results[0].concat? results = results.reduceRight (a, b) -> a.concat(b) else if results[0].merge? results = results.reduceRight (a, b) -> a.merge(b) results # `getFirst` is a prototype and class aware property access method. `getFirst` traverses the prototype chain, # and returns the value of the first `_batman` object which defines the passed key. Useful for # times when the merged value doesn't make sense or the value is a primitive. getFirst: (key) -> results = @getAll(key) results[0] # `getAll` is a prototype and class chain iterator. When passed a key or function, it applies it to each # parent class or parent prototype, and returns the undefined values, closest ancestor first. getAll: (keyOrGetter) -> # Get a function which pulls out the key from the ancestor's `_batman` or use the passed function. if typeof keyOrGetter is 'function' getter = keyOrGetter else getter = (ancestor) -> ancestor._batman?[keyOrGetter] # Apply it to all the ancestors, and then this `_batman`'s object. results = @ancestors(getter) if val = getter(@object) results.unshift val results # `ancestors` traverses the prototype or class chain and returns the application of a function to each # object in the chain. `ancestors` does this _only_ to the `@object`'s ancestors, and not the `@object` # itsself. ancestors: (getter = (x) -> x) -> results = [] # Decide if the object is a class or not, and pull out the first ancestor isClass = !!@object.prototype parent = if isClass @object.__super__?.constructor else if (proto = Object.getPrototypeOf(@object)) == @object @object.constructor.__super__ else proto if parent? parent._batman?.check(parent) # Apply the function and store the result if it isn't undefined. val = getter(parent) results.push(val) if val? # Use a recursive call to `_batman.ancestors` on the ancestor, which will take the next step up the chain. if parent._batman? results = results.concat(parent._batman.ancestors(getter)) results set: (key, value) -> @[key] = value # `Batman.Object` is the base class for all other Batman objects. It is not abstract. class BatmanObject extends Object Batman.initializeObject(this) Batman.initializeObject(@prototype) # Setting `isGlobal` to true will cause the class name to be defined on the # global object. For example, Batman.Model will be aliased to window.Model. # This should be used sparingly; it's mostly useful for debugging. @global: (isGlobal) -> return if isGlobal is false Batman.container[$functionName(@)] = @ # Apply mixins to this class. @classMixin: -> $mixin @, arguments... # Apply mixins to instances of this class. @mixin: -> @classMixin.apply @prototype, arguments mixin: @classMixin counter = 0 _objectID: -> @_objectID = -> c c = counter++ hashKey: -> return if typeof @isEqual is 'function' @hashKey = -> key key = "<Batman.Object #{@_objectID()}>" toJSON: -> obj = {} for own key, value of @ when key not in ["_batman", "hashKey", "_objectID"] obj[key] = if value?.toJSON then value.toJSON() else value obj # Accessor implementation. Accessors are used to create properties on a class or prototype which can be fetched # with get, but are computed instead of just stored. This is a batman and old browser friendly version of # `defineProperty` without as much goodness. # # Accessors track which other properties they rely on for computation, and when those other properties change, # an accessor will recalculate its value and notifiy its observers. This way, when a source value is changed, # any dependent accessors will automatically update any bindings to them with a new value. Accessors accomplish # this feat by tracking `get` calls, do be sure to use `get` to retrieve properties inside accessors. # # `@accessor` or `@classAccessor` can be called with zero, one, or many keys to attach the accessor to. This # has the following effects: # # * zero: create a `defaultAccessor`, which will be called when no other properties or accessors on an object # match a keypath. This is similar to `method_missing` in Ruby or `#doesNotUnderstand` in Smalltalk. # * one: create a `keyAccessor` at the given key, which will only be called when that key is `get`ed. # * many: create `keyAccessors` for each given key, which will then be called whenever each key is `get`ed. # # Note: This function gets called in all sorts of different contexts by various # other pointers to it, but it acts the same way on `this` in all cases. getAccessorObject = (accessor) -> accessor = {get: accessor} if !accessor.get && !accessor.set && !accessor.unset accessor @classAccessor: (keys..., accessor) -> Batman.initializeObject @ # Create a default accessor if no keys have been given. if keys.length is 0 # The `accessor` argument is wrapped in `getAccessorObject` which allows functions to be passed in # as a shortcut to {get: function} @_batman.defaultAccessor = getAccessorObject(accessor) else # Otherwise, add key accessors for each key given. @_batman.keyAccessors ||= new Batman.SimpleHash @_batman.keyAccessors.set(key, getAccessorObject(accessor)) for key in keys # Support adding accessors to the prototype from within class defintions or after the class has been created # with `KlassExtendingBatmanObject.accessor(keys..., accessorObject)` @accessor: -> @classAccessor.apply @prototype, arguments # Support adding accessors to instances after creation accessor: @classAccessor constructor: (mixins...) -> @_batman = new _Batman(@) @mixin mixins... # Make every subclass and their instances observable. @classMixin Batman.EventEmitter, Batman.Observable @mixin Batman.EventEmitter, Batman.Observable # Observe this property on every instance of this class. @observeAll: -> @::observe.apply @prototype, arguments @singleton: (singletonMethodName="sharedInstance") -> @classAccessor singletonMethodName, get: -> @["_#{singletonMethodName}"] ||= new @ Batman.Object = BatmanObject class Batman.Accessible extends Batman.Object constructor: -> @accessor.apply(@, arguments) class Batman.TerminalAccessible extends Batman.Accessible propertyClass: Batman.Property # Collections Batman.Enumerable = isEnumerable: true map: (f, ctx = Batman.container) -> r = []; @forEach(-> r.push f.apply(ctx, arguments)); r mapToProperty: (key) -> r = []; @forEach((item) -> r.push item.get(key)); r every: (f, ctx = Batman.container) -> r = true; @forEach(-> r = r && f.apply(ctx, arguments)); r some: (f, ctx = Batman.container) -> r = false; @forEach(-> r = r || f.apply(ctx, arguments)); r reduce: (f, r) -> count = 0 self = @ @forEach -> if r? then r = f(r, arguments..., count, self) else r = arguments[0] r filter: (f) -> r = new @constructor if r.add wrap = (r, e) -> r.add(e) if f(e); r else if r.set wrap = (r, k, v) -> r.set(k, v) if f(k, v); r else r = [] unless r.push wrap = (r, e) -> r.push(e) if f(e); r @reduce wrap, r # Provide this simple mixin ability so that during bootstrapping we don't have to use `$mixin`. `$mixin` # will correctly attempt to use `set` on the mixinee, which ends up requiring the definition of # `SimpleSet` to be complete during its definition. $extendsEnumerable = (onto) -> onto[k] = v for k,v of Batman.Enumerable class Batman.SimpleHash constructor: (obj) -> @_storage = {} @length = 0 @update(obj) if obj? $extendsEnumerable(@::) propertyClass: Batman.Property hasKey: (key) -> if pairs = @_storage[@hashKeyFor(key)] for pair in pairs return true if @equality(pair[0], key) return false get: (key) -> if pairs = @_storage[@hashKeyFor(key)] for pair in pairs return pair[1] if @equality(pair[0], key) set: (key, val) -> pairs = @_storage[@hashKeyFor(key)] ||= [] for pair in pairs if @equality(pair[0], key) return pair[1] = val @length++ pairs.push([key, val]) val unset: (key) -> hashKey = @hashKeyFor(key) if pairs = @_storage[hashKey] for [obj,value], index in pairs if @equality(obj, key) pair = pairs.splice(index,1) delete @_storage[hashKey] unless pairs.length @length-- return pair[0][1] getOrSet: Batman.Observable.getOrSet hashKeyFor: (obj) -> obj?.hashKey?() or obj equality: (lhs, rhs) -> return true if lhs is rhs return true if lhs isnt lhs and rhs isnt rhs # when both are NaN return true if lhs?.isEqual?(rhs) and rhs?.isEqual?(lhs) return false forEach: (iterator, ctx) -> for key, values of @_storage iterator.call(ctx, obj, value, this) for [obj, value] in values.slice() keys: -> result = [] # Explicitly reference this foreach so that if it's overriden in subclasses the new implementation isn't used. Batman.SimpleHash::forEach.call @, (key) -> result.push key result clear: -> @_storage = {} @length = 0 isEmpty: -> @length is 0 merge: (others...) -> merged = new @constructor others.unshift(@) for hash in others hash.forEach (obj, value) -> merged.set obj, value merged update: (object) -> @set(k,v) for k,v of object replace: (object) -> @forEach (key, value) => @unset(key) unless key of object @update(object) toObject: -> obj = {} for key, pair of @_storage obj[key] = pair[0][1] # the first value for this key obj toJSON: @::toObject class Batman.Hash extends Batman.Object class @Metadata extends Batman.Object constructor: (@hash) -> @accessor 'length', -> @hash.registerAsMutableSource() @hash.length @accessor 'isEmpty', -> @hash.isEmpty() @accessor 'keys', -> @hash.keys() constructor: -> @meta = new @constructor.Metadata(this) Batman.SimpleHash.apply(@, arguments) super $extendsEnumerable(@::) propertyClass: Batman.Property @accessor get: Batman.SimpleHash::get set: @mutation (key, value) -> result = Batman.SimpleHash::set.call(@, key, value) @fire 'itemsWereAdded', key result unset: @mutation (key) -> result = Batman.SimpleHash::unset.call(@, key) @fire 'itemsWereRemoved', key if result? result cachable: false _preventMutationEvents: (block) -> @prevent 'change' @prevent 'itemsWereAdded' @prevent 'itemsWereRemoved' try block.call(this) finally @allow 'change' @allow 'itemsWereAdded' @allow 'itemsWereRemoved' clear: @mutation -> keys = @keys() @_preventMutationEvents -> @forEach (k) => @unset(k) result = Batman.SimpleHash::clear.call(@) @fire 'itemsWereRemoved', keys... result update: @mutation (object) -> addedKeys = [] @_preventMutationEvents -> Batman.forEach object, (k,v) => addedKeys.push(k) unless @hasKey(k) @set(k,v) @fire('itemsWereAdded', addedKeys...) if addedKeys.length > 0 replace: @mutation (object) -> addedKeys = [] removedKeys = [] @_preventMutationEvents -> @forEach (k, _) => unless Batman.objectHasKey(object, k) @unset(k) removedKeys.push(k) Batman.forEach object, (k,v) => addedKeys.push(k) unless @hasKey(k) @set(k,v) @fire('itemsWereAdded', addedKeys...) if addedKeys.length > 0 @fire('itemsWereRemoved', removedKeys...) if removedKeys.length > 0 equality: Batman.SimpleHash::equality hashKeyFor: Batman.SimpleHash::hashKeyFor for k in ['hasKey', 'forEach', 'isEmpty', 'keys', 'merge', 'toJSON', 'toObject'] proto = @prototype do (k) -> proto[k] = -> @registerAsMutableSource() Batman.SimpleHash::[k].apply(@, arguments) class Batman.SimpleSet constructor: -> @_storage = new Batman.SimpleHash @_indexes = new Batman.SimpleHash @_uniqueIndexes = new Batman.SimpleHash @_sorts = new Batman.SimpleHash @length = 0 @add.apply @, arguments if arguments.length > 0 $extendsEnumerable(@::) has: (item) -> @_storage.hasKey item add: (items...) -> addedItems = [] for item in items when !@_storage.hasKey(item) @_storage.set item, true addedItems.push item @length++ if @fire and addedItems.length isnt 0 @fire('change', this, this) @fire('itemsWereAdded', addedItems...) addedItems remove: (items...) -> removedItems = [] for item in items when @_storage.hasKey(item) @_storage.unset item removedItems.push item @length-- if @fire and removedItems.length isnt 0 @fire('change', this, this) @fire('itemsWereRemoved', removedItems...) removedItems find: (f) -> ret = undefined @forEach (item) -> if ret is undefined && f(item) is true ret = item ret forEach: (iterator, ctx) -> container = this @_storage.forEach (key) -> iterator.call(ctx, key, null, container) isEmpty: -> @length is 0 clear: -> items = @toArray() @_storage = new Batman.SimpleHash @length = 0 if @fire and items.length isnt 0 @fire('change', this, this) @fire('itemsWereRemoved', items...) items replace: (other) -> try @prevent?('change') @clear() @add(other.toArray()...) finally @allowAndFire?('change', this, this) toArray: -> @_storage.keys() merge: (others...) -> merged = new @constructor others.unshift(@) for set in others set.forEach (v) -> merged.add v merged indexedBy: (key) -> @_indexes.get(key) or @_indexes.set(key, new Batman.SetIndex(@, key)) indexedByUnique: (key) -> @_uniqueIndexes.get(key) or @_uniqueIndexes.set(key, new Batman.UniqueSetIndex(@, key)) sortedBy: (key, order="asc") -> order = if order.toLowerCase() is "desc" then "desc" else "asc" sortsForKey = @_sorts.get(key) or @_sorts.set(key, new Batman.Object) sortsForKey.get(order) or sortsForKey.set(order, new Batman.SetSort(@, key, order)) class Batman.Set extends Batman.Object constructor: -> Batman.SimpleSet.apply @, arguments $extendsEnumerable(@::) for k in ['add', 'remove', 'find', 'clear', 'replace', 'indexedBy', 'indexedByUnique', 'sortedBy'] @::[k] = Batman.SimpleSet::[k] for k in ['merge', 'forEach', 'toArray', 'isEmpty', 'has'] proto = @prototype do (k) -> proto[k] = -> @registerAsMutableSource() Batman.SimpleSet::[k].apply(@, arguments) toJSON: @::toArray applySetAccessors = (klass) -> klass.accessor 'first', -> @toArray()[0] klass.accessor 'last', -> @toArray()[@length - 1] klass.accessor 'indexedBy', -> new Batman.TerminalAccessible (key) => @indexedBy(key) klass.accessor 'indexedByUnique', -> new Batman.TerminalAccessible (key) => @indexedByUnique(key) klass.accessor 'sortedBy', -> new Batman.TerminalAccessible (key) => @sortedBy(key) klass.accessor 'sortedByDescending', -> new Batman.TerminalAccessible (key) => @sortedBy(key, 'desc') klass.accessor 'isEmpty', -> @isEmpty() klass.accessor 'toArray', -> @toArray() klass.accessor 'length', -> @registerAsMutableSource() @length applySetAccessors(Batman.Set) class Batman.SetObserver extends Batman.Object constructor: (@base) -> @_itemObservers = new Batman.SimpleHash @_setObservers = new Batman.SimpleHash @_setObservers.set "itemsWereAdded", => @fire('itemsWereAdded', arguments...) @_setObservers.set "itemsWereRemoved", => @fire('itemsWereRemoved', arguments...) @on 'itemsWereAdded', @startObservingItems.bind(@) @on 'itemsWereRemoved', @stopObservingItems.bind(@) observedItemKeys: [] observerForItemAndKey: (item, key) -> _getOrSetObserverForItemAndKey: (item, key) -> @_itemObservers.getOrSet item, => observersByKey = new Batman.SimpleHash observersByKey.getOrSet key, => @observerForItemAndKey(item, key) startObserving: -> @_manageItemObservers("observe") @_manageSetObservers("addHandler") stopObserving: -> @_manageItemObservers("forget") @_manageSetObservers("removeHandler") startObservingItems: (items...) -> @_manageObserversForItem(item, "observe") for item in items stopObservingItems: (items...) -> @_manageObserversForItem(item, "forget") for item in items _manageObserversForItem: (item, method) -> return unless item.isObservable for key in @observedItemKeys item[method] key, @_getOrSetObserverForItemAndKey(item, key) @_itemObservers.unset(item) if method is "forget" _manageItemObservers: (method) -> @base.forEach (item) => @_manageObserversForItem(item, method) _manageSetObservers: (method) -> return unless @base.isObservable @_setObservers.forEach (key, observer) => @base.event(key)[method](observer) class Batman.SetProxy extends Batman.Object constructor: () -> super() @length = 0 @base.on 'itemsWereAdded', (items...) => @fire('itemsWereAdded', items...) @base.on 'itemsWereRemoved', (items...) => @fire('itemsWereRemoved', items...) $extendsEnumerable(@::) filter: (f) -> r = new Batman.Set() @reduce(((r, e) -> r.add(e) if f(e); r), r) for k in ['add', 'remove', 'find', 'clear', 'replace'] do (k) => @::[k] = -> results = @base[k](arguments...) @length = @set('length', @base.get 'length') results for k in ['has', 'merge', 'toArray', 'isEmpty', 'indexedBy', 'indexedByUnique', 'sortedBy'] do (k) => @::[k] = -> @base[k](arguments...) applySetAccessors(@) @accessor 'length', get: -> @registerAsMutableSource() @length set: (_, v) -> @length = v class Batman.SetSort extends Batman.SetProxy constructor: (@base, @key, order="asc") -> super() @descending = order.toLowerCase() is "desc" if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] boundReIndex = @_reIndex.bind(@) @_setObserver.observerForItemAndKey = -> boundReIndex @_setObserver.on 'itemsWereAdded', boundReIndex @_setObserver.on 'itemsWereRemoved', boundReIndex @startObserving() @_reIndex() startObserving: -> @_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() toArray: -> @get('_storage') forEach: (iterator, ctx) -> iterator.call(ctx,e,i,this) for e,i in @get('_storage') compare: (a,b) -> return 0 if a is b return 1 if a is undefined return -1 if b is undefined return 1 if a is null return -1 if b is null return 1 if a is false return -1 if b is false return 1 if a is true return -1 if b is true if a isnt a if b isnt b return 0 # both are NaN else return 1 # a is NaN return -1 if b isnt b # b is NaN return 1 if a > b return -1 if a < b return 0 _reIndex: -> newOrder = @base.toArray().sort (a,b) => valueA = $get(a, @key) valueA = valueA.valueOf() if valueA? valueB = $get(b, @key) valueB = valueB.valueOf() if valueB? multiple = if @descending then -1 else 1 @compare.call(@, valueA, valueB) * multiple @_setObserver?.startObservingItems(newOrder...) @set('_storage', newOrder) class Batman.SetIndex extends Batman.Object propertyClass: Batman.Property constructor: (@base, @key) -> super() @_storage = new Batman.SimpleHash if @base.isEventEmitter @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] @_setObserver.observerForItemAndKey = @observerForItemAndKey.bind(@) @_setObserver.on 'itemsWereAdded', (items...) => @_addItem(item) for item in items @_setObserver.on 'itemsWereRemoved', (items...) => @_removeItem(item) for item in items @base.forEach @_addItem.bind(@) @startObserving() @accessor (key) -> @_resultSetForKey(key) startObserving: ->@_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() observerForItemAndKey: (item, key) -> (newValue, oldValue) => @_removeItemFromKey(item, oldValue) @_addItemToKey(item, newValue) _addItem: (item) -> @_addItemToKey(item, @_keyForItem(item)) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item _removeItem: (item) -> @_removeItemFromKey(item, @_keyForItem(item)) _removeItemFromKey: (item, key) -> @_resultSetForKey(key).remove(item) _resultSetForKey: (key) -> @_storage.getOrSet(key, -> new Batman.Set) _keyForItem: (item) -> Batman.Keypath.forBaseAndKey(item, @key).getValue() class Batman.UniqueSetIndex extends Batman.SetIndex constructor: -> @_uniqueIndex = new Batman.Hash super @accessor (key) -> @_uniqueIndex.get(key) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item unless @_uniqueIndex.hasKey(key) @_uniqueIndex.set(key, item) _removeItemFromKey: (item, key) -> resultSet = @_resultSetForKey(key) super if resultSet.isEmpty() @_uniqueIndex.unset(key) else @_uniqueIndex.set(key, resultSet.toArray()[0]) class Batman.BinarySetOperation extends Batman.Set constructor: (@left, @right) -> super() @_setup @left, @right @_setup @right, @left _setup: (set, opposite) => set.on 'itemsWereAdded', (items...) => @_itemsWereAddedToSource(set, opposite, items...) set.on 'itemsWereRemoved', (items...) => @_itemsWereRemovedFromSource(set, opposite, items...) @_itemsWereAddedToSource set, opposite, set.toArray()... merge: (others...) -> merged = new Batman.Set others.unshift(@) for set in others set.forEach (v) -> merged.add v merged filter: Batman.SetProxy::filter class Batman.SetUnion extends Batman.BinarySetOperation _itemsWereAddedToSource: (source, opposite, items...) -> @add items... _itemsWereRemovedFromSource: (source, opposite, items...) -> itemsToRemove = (item for item in items when !opposite.has(item)) @remove itemsToRemove... class Batman.SetIntersection extends Batman.BinarySetOperation _itemsWereAddedToSource: (source, opposite, items...) -> itemsToAdd = (item for item in items when opposite.has(item)) @add itemsToAdd... _itemsWereRemovedFromSource: (source, opposite, items...) -> @remove items... # State Machines # -------------- Batman.StateMachine = { initialize: -> Batman.initializeObject @ if not @_batman.states @_batman.states = new Batman.SimpleHash state: (name, callback) -> Batman.StateMachine.initialize.call @ return @_batman.getFirst 'state' unless name developer.assert @isEventEmitter, "StateMachine requires EventEmitter" @[name] ||= (callback) -> _stateMachine_setState.call(@, name) @on(name, callback) if typeof callback is 'function' transition: (from, to, callback) -> Batman.StateMachine.initialize.call @ @state from @state to @on("#{from}->#{to}", callback) if callback } # A special method to alias state machine methods to class methods Batman.Object.actsAsStateMachine = (includeInstanceMethods=true) -> Batman.StateMachine.initialize.call @ Batman.StateMachine.initialize.call @prototype @classState = -> Batman.StateMachine.state.apply @, arguments @state = -> @classState.apply @prototype, arguments @::state = @classState if includeInstanceMethods @classTransition = -> Batman.StateMachine.transition.apply @, arguments @transition = -> @classTransition.apply @prototype, arguments @::transition = @classTransition if includeInstanceMethods # This is cached here so it doesn't need to be recompiled for every setter _stateMachine_setState = (newState) -> Batman.StateMachine.initialize.call @ if @_batman.isTransitioning (@_batman.nextState ||= []).push(newState) return false @_batman.isTransitioning = yes oldState = @state() @_batman.state = newState if newState and oldState @fire("#{oldState}->#{newState}", newState, oldState) if newState @fire(newState, newState, oldState) @_batman.isTransitioning = no @[@_batman.nextState.shift()]() if @_batman.nextState?.length newState # App, Requests, and Routing # -------------------------- # `Batman.Request` is a normalizer for XHR requests in the Batman world. class Batman.Request extends Batman.Object @objectToFormData: (data) -> pairForList = (key, object, first = false) -> list = switch Batman.typeOf(object) when 'Object' list = for k, v of object pairForList((if first then k else "#{key}[#{k}]"), v) list.reduce((acc, list) -> acc.concat list , []) when 'Array' object.reduce((acc, element) -> acc.concat pairForList("#{key}[]", element) , []) else [[key, object]] formData = new Batman.container.FormData() for [key, val] in pairForList("", data, true) formData.append(key, val) formData url: '' data: '' method: 'GET' formData: false response: null status: null headers: {} @accessor 'method', $mixin {}, Batman.Property.defaultAccessor, set: (k,val) -> @[k] = val?.toUpperCase?() # Set the content type explicitly for PUT and POST requests. contentType: 'application/x-www-form-urlencoded' constructor: (options) -> handlers = {} for k, handler of options when k in ['success', 'error', 'loading', 'loaded'] handlers[k] = handler delete options[k] super(options) @on k, handler for k, handler of handlers # After the URL gets set, we'll try to automatically send # your request after a short period. If this behavior is # not desired, use @cancel() after setting the URL. @observeAll 'url', (url) -> @_autosendTimeout = $setImmediate => @send() # `send` is implmented in the platform layer files. One of those must be required for # `Batman.Request` to be useful. send: -> developer.error "Please source a dependency file for a request implementation" cancel: -> $clearImmediate(@_autosendTimeout) if @_autosendTimeout ## Routes class Batman.Route extends Batman.Object # Route regexes courtesy of Backbone @regexps = namedParam: /:([\w\d]+)/g splatParam: /\*([\w\d]+)/g queryParam: '(?:\\?.+)?' namedOrSplat: /[:|\*]([\w\d]+)/g namePrefix: '[:|\*]' escapeRegExp: /[-[\]{}()+?.,\\^$|#\s]/g optionKeys: ['member', 'collection'] testKeys: ['controller', 'action'] isRoute: true constructor: (templatePath, baseParams) -> regexps = @constructor.regexps templatePath = "/#{templatePath}" if templatePath.indexOf('/') isnt 0 pattern = templatePath.replace(regexps.escapeRegExp, '\\$&') regexp = /// ^ #{pattern .replace(regexps.namedParam, '([^\/]+)') .replace(regexps.splatParam, '(.*?)') } #{regexps.queryParam} $ /// namedArguments = (matches[1] while matches = regexps.namedOrSplat.exec(pattern)) properties = {templatePath, pattern, regexp, namedArguments, baseParams} for k in @optionKeys properties[k] = baseParams[k] delete baseParams[k] super(properties) paramsFromPath: (path) -> [path, query] = path.split '?' namedArguments = @get('namedArguments') params = $mixin {path}, @get('baseParams') matches = @get('regexp').exec(path).slice(1) for match, index in matches name = namedArguments[index] params[name] = match if query for pair in query.split('&') [key, value] = pair.split '=' params[key] = value params pathFromParams: (argumentParams) -> params = $mixin {}, argumentParams path = @get('templatePath') # Replace the names in the template with their values from params for name in @get('namedArguments') regexp = ///#{@constructor.regexps.namePrefix}#{name}/// newPath = path.replace regexp, (if params[name]? then params[name] else '') if newPath != path delete params[name] path = newPath for key in @testKeys delete params[key] # Append the rest of the params as a query string queryParams = ("#{key}=#{value}" for key, value of params) if queryParams.length > 0 path += "?" + queryParams.join("&") path test: (pathOrParams) -> if typeof pathOrParams is 'string' path = pathOrParams else if pathOrParams.path? path = pathOrParams.path else path = @pathFromParams(pathOrParams) for key in @testKeys if (value = @get(key))? return false unless pathOrParams[key] == value @get('regexp').test(path) dispatch: (pathOrParams) -> return false unless @test(pathOrParams) if typeof pathOrParams is 'string' params = @paramsFromPath(pathOrParams) path = pathOrParams else params = pathOrParams path = @pathFromParams(pathOrParams) @get('callback')(params) return path callback: -> throw new Batman.DevelopmentError "Override callback in a Route subclass" class Batman.CallbackActionRoute extends Batman.Route optionKeys: ['member', 'collection', 'callback', 'app'] controller: false action: false class Batman.ControllerActionRoute extends Batman.Route optionKeys: ['member', 'collection', 'app', 'controller', 'action'] constructor: (templatePath, options) -> if options.signature [controller, action] = options.signature.split('#') action ||= 'index' options.controller = controller options.action = action delete options.signature super(templatePath, options) callback: (params) => controller = @get("app.dispatcher.controllers.#{@get('controller')}") controller.dispatch(@get('action'), params) class Batman.Dispatcher extends Batman.Object @canInferRoute: (argument) -> argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy || argument.prototype instanceof Batman.Model @paramsFromArgument: (argument) -> resourceNameFromModel = (model) -> helpers.underscore(helpers.pluralize($functionName(model))) return argument unless @canInferRoute(argument) if argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy argument = argument.get('target') if argument.isProxy if argument? { controller: resourceNameFromModel(argument.constructor) action: 'show' id: argument.get('id') } else {} else if argument.prototype instanceof Batman.Model { controller: resourceNameFromModel(argument) action: 'index' } else argument class ControllerDirectory extends Batman.Object @accessor '__app', Batman.Property.defaultAccessor @accessor (key) -> @get("__app.#{helpers.capitalize(key)}Controller.sharedController") @accessor 'controllers', -> new ControllerDirectory(__app: @get('app')) constructor: (app, routeMap) -> super({app, routeMap}) routeForParams: (params) -> params = @constructor.paramsFromArgument(params) @get('routeMap').routeForParams(params) pathFromParams: (params) -> return params if typeof params is 'string' params = @constructor.paramsFromArgument(params) @routeForParams(params)?.pathFromParams(params) dispatch: (params) -> inferredParams = @constructor.paramsFromArgument(params) route = @routeForParams(inferredParams) if route path = route.dispatch(inferredParams) else # No route matching the parameters was found, but an object which might be for # use with the params replacer has been passed. If its an object like a model # or a record we could have inferred a route for it (but didn't), so we make # sure that it isn't by running it through canInferRoute. if $typeOf(params) is 'Object' && !@constructor.canInferRoute(params) return @get('app.currentParams').replace(params) else @get('app.currentParams').clear() return Batman.redirect('/404') unless path is '/404' or params is '/404' @set 'app.currentURL', path @set 'app.currentRoute', route path class Batman.RouteMap memberRoute: null collectionRoute: null constructor: -> @childrenByOrder = [] @childrenByName = {} routeForParams: (params) -> for route in @childrenByOrder return route if route.test(params) return undefined addRoute: (name, route) -> @childrenByOrder.push(route) if name.length > 0 && (names = name.split('.')).length > 0 base = names.shift() unless @childrenByName[base] @childrenByName[base] = new Batman.RouteMap @childrenByName[base].addRoute(names.join('.'), route) else if route.get('member') developer.do => Batman.developer.error("Member route with name #{name} already exists!") if @memberRoute @memberRoute = route else developer.do => Batman.developer.error("Collection route with name #{name} already exists!") if @collectionRoute @collectionRoute = route true class Batman.NamedRouteQuery extends Batman.Object isNamedRouteQuery: true developer.do => class NonWarningProperty extends Batman.Keypath constructor: -> developer.suppress() super developer.unsuppress() @::propertyClass = NonWarningProperty constructor: (routeMap, args = []) -> super({routeMap, args}) @accessor 'route', -> {memberRoute, collectionRoute} = @get('routeMap') for route in [memberRoute, collectionRoute] when route? return route if route.namedArguments.length == @get('args').length return collectionRoute || memberRoute @accessor 'path', -> params = {} namedArguments = @get('route.namedArguments') for argumentName, index in namedArguments if (argumentValue = @get('args')[index])? params[argumentName] = @_toParam(argumentValue) @get('route').pathFromParams(params) @accessor 'routeMap', 'args', 'cardinality', Batman.Property.defaultAccessor @accessor get: (key) -> return if !key? if typeof key is 'string' @nextQueryForName(key) else @nextQueryWithArgument(key) set: -> cacheable: false nextQueryForName: (key) -> if map = @get('routeMap').childrenByName[key] return new Batman.NamedRouteQuery(map, @args) else Batman.developer.error "Couldn't find a route for the name #{key}!" nextQueryWithArgument: (arg) -> args = @args.slice(0) args.push arg @clone(args) _toParam: (arg) -> if arg instanceof Batman.AssociationProxy arg = arg.get('target') if arg.toParam isnt 'undefined' then arg.toParam() else arg _paramName: (arg) -> string = helpers.singularize($functionName(arg)) + "Id" string.charAt(0).toLowerCase() + string.slice(1) clone: (args = @args) -> new Batman.NamedRouteQuery(@routeMap, args) class Batman.RouteMapBuilder @BUILDER_FUNCTIONS = ['resources', 'member', 'collection', 'route', 'root'] @ROUTES = index: cardinality: 'collection' path: (resource) -> resource name: (resource) -> resource new: cardinality: 'collection' path: (resource) -> "#{resource}/new" name: (resource) -> "#{resource}.new" show: cardinality: 'member' path: (resource) -> "#{resource}/:id" name: (resource) -> resource edit: cardinality: 'member' path: (resource) -> "#{resource}/:id/edit" name: (resource) -> "#{resource}.edit" collection: cardinality: 'collection' path: (resource, name) -> "#{resource}/#{name}" name: (resource, name) -> "#{resource}.#{name}" member: cardinality: 'member' path: (resource, name) -> "#{resource}/:id/#{name}" name: (resource, name) -> "#{resource}.#{name}" constructor: (@app, @routeMap, @parent, @baseOptions = {}) -> if @parent @rootPath = @parent._nestingPath() @rootName = @parent._nestingName() else @rootPath = '' @rootName = '' resources: (args...) -> resourceNames = (arg for arg in args when typeof arg is 'string') callback = args.pop() if typeof args[args.length - 1] is 'function' if typeof args[args.length - 1] is 'object' options = args.pop() else options = {} actions = {index: true, new: true, show: true, edit: true} if options.except actions[k] = false for k in options.except delete options.except else if options.only actions[k] = false for k, v of actions actions[k] = true for k in options.only delete options.only for resourceName in resourceNames controller = resourceRoot = helpers.pluralize(resourceName) childBuilder = @_childBuilder({controller}) # Call the callback so that routes defined within it are matched # before the standard routes defined by `resources`. callback?.call(childBuilder) for action, included of actions when included route = @constructor.ROUTES[action] as = route.name(resourceRoot) path = route.path(resourceRoot) routeOptions = $mixin {controller, action, path, as}, options childBuilder[route.cardinality](action, routeOptions) true member: -> @_addRoutesWithCardinality('member', arguments...) collection: -> @_addRoutesWithCardinality('collection', arguments...) root: (signature, options) -> @route '/', signature, options route: (path, signature, options, callback) -> if !callback if typeof options is 'function' callback = options options = undefined else if typeof signature is 'function' callback = signature signature = undefined if !options if typeof signature is 'string' options = {signature} else options = signature options ||= {} else options.signature = signature if signature options.callback = callback if callback options.as ||= @_nameFromPath(path) options.path = path @_addRoute(options) _addRoutesWithCardinality: (cardinality, names..., options) -> if typeof options is 'string' names.push options options = {} options = $mixin {}, @baseOptions, options options[cardinality] = true route = @constructor.ROUTES[cardinality] resourceRoot = options.controller for name in names routeOptions = $mixin {action: name}, options unless routeOptions.path? routeOptions.path = route.path(resourceRoot, name) unless routeOptions.as? routeOptions.as = route.name(resourceRoot, name) @_addRoute(routeOptions) true _addRoute: (options = {}) -> path = @rootPath + options.path name = @rootName + options.as delete options.as delete options.path klass = if options.callback then Batman.CallbackActionRoute else Batman.ControllerActionRoute options.app = @app route = new klass(path, options) @routeMap.addRoute(name, route) _nameFromPath: (path) -> underscored = path .replace(Batman.Route.regexps.namedOrSplat, '') .replace(/\/+/g, '_') .replace(/(^_)|(_$)/g, '') name = helpers.camelize(underscored) name.charAt(0).toLowerCase() + name.slice(1) _nestingPath: -> unless @parent "" else nestingParam = ":" + helpers.singularize(@baseOptions.controller) + "Id" "#{@parent._nestingPath()}/#{@baseOptions.controller}/#{nestingParam}/" _nestingName: -> unless @parent "" else @baseOptions.controller + "." _childBuilder: (baseOptions = {}) -> new Batman.RouteMapBuilder(@app, @routeMap, @, baseOptions) class Batman.Navigator @defaultClass: -> if Batman.config.usePushState and Batman.PushStateNavigator.isSupported() Batman.PushStateNavigator else Batman.HashbangNavigator @forApp: (app) -> new (@defaultClass())(app) constructor: (@app) -> start: -> return if typeof window is 'undefined' return if @started @started = yes @startWatching() Batman.currentApp.prevent 'ready' $setImmediate => if @started && Batman.currentApp @handleCurrentLocation() Batman.currentApp.allowAndFire 'ready' stop: -> @stopWatching() @started = no handleLocation: (location) -> path = @pathFromLocation(location) return if path is @cachedPath @dispatch(path) handleCurrentLocation: => @handleLocation(window.location) dispatch: (params) -> @cachedPath = @app.get('dispatcher').dispatch(params) push: (params) -> path = @dispatch(params) @pushState(null, '', path) path replace: (params) -> path = @dispatch(params) @replaceState(null, '', path) path redirect: @::push normalizePath: (segments...) -> segments = for seg, i in segments "#{seg}".replace(/^(?!\/)/, '/').replace(/\/+$/,'') segments.join('') or '/' @normalizePath: @::normalizePath class Batman.PushStateNavigator extends Batman.Navigator @isSupported: -> window?.history?.pushState? startWatching: -> $addEventListener window, 'popstate', @handleCurrentLocation stopWatching: -> $removeEventListener window, 'popstate', @handleCurrentLocation pushState: (stateObject, title, path) -> window.history.pushState(stateObject, title, @linkTo(path)) replaceState: (stateObject, title, path) -> window.history.replaceState(stateObject, title, @linkTo(path)) linkTo: (url) -> @normalizePath(Batman.config.pathPrefix, url) pathFromLocation: (location) -> fullPath = "#{location.pathname or ''}#{location.search or ''}" prefixPattern = new RegExp("^#{@normalizePath(Batman.config.pathPrefix)}") @normalizePath(fullPath.replace(prefixPattern, '')) handleLocation: (location) -> path = @pathFromLocation(location) if path is '/' and (hashbangPath = Batman.HashbangNavigator::pathFromLocation(location)) isnt '/' @replace(hashbangPath) else super class Batman.HashbangNavigator extends Batman.Navigator HASH_PREFIX: '#!' if window? and 'onhashchange' of window @::startWatching = -> $addEventListener window, 'hashchange', @handleCurrentLocation @::stopWatching = -> $removeEventListener window, 'hashchange', @handleCurrentLocation else @::startWatching = -> @interval = setInterval @handleCurrentLocation, 100 @::stopWatching = -> @interval = clearInterval @interval pushState: (stateObject, title, path) -> window.location.hash = @linkTo(path) replaceState: (stateObject, title, path) -> loc = window.location loc.replace("#{loc.pathname}#{loc.search}#{@linkTo(path)}") linkTo: (url) -> @HASH_PREFIX + url pathFromLocation: (location) -> hash = location.hash if hash?.substr(0,2) is @HASH_PREFIX @normalizePath(hash.substr(2)) else '/' handleLocation: (location) -> return super unless Batman.config.usePushState realPath = Batman.PushStateNavigator::pathFromLocation(location) if realPath is '/' super else location.replace(@normalizePath("#{Batman.config.pathPrefix}#{@linkTo(realPath)}")) Batman.redirect = $redirect = (url) -> Batman.navigator?.redirect url class Batman.ParamsReplacer extends Batman.Object constructor: (@navigator, @params) -> redirect: -> @navigator.replace(@toObject()) replace: (params) -> @params.replace(params) @redirect() update: (params) -> @params.update(params) @redirect() clear: () -> @params.clear() @redirect() toObject: -> @params.toObject() @accessor get: (k) -> @params.get(k) set: (k,v) -> oldValue = @params.get(k) result = @params.set(k,v) @redirect() if oldValue isnt v result unset: (k) -> hadKey = @params.hasKey(k) result = @params.unset(k) @redirect() if hadKey result class Batman.ParamsPusher extends Batman.ParamsReplacer redirect: -> @navigator.push(@toObject()) # `Batman.App` manages requiring files and acts as a namespace for all code subclassing # Batman objects. class Batman.App extends Batman.Object @classAccessor 'currentParams', get: -> new Batman.Hash 'final': true @classAccessor 'paramsManager', get: -> return unless nav = @get('navigator') params = @get('currentParams') params.replacer = new Batman.ParamsReplacer(nav, params) 'final': true @classAccessor 'paramsPusher', get: -> return unless nav = @get('navigator') params = @get('currentParams') params.pusher = new Batman.ParamsPusher(nav, params) 'final': true @classAccessor 'routes', -> new Batman.NamedRouteQuery(@get('routeMap')) @classAccessor 'routeMap', -> new Batman.RouteMap @classAccessor 'routeMapBuilder', -> new Batman.RouteMapBuilder(@, @get('routeMap')) @classAccessor 'dispatcher', -> new Batman.Dispatcher(@, @get('routeMap')) @classAccessor 'controllers', -> @get('dispatcher.controllers') @classAccessor '_renderContext', -> Batman.RenderContext.base.descend(@) # Require path tells the require methods which base directory to look in. @requirePath: '' # The require class methods (`controller`, `model`, `view`) simply tells # your app where to look for coffeescript source files. This # implementation may change in the future. developer.do => App.require = (path, names...) -> base = @requirePath + path for name in names @prevent 'run' path = base + '/' + name + '.coffee' new Batman.Request url: path type: 'html' success: (response) => CoffeeScript.eval response @allow 'run' if not @isPrevented 'run' @fire 'loaded' @run() if @wantsToRun @ @controller = (names...) -> names = names.map (n) -> n + '_controller' @require 'controllers', names... @model = -> @require 'models', arguments... @view = -> @require 'views', arguments... # Layout is the base view that other views can be yielded into. The # default behavior is that when `app.run()` is called, a new view will # be created for the layout using the `document` node as its content. # Use `MyApp.layout = null` to turn off the default behavior. @layout: undefined # Routes for the app are built using a RouteMapBuilder, so delegate the # functions used to build routes to it. for name in Batman.RouteMapBuilder.BUILDER_FUNCTIONS do (name) => @[name] = -> @get('routeMapBuilder')[name](arguments...) # Call `MyApp.run()` to start up an app. Batman level initializers will # be run to bootstrap the application. @event('ready').oneShot = true @event('run').oneShot = true @run: -> if Batman.currentApp return if Batman.currentApp is @ Batman.currentApp.stop() return false if @hasRun if @isPrevented 'run' @wantsToRun = true return false else delete @wantsToRun Batman.currentApp = @ Batman.App.set('current', @) unless @get('dispatcher')? @set 'dispatcher', new Batman.Dispatcher(@, @get('routeMap')) @set 'controllers', @get('dispatcher.controllers') unless @get('navigator')? @set('navigator', Batman.Navigator.forApp(@)) @on 'run', => Batman.navigator = @get('navigator') Batman.navigator.start() if Object.keys(@get('dispatcher').routeMap).length > 0 @observe 'layout', (layout) => layout?.on 'ready', => @fire 'ready' if typeof @layout is 'undefined' @set 'layout', new Batman.View context: @ node: document else if typeof @layout is 'string' @set 'layout', new @[helpers.camelize(@layout) + 'View'] @hasRun = yes @fire('run') @ @event('ready').oneShot = true @event('stop').oneShot = true @stop: -> @navigator?.stop() Batman.navigator = null @hasRun = no @fire('stop') @ # Controllers # ----------- class Batman.Controller extends Batman.Object @singleton 'sharedController' @accessor 'controllerName', -> @_controllerName ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) @accessor '_renderContext', -> Batman.RenderContext.root().descend(@) @beforeFilter: (options, nameOrFunction) -> if not nameOrFunction nameOrFunction = options options = {} else options.only = [options.only] if options.only and $typeOf(options.only) isnt 'Array' options.except = [options.except] if options.except and $typeOf(options.except) isnt 'Array' Batman.initializeObject @ options.block = nameOrFunction filters = @_batman.beforeFilters ||= new Batman.Hash filters.set(nameOrFunction, options) @afterFilter: (options, nameOrFunction) -> if not nameOrFunction nameOrFunction = options options = {} else options.only = [options.only] if options.only and $typeOf(options.only) isnt 'Array' options.except = [options.except] if options.except and $typeOf(options.except) isnt 'Array' Batman.initializeObject @ options.block = nameOrFunction filters = @_batman.afterFilters ||= new Batman.Hash filters.set(nameOrFunction, options) runFilters: (params, filters) -> action = params.action if filters = @constructor._batman?.get(filters) filters.forEach (_, options) => return if options.only and action not in options.only return if options.except and action in options.except block = options.block if typeof block is 'function' then block.call(@, params) else @[block]?(params) # You shouldn't call this method directly. It will be called by the dispatcher when a route is called. # If you need to call a route manually, use `$redirect()`. dispatch: (action, params = {}) -> params.controller ||= @get 'controllerName' params.action ||= action params.target ||= @ oldRedirect = Batman.navigator?.redirect Batman.navigator?.redirect = @redirect @_inAction = yes @_actedDuringAction = no @set 'action', action @set 'params', params @runFilters params, 'beforeFilters' developer.assert @[action], "Error! Controller action #{@get 'controllerName'}.#{action} couldn't be found!" @[action](params) if not @_actedDuringAction @render() @runFilters params, 'afterFilters' delete @_actedDuringAction delete @_inAction Batman.navigator?.redirect = oldRedirect redirectTo = @_afterFilterRedirect delete @_afterFilterRedirect $redirect(redirectTo) if redirectTo redirect: (url) => if @_actedDuringAction && @_inAction developer.warn "Warning! Trying to redirect but an action has already be taken during #{@get('controllerName')}.#{@get('action')}}" if @_inAction @_actedDuringAction = yes @_afterFilterRedirect = url else if $typeOf(url) is 'Object' url.controller = @ if not url.controller $redirect url render: (options = {}) -> if @_actedDuringAction && @_inAction developer.warn "Warning! Trying to render but an action has already be taken during #{@get('controllerName')}.#{@get('action')}" @_actedDuringAction = yes return if options is false if not options.view options.context ||= @get('_renderContext') options.source ||= helpers.underscore(@get('controllerName') + '/' + @get('action')) options.view = new (Batman.currentApp?[helpers.camelize("#{@get('controllerName')}_#{@get('action')}_view")] || Batman.View)(options) if view = options.view Batman.currentApp?.prevent 'ready' view.on 'ready', => Batman.DOM.replace options.into || 'main', view.get('node'), view.hasContainer Batman.currentApp?.allowAndFire 'ready' view.ready?(@params) view # Models # ------ class Batman.Model extends Batman.Object # ## Model API # Override this property if your model is indexed by a key other than `id` @primaryKey: 'id' # Override this property to define the key which storage adapters will use to store instances of this model under. # - For RestStorage, this ends up being part of the url built to store this model # - For LocalStorage, this ends up being the namespace in localStorage in which JSON is stored @storageKey: null # Pick one or many mechanisms with which this model should be persisted. The mechanisms # can be already instantiated or just the class defining them. @persist: (mechanisms...) -> Batman.initializeObject @prototype storage = @::_batman.storage ||= [] results = for mechanism in mechanisms mechanism = if mechanism.isStorageAdapter then mechanism else new mechanism(@) storage.push mechanism mechanism if results.length > 1 results else results[0] # Encoders are the tiny bits of logic which manage marshalling Batman models to and from their # storage representations. Encoders do things like stringifying dates and parsing them back out again, # pulling out nested model collections and instantiating them (and JSON.stringifying them back again), # and marshalling otherwise un-storable object. @encode: (keys..., encoderOrLastKey) -> Batman.initializeObject @prototype @::_batman.encoders ||= new Batman.SimpleHash @::_batman.decoders ||= new Batman.SimpleHash encoder = {} switch $typeOf(encoderOrLastKey) when 'String' keys.push encoderOrLastKey when 'Function' encoder.encode = encoderOrLastKey else encoder.encode = encoderOrLastKey.encode encoder.decode = encoderOrLastKey.decode encoder = $mixin {}, @defaultEncoder, encoder for operation in ['encode', 'decode'] for key in keys hash = @::_batman["#{operation}rs"] if encoder[operation] hash.set(key, encoder[operation]) else hash.unset(key) #true # Set up the unit functions as the default for both @defaultEncoder: encode: (x) -> x decode: (x) -> x # Attach encoders and decoders for the primary key, and update them if the primary key changes. @observeAndFire 'primaryKey', (newPrimaryKey) -> @encode newPrimaryKey, {encode: false, decode: @defaultEncoder.decode} # Validations allow a model to be marked as 'valid' or 'invalid' based on a set of programmatic rules. # By validating our data before it gets to the server we can provide immediate feedback to the user about # what they have entered and forgo waiting on a round trip to the server. # `validate` allows the attachment of validations to the model on particular keys, where the validation is # either a built in one (by use of options to pass to them) or a custom one (by use of a custom function as # the second argument). Custom validators should have the signature `(errors, record, key, callback)`. They # should add strings to the `errors` set based on the record (maybe depending on the `key` they were attached # to) and then always call the callback. Again: the callback must always be called. @validate: (keys..., optionsOrFunction) -> Batman.initializeObject @prototype validators = @::_batman.validators ||= [] if typeof optionsOrFunction is 'function' # Given a function, use that as the actual validator, expecting it to conform to the API # the built in validators do. validators.push keys: keys callback: optionsOrFunction else # Given options, find the validations which match the given options, and add them to the validators # array. options = optionsOrFunction for validator in Validators if (matches = validator.matches(options)) delete options[match] for match in matches validators.push keys: keys validator: new validator(matches) @urlNestsUnder: (key) -> parent = Batman.helpers.pluralize(key) children = Batman.helpers.pluralize(Batman._functionName(@).toLowerCase()) @url = (options) -> parentID = options.data[key + '_id'] delete options.data[key + '_id'] "#{parent}/#{parentID}/#{children}" @::url = -> url = "#{parent}/#{@get(key + '_id')}/#{children}" if id = @get('id') url += '/' + id url # ### Query methods @classAccessor 'all', get: -> @load() if @::hasStorage() and @classState() not in ['loaded', 'loading'] @get('loaded') set: (k, v) -> @set('loaded', v) @classAccessor 'loaded', get: -> @_loaded ||= new Batman.Set set: (k, v) -> @_loaded = v @classAccessor 'first', -> @get('all').toArray()[0] @classAccessor 'last', -> x = @get('all').toArray(); x[x.length - 1] @clear: -> Batman.initializeObject(@) result = @get('loaded').clear() @_batman.get('associations')?.reset() result @find: (id, callback) -> developer.assert callback, "Must call find with a callback!" record = new @() record.set 'id', id newRecord = @_mapIdentity(record) newRecord.load callback return newRecord # `load` fetches records from all sources possible @load: (options, callback) -> if typeof options in ['function', 'undefined'] callback = options options = {} developer.assert @::_batman.getAll('storage').length, "Can't load model #{$functionName(@)} without any storage adapters!" @loading() @::_doStorageOperation 'readAll', options, (err, records) => if err? callback?(err, []) else mappedRecords = (@_mapIdentity(record) for record in records) @loaded() callback?(err, mappedRecords) # `create` takes an attributes hash, creates a record from it, and saves it given the callback. @create: (attrs, callback) -> if !callback [attrs, callback] = [{}, attrs] obj = new this(attrs) obj.save(callback) obj # `findOrCreate` takes an attributes hash, optionally containing a primary key, and returns to you a saved record # representing those attributes, either from the server or from the identity map. @findOrCreate: (attrs, callback) -> record = new this(attrs) if record.isNew() record.save(callback) else foundRecord = @_mapIdentity(record) foundRecord.updateAttributes(attrs) callback(undefined, foundRecord) @_mapIdentity: (record) -> if typeof (id = record.get('id')) == 'undefined' || id == '' return record else existing = @get("loaded.indexedBy.id").get(id)?.toArray()[0] if existing existing.updateAttributes(record._batman.attributes || {}) return existing else @get('loaded').add(record) return record associationProxy: (association) -> Batman.initializeObject(@) proxies = @_batman.associationProxies ||= new Batman.SimpleHash proxies.get(association.label) or proxies.set(association.label, new association.proxyClass(association, @)) # ### Record API # Add a universally accessible accessor for retrieving the primrary key, regardless of which key its stored under. @accessor 'id', get: -> pk = @constructor.primaryKey if pk == 'id' @id else @get(pk) set: (k, v) -> # naively coerce string ids into integers if typeof v is "string" and v.match(/[^0-9]/) is null v = parseInt(v, 10) pk = @constructor.primaryKey if pk == 'id' @id = v else @set(pk, v) # Add normal accessors for the dirty keys and errors attributes of a record, so these accesses don't fall to the # default accessor. @accessor 'dirtyKeys', 'errors', Batman.Property.defaultAccessor # Add an accessor for the internal batman state under `batmanState`, so that the `state` key can be a valid # attribute. @accessor 'batmanState' get: -> @state() set: (k, v) -> @state(v) # Add a default accessor to make models store their attributes under a namespace by default. @accessor Model.defaultAccessor = get: (k) -> attribute = (@_batman.attributes ||= {})[k] if typeof attribute isnt 'undefined' attribute else @[k] set: (k, v) -> (@_batman.attributes ||= {})[k] = v unset: (k) -> x = (@_batman.attributes ||={})[k] delete @_batman.attributes[k] x # New records can be constructed by passing either an ID or a hash of attributes (potentially # containing an ID) to the Model constructor. By not passing an ID, the model is marked as new. constructor: (idOrAttributes = {}) -> developer.assert @ instanceof Batman.Object, "constructors must be called with new" # We have to do this ahead of super, because mixins will call set which calls things on dirtyKeys. @dirtyKeys = new Batman.Hash @errors = new Batman.ErrorsSet # Find the ID from either the first argument or the attributes. if $typeOf(idOrAttributes) is 'Object' super(idOrAttributes) else super() @set('id', idOrAttributes) @empty() if not @state() # Override the `Batman.Observable` implementation of `set` to implement dirty tracking. set: (key, value) -> # Optimize setting where the value is the same as what's already been set. oldValue = @get(key) return if oldValue is value # Actually set the value and note what the old value was in the tracking array. result = super @dirtyKeys.set(key, oldValue) # Mark the model as dirty if isn't already. @dirty() unless @state() in ['dirty', 'loading', 'creating'] result updateAttributes: (attrs) -> @mixin(attrs) @ toString: -> "#{$functionName(@constructor)}: #{@get('id')}" # `toJSON` uses the various encoders for each key to grab a storable representation of the record. toJSON: -> obj = {} # Encode each key into a new object encoders = @_batman.get('encoders') unless !encoders or encoders.isEmpty() encoders.forEach (key, encoder) => val = @get key if typeof val isnt 'undefined' encodedVal = encoder(val, key, obj, @) if typeof encodedVal isnt 'undefined' obj[key] = encodedVal if @constructor.primaryKey isnt 'id' obj[@constructor.primaryKey] = @get('id') delete obj.id obj # `fromJSON` uses the various decoders for each key to generate a record instance from the JSON # stored in whichever storage mechanism. fromJSON: (data) -> obj = {} decoders = @_batman.get('decoders') # If no decoders were specified, do the best we can to interpret the given JSON by camelizing # each key and just setting the values. if !decoders or decoders.isEmpty() for key, value of data obj[key] = value else # If we do have decoders, use them to get the data. decoders.forEach (key, decoder) => obj[key] = decoder(data[key], key, data, obj, @) unless typeof data[key] is 'undefined' if @constructor.primaryKey isnt 'id' obj.id = data[@constructor.primaryKey] developer.do => if (!decoders) || decoders.length <= 1 developer.warn "Warning: Model #{$functionName(@constructor)} has suspiciously few decoders!" # Mixin the buffer object to use optimized and event-preventing sets used by `mixin`. @mixin obj toParam: -> @get('id') # Each model instance (each record) can be in one of many states throughout its lifetime. Since various # operations on the model are asynchronous, these states are used to indicate exactly what point the # record is at in it's lifetime, which can often be during a save or load operation. @actsAsStateMachine yes # Add the various states to the model. for k in ['empty', 'dirty', 'loading', 'loaded', 'saving', 'saved', 'creating', 'created', 'validating', 'validated', 'destroying', 'destroyed'] @state k for k in ['loading', 'loaded'] @classState k _doStorageOperation: (operation, options, callback) -> developer.assert @hasStorage(), "Can't #{operation} model #{$functionName(@constructor)} without any storage adapters!" adapters = @_batman.get('storage') for adapter in adapters adapter.perform operation, @, {data: options}, callback true hasStorage: -> (@_batman.get('storage') || []).length > 0 # `load` fetches the record from all sources possible load: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't load a destroyed record!")) return @loading() @_doStorageOperation 'read', {}, (err, record) => unless err @loaded() record = @constructor._mapIdentity(record) callback?(err, record) # `save` persists a record to all the storage mechanisms added using `@persist`. `save` will only save # a model if it is valid. save: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't save a destroyed record!")) return @validate (isValid, errors) => if !isValid callback?(errors) return creating = @isNew() do @saving do @creating if creating associations = @constructor._batman.get('associations') # Save belongsTo models immediately since we don't need this model's id associations?.getByType('belongsTo')?.forEach (association, label) => association.apply(@) @_doStorageOperation (if creating then 'create' else 'update'), {}, (err, record) => unless err if creating do @created do @saved @dirtyKeys.clear() associations?.getByType('hasOne')?.forEach (association) -> association.apply(err, record) associations?.getByType('hasMany')?.forEach (association) -> association.apply(err, record) record = @constructor._mapIdentity(record) callback?(err, record) # `destroy` destroys a record in all the stores. destroy: (callback) => do @destroying @_doStorageOperation 'destroy', {}, (err, record) => unless err @constructor.get('all').remove(@) do @destroyed callback?(err) # `validate` performs the record level validations determining the record's validity. These may be asynchronous, # in which case `validate` has no useful return value. Results from asynchronous validations can be received by # listening to the `afterValidation` lifecycle callback. validate: (callback) -> oldState = @state() @errors.clear() do @validating finish = () => do @validated @[oldState]() callback?(@errors.length == 0, @errors) validators = @_batman.get('validators') || [] unless validators.length > 0 finish() else count = validators.length validationCallback = => if --count == 0 finish() for validator in validators v = validator.validator # Run the validator `v` or the custom callback on each key it validates by instantiating a new promise # and passing it to the appropriate function along with the key and the value to be validated. for key in validator.keys if v v.validateEach @errors, @, key, validationCallback else validator.callback @errors, @, key, validationCallback return isNew: -> typeof @get('id') is 'undefined' # ## Associations class Batman.AssociationProxy extends Batman.Object isProxy: true constructor: (@association, @model) -> loaded: false toJSON: -> target = @get('target') @get('target').toJSON() if target? load: (callback) -> @fetch (err, proxiedRecord) => unless err @set 'loaded', true @set 'target', proxiedRecord callback?(err, proxiedRecord) @get('target') fetch: (callback) -> unless (@get('foreignValue') || @get('primaryValue'))? return callback(undefined, undefined) record = @fetchFromLocal() if record return callback(undefined, record) else @fetchFromRemote(callback) @accessor 'loaded', Batman.Property.defaultAccessor @accessor 'target', get: -> @fetchFromLocal() set: (_, v) -> v # This just needs to bust the cache @accessor get: (k) -> @get('target')?.get(k) set: (k, v) -> @get('target')?.set(k, v) class Batman.BelongsToProxy extends Batman.AssociationProxy @accessor 'foreignValue', -> @model.get(@association.foreignKey) fetchFromLocal: -> @association.setIndex().get(@get('foreignValue')) fetchFromRemote: (callback) -> @association.getRelatedModel().find @get('foreignValue'), (error, loadedRecord) => throw error if error callback undefined, loadedRecord class Batman.HasOneProxy extends Batman.AssociationProxy @accessor 'primaryValue', -> @model.get(@association.primaryKey) fetchFromLocal: -> @association.setIndex().get(@get('primaryValue')) fetchFromRemote: (callback) -> loadOptions = {} loadOptions[@association.foreignKey] = @get('primaryValue') @association.getRelatedModel().load loadOptions, (error, loadedRecords) => throw error if error if !loadedRecords or loadedRecords.length <= 0 callback new Error("Couldn't find related record!"), undefined else callback undefined, loadedRecords[0] class Batman.AssociationSet extends Batman.SetSort constructor: (@value, @association) -> base = new Batman.Set super(base, 'hashKey') loaded: false load: (callback) -> return callback(undefined, @) unless @value? loadOptions = {} loadOptions[@association.foreignKey] = @value @association.getRelatedModel().load loadOptions, (err, records) => @loaded = true unless err @fire 'loaded' callback(err, @) class Batman.UniqueAssociationSetIndex extends Batman.UniqueSetIndex constructor: (@association, key) -> super @association.getRelatedModel().get('loaded'), key class Batman.AssociationSetIndex extends Batman.SetIndex constructor: (@association, key) -> super @association.getRelatedModel().get('loaded'), key _resultSetForKey: (key) -> @_storage.getOrSet key, => new Batman.AssociationSet(key, @association) _setResultSet: (key, set) -> @_storage.set key, set class Batman.AssociationCurator extends Batman.SimpleHash @availableAssociations: ['belongsTo', 'hasOne', 'hasMany'] constructor: (@model) -> super() # Contains (association, label) pairs mapped by association type # ie. @storage = {<Association.associationType>: [<Association>, <Association>]} @_byTypeStorage = new Batman.SimpleHash add: (association) -> @set association.label, association unless associationTypeSet = @_byTypeStorage.get(association.associationType) associationTypeSet = new Batman.SimpleSet @_byTypeStorage.set association.associationType, associationTypeSet associationTypeSet.add association getByType: (type) -> @_byTypeStorage.get(type) getByLabel: (label) -> @get(label) reset: -> @forEach (label, association) -> association.reset() true merge: (others...) -> result = super result._byTypeStorage = @_byTypeStorage.merge(others.map (other) -> other._byTypeStorage) result class Batman.Association associationType: '' defaultOptions: saveInline: true autoload: true constructor: (@model, @label, options = {}) -> defaultOptions = namespace: Batman.currentApp name: helpers.camelize(helpers.singularize(@label)) @options = $mixin defaultOptions, @defaultOptions, options # Setup encoders and accessors for this association. The accessor needs reference to this # association object, so curry the association info into the getAccessor, which has the # model applied as the context @model.encode label, @encoder() self = @ getAccessor = -> return self.getAccessor.call(@, self, @model, @label) @model.accessor @label, get: getAccessor set: model.defaultAccessor.set unset: model.defaultAccessor.unset if @url @model.url ||= (recordOptions) -> return self.url(recordOptions) getRelatedModel: -> scope = @options.namespace or Batman.currentApp modelName = @options.name relatedModel = scope?[modelName] developer.do -> if Batman.currentApp? and not relatedModel developer.warn "Related model #{modelName} hasn't loaded yet." relatedModel getFromAttributes: (record) -> record.constructor.defaultAccessor.get.call(record, @label) setIntoAttributes: (record, value) -> record.constructor.defaultAccessor.set.call(record, @label, value) encoder: -> developer.error "You must override encoder in Batman.Association subclasses." setIndex: -> developer.error "You must override setIndex in Batman.Association subclasses." inverse: -> if relatedAssocs = @getRelatedModel()._batman.get('associations') if @options.inverseOf return relatedAssocs.getByLabel(@options.inverseOf) inverse = null relatedAssocs.forEach (label, assoc) => if assoc.getRelatedModel() is @model inverse = assoc inverse reset: -> delete @index true class Batman.SingularAssociation extends Batman.Association isSingular: true getAccessor: (self, model, label) -> # Check whether the relation has already been set on this model if recordInAttributes = self.getFromAttributes(@) return recordInAttributes # Make sure the related model has been loaded if self.getRelatedModel() proxy = @associationProxy(self) Batman.Property.withoutTracking -> if not proxy.get('loaded') and self.options.autoload proxy.load() proxy setIndex: -> @index ||= new Batman.UniqueAssociationSetIndex(@, @[@indexRelatedModelOn]) @index class Batman.PluralAssociation extends Batman.Association isSingular: false setForRecord: (record) -> Batman.Property.withoutTracking => if id = record.get(@primaryKey) @setIndex().get(id) else new Batman.AssociationSet(undefined, @) getAccessor: (self, model, label) -> return unless self.getRelatedModel() # Check whether the relation has already been set on this model if setInAttributes = self.getFromAttributes(@) setInAttributes else relatedRecords = self.setForRecord(@) self.setIntoAttributes(@, relatedRecords) Batman.Property.withoutTracking => if self.options.autoload and not @isNew() and not relatedRecords.loaded relatedRecords.load (error, records) -> throw error if error relatedRecords setIndex: -> @index ||= new Batman.AssociationSetIndex(@, @[@indexRelatedModelOn]) @index class Batman.BelongsToAssociation extends Batman.SingularAssociation associationType: 'belongsTo' proxyClass: Batman.BelongsToProxy indexRelatedModelOn: 'primaryKey' defaultOptions: saveInline: false autoload: true constructor: -> super @foreignKey = @options.foreignKey or "#{@label}_id" @primaryKey = @options.primaryKey or "id" @model.encode @foreignKey url: (recordOptions) -> if inverse = @inverse() root = Batman.helpers.pluralize(@label) id = recordOptions.data?["#{@label}_id"] helper = if inverse.isSingular then "singularize" else "pluralize" ending = Batman.helpers[helper](inverse.label) return "/#{root}/#{id}/#{ending}" encoder: -> association = @ encoder = encode: false decode: (data, _, __, ___, childRecord) -> relatedModel = association.getRelatedModel() record = new relatedModel() record.fromJSON(data) record = relatedModel._mapIdentity(record) if association.options.inverseOf if inverse = association.inverse() if inverse instanceof Batman.HasManyAssociation # Rely on the parent's set index to get this out. childRecord.set(association.foreignKey, record.get(association.primaryKey)) else record.set(inverse.label, childRecord) childRecord.set(association.label, record) record if @options.saveInline encoder.encode = (val) -> val.toJSON() encoder apply: (base) -> if model = base.get(@label) foreignValue = model.get(@primaryKey) if foreignValue isnt undefined base.set @foreignKey, foreignValue class Batman.HasOneAssociation extends Batman.SingularAssociation associationType: 'hasOne' proxyClass: Batman.HasOneProxy indexRelatedModelOn: 'foreignKey' constructor: -> super @primaryKey = @options.primaryKey or "id" @foreignKey = @options.foreignKey or "#{helpers.underscore($functionName(@model))}_id" apply: (baseSaveError, base) -> if relation = @getFromAttributes(base) relation.set @foreignKey, base.get(@primaryKey) encoder: -> association = @ return { encode: (val, key, object, record) -> return unless association.options.saveInline if json = val.toJSON() json[association.foreignKey] = record.get(association.primaryKey) json decode: (data, _, __, ___, parentRecord) -> relatedModel = association.getRelatedModel() record = new (relatedModel)() record.fromJSON(data) if association.options.inverseOf record.set association.options.inverseOf, parentRecord record = relatedModel._mapIdentity(record) record } class Batman.HasManyAssociation extends Batman.PluralAssociation associationType: 'hasMany' indexRelatedModelOn: 'foreignKey' constructor: -> super @primaryKey = @options.primaryKey or "id" @foreignKey = @options.foreignKey or "#{helpers.underscore($functionName(@model))}_id" apply: (baseSaveError, base) -> unless baseSaveError if relations = @getFromAttributes(base) relations.forEach (model) => model.set @foreignKey, base.get(@primaryKey) base.set @label, @setForRecord(base) encoder: -> association = @ return { encode: (relationSet, _, __, record) -> return if association._beingEncoded association._beingEncoded = true return unless association.options.saveInline if relationSet? jsonArray = [] relationSet.forEach (relation) -> relationJSON = relation.toJSON() relationJSON[association.foreignKey] = record.get(association.primaryKey) jsonArray.push relationJSON delete association._beingEncoded jsonArray decode: (data, key, _, __, parentRecord) -> if relatedModel = association.getRelatedModel() existingRelations = association.getFromAttributes(parentRecord) || association.setForRecord(parentRecord) existingArray = existingRelations?.toArray() for jsonObject, i in data record = if existingArray && existingArray[i] existing = true existingArray[i] else existing = false new relatedModel() record.fromJSON jsonObject if association.options.inverseOf record.set association.options.inverseOf, parentRecord record = relatedModel._mapIdentity(record) existingRelations.add record else developer.error "Can't decode model #{association.options.name} because it hasn't been loaded yet!" existingRelations } # ### Model Associations API for k in Batman.AssociationCurator.availableAssociations do (k) => Batman.Model[k] = (label, scope) -> Batman.initializeObject(@) collection = @_batman.associations ||= new Batman.AssociationCurator(@) collection.add new Batman["#{helpers.capitalize(k)}Association"](@, label, scope) class Batman.ValidationError extends Batman.Object constructor: (attribute, message) -> super({attribute, message}) # `ErrorSet` is a simple subclass of `Set` which makes it a bit easier to # manage the errors on a model. class Batman.ErrorsSet extends Batman.Set # Define a default accessor to get the set of errors on a key @accessor (key) -> @indexedBy('attribute').get(key) # Define a shorthand method for adding errors to a key. add: (key, error) -> super(new Batman.ValidationError(key, error)) class Batman.Validator extends Batman.Object constructor: (@options, mixins...) -> super mixins... validate: (record) -> developer.error "You must override validate in Batman.Validator subclasses." format: (key, messageKey, interpolations) -> t('errors.format', {attribute: key, message: t("errors.messages.#{messageKey}", interpolations)}) @options: (options...) -> Batman.initializeObject @ if @_batman.options then @_batman.options.concat(options) else @_batman.options = options @matches: (options) -> results = {} shouldReturn = no for key, value of options if ~@_batman?.options?.indexOf(key) results[key] = value shouldReturn = yes return results if shouldReturn Validators = Batman.Validators = [ class Batman.LengthValidator extends Batman.Validator @options 'minLength', 'maxLength', 'length', 'lengthWithin', 'lengthIn' constructor: (options) -> if range = (options.lengthIn or options.lengthWithin) options.minLength = range[0] options.maxLength = range[1] || -1 delete options.lengthWithin delete options.lengthIn super validateEach: (errors, record, key, callback) -> options = @options value = record.get(key) ? [] if options.minLength and value.length < options.minLength errors.add key, @format(key, 'too_short', {count: options.minLength}) if options.maxLength and value.length > options.maxLength errors.add key, @format(key, 'too_long', {count: options.maxLength}) if options.length and value.length isnt options.length errors.add key, @format(key, 'wrong_length', {count: options.length}) callback() class Batman.PresenceValidator extends Batman.Validator @options 'presence' validateEach: (errors, record, key, callback) -> value = record.get(key) if @options.presence && (!value? || value is '') errors.add key, @format(key, 'blank') callback() ] $mixin Batman.translate.messages, errors: format: "%{attribute} %{message}" messages: too_short: "must be at least %{count} characters" too_long: "must be less than %{count} characters" wrong_length: "must be %{count} characters" blank: "can't be blank" class Batman.StorageAdapter extends Batman.Object class @StorageError extends Error name: "StorageError" constructor: (message) -> super @message = message class @RecordExistsError extends @StorageError name: 'RecordExistsError' constructor: (message) -> super(message || "Can't create this record because it already exists in the store!") class @NotFoundError extends @StorageError name: 'NotFoundError' constructor: (message) -> super(message || "Record couldn't be found in storage!") constructor: (model) -> super(model: model) isStorageAdapter: true storageKey: (record) -> model = record?.constructor || @model model.get('storageKey') || helpers.pluralize(helpers.underscore($functionName(model))) getRecordFromData: (attributes, constructor = @model) -> record = new constructor() record.fromJSON(attributes) record @skipIfError: (f) -> return (env, next) -> if env.error? next() else f.call(@, env, next) before: -> @_addFilter('before', arguments...) after: -> @_addFilter('after', arguments...) _inheritFilters: -> if !@_batman.check(@) || !@_batman.filters oldFilters = @_batman.getFirst('filters') @_batman.filters = {before: {}, after: {}} if oldFilters? for position, filtersByKey of oldFilters for key, filtersList of filtersByKey @_batman.filters[position][key] = filtersList.slice(0) _addFilter: (position, keys..., filter) -> @_inheritFilters() for key in keys @_batman.filters[position][key] ||= [] @_batman.filters[position][key].push filter true runFilter: (position, action, env, callback) -> @_inheritFilters() allFilters = @_batman.filters[position].all || [] actionFilters = @_batman.filters[position][action] || [] env.action = action # Action specific filters execute first, and then the `all` filters. filters = actionFilters.concat(allFilters) next = (newEnv) => env = newEnv if newEnv? if (nextFilter = filters.shift())? nextFilter.call @, env, next else callback.call @, env next() runBeforeFilter: -> @runFilter 'before', arguments... runAfterFilter: (action, env, callback) -> @runFilter 'after', action, env, @exportResult(callback) exportResult: (callback) -> (env) -> callback(env.error, env.result, env) _jsonToAttributes: (json) -> JSON.parse(json) perform: (key, recordOrProto, options, callback) -> options ||= {} env = {options} if key == 'readAll' env.proto = recordOrProto else env.record = recordOrProto next = (newEnv) => env = newEnv if newEnv? @runAfterFilter key, env, callback @runBeforeFilter key, env, (env) -> @[key](env, next) class Batman.LocalStorage extends Batman.StorageAdapter constructor: -> return null if typeof window.localStorage is 'undefined' super @storage = localStorage storageRegExpForRecord: (record) -> new RegExp("^#{@storageKey(record)}(\\d+)$") nextIdForRecord: (record) -> re = @storageRegExpForRecord(record) nextId = 1 @_forAllStorageEntries (k, v) -> if matches = re.exec(k) nextId = Math.max(nextId, parseInt(matches[1], 10) + 1) nextId _forAllStorageEntries: (iterator) -> for i in [0...@storage.length] key = @storage.key(i) iterator.call(@, key, @storage.getItem(key)) true _storageEntriesMatching: (proto, options) -> re = @storageRegExpForRecord(proto) records = [] @_forAllStorageEntries (storageKey, storageString) -> if keyMatches = re.exec(storageKey) data = @_jsonToAttributes(storageString) data[proto.constructor.primaryKey] = keyMatches[1] records.push data if @_dataMatches(options, data) records _dataMatches: (conditions, data) -> match = true for k, v of conditions if data[k] != v match = false break match @::before 'read', 'create', 'update', 'destroy', @skipIfError (env, next) -> if env.action == 'create' env.id = env.record.get('id') || env.record.set('id', @nextIdForRecord(env.record)) else env.id = env.record.get('id') unless env.id? env.error = new @constructor.StorageError("Couldn't get/set record primary key on #{env.action}!") else env.key = @storageKey(env.record) + env.id next() @::before 'create', 'update', @skipIfError (env, next) -> env.recordAttributes = JSON.stringify(env.record) next() @::after 'read', @skipIfError (env, next) -> if typeof env.recordAttributes is 'string' try env.recordAttributes = @_jsonToAttributes(env.recordAttributes) catch error env.error = error return next() env.record.fromJSON env.recordAttributes next() @::after 'read', 'create', 'update', 'destroy', @skipIfError (env, next) -> env.result = env.record next() @::after 'readAll', @skipIfError (env, next) -> env.result = env.records = for recordAttributes in env.recordsAttributes @getRecordFromData(recordAttributes, env.proto.constructor) next() read: @skipIfError (env, next) -> env.recordAttributes = @storage.getItem(env.key) if !env.recordAttributes env.error = new @constructor.NotFoundError() next() create: @skipIfError ({key, recordAttributes}, next) -> if @storage.getItem(key) arguments[0].error = new @constructor.RecordExistsError else @storage.setItem(key, recordAttributes) next() update: @skipIfError ({key, recordAttributes}, next) -> @storage.setItem(key, recordAttributes) next() destroy: @skipIfError ({key}, next) -> @storage.removeItem(key) next() readAll: @skipIfError ({proto, options}, next) -> try arguments[0].recordsAttributes = @_storageEntriesMatching(proto, options.data) catch error arguments[0].error = error next() class Batman.SessionStorage extends Batman.LocalStorage constructor: -> if typeof window.sessionStorage is 'undefined' return null super @storage = sessionStorage class Batman.RestStorage extends Batman.StorageAdapter @JSONContentType: 'application/json' @PostBodyContentType: 'application/x-www-form-urlencoded' defaultRequestOptions: type: 'json' serializeAsForm: true constructor: -> super @defaultRequestOptions = $mixin {}, @defaultRequestOptions recordJsonNamespace: (record) -> helpers.singularize(@storageKey(record)) collectionJsonNamespace: (proto) -> helpers.pluralize(@storageKey(proto)) _execWithOptions: (object, key, options) -> if typeof object[key] is 'function' then object[key](options) else object[key] _defaultCollectionUrl: (record) -> "/#{@storageKey(record)}" urlForRecord: (record, env) -> if record.url url = @_execWithOptions(record, 'url', env.options) else url = if record.constructor.url @_execWithOptions(record.constructor, 'url', env.options) else @_defaultCollectionUrl(record) if env.action != 'create' if (id = record.get('id'))? url = url + "/" + id else throw new @constructor.StorageError("Couldn't get/set record primary key on #{env.action}!") @urlPrefix(record, env) + url + @urlSuffix(record, env) urlForCollection: (model, env) -> url = if model.url @_execWithOptions(model, 'url', env.options) else @_defaultCollectionUrl(model::, env.options) @urlPrefix(model, env) + url + @urlSuffix(model, env) urlPrefix: (object, env) -> @_execWithOptions(object, 'urlPrefix', env.options) || '' urlSuffix: (object, env) -> @_execWithOptions(object, 'urlSuffix', env.options) || '' request: (env, next) -> options = $mixin env.options, success: (data) -> env.data = data error: (error) -> env.error = error loaded: -> env.response = req.get('response') next() req = new Batman.Request(options) perform: (key, record, options, callback) -> $mixin (options ||= {}), @defaultRequestOptions super @::before 'create', 'read', 'update', 'destroy', @skipIfError (env, next) -> try env.options.url = @urlForRecord(env.record, env) catch error env.error = error next() @::before 'readAll', @skipIfError (env, next) -> try env.options.url = @urlForCollection(env.proto.constructor, env) catch error env.error = error next() @::before 'create', 'update', @skipIfError (env, next) -> json = env.record.toJSON() if namespace = @recordJsonNamespace(env.record) data = {} data[namespace] = json else data = json if @serializeAsForm # Leave the POJO in the data for the request adapter to serialize to a body env.options.contentType = @constructor.PostBodyContentType else data = JSON.stringify(data) env.options.contentType = @constructor.JSONContentType env.options.data = data next() @::after 'create', 'read', 'update', @skipIfError (env, next) -> if typeof env.data is 'string' try json = @_jsonToAttributes(env.data) catch error env.error = error return next() else json = env.data namespace = @recordJsonNamespace(env.record) json = json[namespace] if namespace && json[namespace]? env.record.fromJSON(json) env.result = env.record next() @::after 'readAll', @skipIfError (env, next) -> if typeof env.data is 'string' try env.data = JSON.parse(env.env) catch jsonError env.error = jsonError return next() namespace = @collectionJsonNamespace(env.proto) env.recordsAttributes = if namespace && env.data[namespace]? env.data[namespace] else env.data env.result = env.records = for jsonRecordAttributes in env.recordsAttributes @getRecordFromData(jsonRecordAttributes, env.proto.constructor) next() @HTTPMethods = create: 'POST' update: 'PUT' read: 'GET' readAll: 'GET' destroy: 'DELETE' for key in ['create', 'read', 'update', 'destroy', 'readAll'] do (key) => @::[key] = @skipIfError (env, next) -> env.options.method = @constructor.HTTPMethods[key] @request(env, next) # Views # ----------- class Batman.ViewStore extends Batman.Object @prefix: 'views' constructor: -> super @_viewContents = {} @_requestedPaths = new Batman.SimpleSet propertyClass: Batman.Property fetchView: (path) -> developer.do -> unless typeof Batman.View::prefix is 'undefined' developer.warn "Batman.View.prototype.prefix has been removed, please use Batman.ViewStore.prefix instead." new Batman.Request url: Batman.Navigator.normalizePath(@constructor.prefix, "#{path}.html") type: 'html' success: (response) => @set(path, response) error: (response) -> throw new Error("Could not load view from #{path}") @accessor 'final': true get: (path) -> return @get("/#{path}") unless path[0] is '/' return @_viewContents[path] if @_viewContents[path] return if @_requestedPaths.has(path) @fetchView(path) return set: (path, content) -> return @set("/#{path}", content) unless path[0] is '/' @_requestedPaths.add(path) @_viewContents[path] = content prefetch: (path) -> @get(path) true # A `Batman.View` can function two ways: a mechanism to load and/or parse html files # or a root of a subclass hierarchy to create rich UI classes, like in Cocoa. class Batman.View extends Batman.Object isView: true constructor: (options = {}) -> context = options.context if context unless context instanceof Batman.RenderContext context = Batman.RenderContext.root().descend(context) else context = Batman.RenderContext.root() options.context = context.descend(@) super(options) # Start the rendering by asking for the node Batman.Property.withoutTracking => if node = @get('node') @render node else @observe 'node', (node) => @render(node) @store: new Batman.ViewStore() # Set the source attribute to an html file to have that file loaded. source: '' # Set the html to a string of html to have that html parsed. html: '' # Set an existing DOM node to parse immediately. node: null # Fires once a node is parsed. @::event('ready').oneShot = true @accessor 'html', get: -> return @html if @html && @html.length > 0 return unless source = @get 'source' source = Batman.Navigator.normalizePath(source) @html = @constructor.store.get(source) set: (_, html) -> @html = html @accessor 'node' get: -> unless @node html = @get('html') return unless html && html.length > 0 @hasContainer = true @node = document.createElement 'div' $setInnerHTML(@node, html) if @node.children.length > 0 Batman.data(@node.children[0], 'view', @) return @node set: (_, node) -> @node = node Batman.data(@node, 'view', @) updateHTML = (html) => if html? $setInnerHTML(@get('node'), html) @forget('html', updateHTML) @observeAndFire 'html', updateHTML render: (node) -> @event('ready').resetOneShot() @_renderer?.forgetAll() # We use a renderer with the continuation style rendering engine to not # block user interaction for too long during the render. if node @_renderer = new Batman.Renderer(node, null, @context, @) @_renderer.on 'rendered', => @fire('ready', node) @::on 'appear', -> @viewDidAppear? arguments... @::on 'disappear', -> @viewDidDisappear? arguments... @::on 'beforeAppear', -> @viewWillAppear? arguments... @::on 'beforeDisappear', -> @viewWillDisappear? arguments... # DOM Helpers # ----------- # `Batman.Renderer` will take a node and parse all recognized data attributes out of it and its children. # It is a continuation style parser, designed not to block for longer than 50ms at a time if the document # fragment is particularly long. class Batman.Renderer extends Batman.Object deferEvery: 50 constructor: (@node, callback, @context, view) -> super() @on('parsed', callback) if callback? developer.error "Must pass a RenderContext to a renderer for rendering" unless @context instanceof Batman.RenderContext @immediate = $setImmediate @start start: => @startTime = new Date @parseNode @node resume: => @startTime = new Date @parseNode @resumeNode finish: -> @startTime = null @prevent 'stopped' @fire 'parsed' @fire 'rendered' stop: -> $clearImmediate @immediate @fire 'stopped' forgetAll: -> for k in ['parsed', 'rendered', 'stopped'] @::event(k).oneShot = true bindingRegexp = /^data\-(.*)/ bindingSortOrder = ["renderif", "foreach", "formfor", "context", "bind", "source", "target"] bindingSortPositions = {} bindingSortPositions[name] = pos for name, pos in bindingSortOrder _sortBindings: (a,b) -> aindex = bindingSortPositions[a[0]] bindex = bindingSortPositions[b[0]] aindex ?= bindingSortOrder.length # put unspecified bindings last bindex ?= bindingSortOrder.length if aindex > bindex 1 else if bindex > aindex -1 else if a[0] > b[0] 1 else if b[0] > a[0] -1 else 0 parseNode: (node) -> if @deferEvery && (new Date - @startTime) > @deferEvery @resumeNode = node @timeout = $setImmediate @resume return if node.getAttribute and node.attributes bindings = for attr in node.attributes name = attr.nodeName.match(bindingRegexp)?[1] continue if not name if ~(varIndex = name.indexOf('-')) [name.substr(0, varIndex), name.substr(varIndex + 1), attr.value] else [name, attr.value] for readerArgs in bindings.sort(@_sortBindings) key = readerArgs[1] result = if readerArgs.length == 2 Batman.DOM.readers[readerArgs[0]]?(node, key, @context, @) else Batman.DOM.attrReaders[readerArgs[0]]?(node, key, readerArgs[2], @context, @) if result is false skipChildren = true break else if result instanceof Batman.RenderContext oldContext = @context @context = result $onParseExit(node, => @context = oldContext) if (nextNode = @nextNode(node, skipChildren)) then @parseNode(nextNode) else @finish() nextNode: (node, skipChildren) -> if not skipChildren children = node.childNodes return children[0] if children?.length sibling = node.nextSibling # Grab the reference before onParseExit may remove the node $onParseExit(node).forEach (callback) -> callback() $forgetParseExit(node) return if @node == node return sibling if sibling nextParent = node while nextParent = nextParent.parentNode $onParseExit(nextParent).forEach (callback) -> callback() $forgetParseExit(nextParent) return if @node == nextParent parentSibling = nextParent.nextSibling return parentSibling if parentSibling return # The RenderContext class manages the stack of contexts accessible to a view during rendering. class Batman.RenderContext @deProxy: (object) -> if object? && object.isContextProxy then object.get('proxiedObject') else object @root: -> if Batman.currentApp? Batman.currentApp.get('_renderContext') else @base constructor: (@object, @parent) -> findKey: (key) -> base = key.split('.')[0].split('|')[0].trim() currentNode = @ while currentNode # We define the behaviour of the context stack as latching a get when the first key exists, # so we need to check only if the basekey exists, not if all intermediary keys do as well. val = $get(currentNode.object, base) if typeof val isnt 'undefined' val = $get(currentNode.object, key) return [val, currentNode.object].map(@constructor.deProxy) currentNode = currentNode.parent @windowWrapper ||= window: Batman.container [$get(@windowWrapper, key), @windowWrapper] get: (key) -> @findKey(key)[0] # Below are the three primitives that all the `Batman.DOM` helpers are composed of. # `descend` takes an `object`, and optionally a `scopedKey`. It creates a new `RenderContext` leaf node # in the tree with either the object available on the stack or the object available at the `scopedKey` # on the stack. descend: (object, scopedKey) -> if scopedKey oldObject = object object = new Batman.Object() object[scopedKey] = oldObject return new @constructor(object, @) # `descendWithKey` takes a `key` and optionally a `scopedKey`. It creates a new `RenderContext` leaf node # with the runtime value of the `key` available on the stack or under the `scopedKey` if given. This # differs from a normal `descend` in that it looks up the `key` at runtime (in the parent `RenderContext`) # and will correctly reflect changes if the value at the `key` changes. A normal `descend` takes a concrete # reference to an object which never changes. descendWithKey: (key, scopedKey) -> proxy = new ContextProxy(@, key) return @descend(proxy, scopedKey) # `chain` flattens a `RenderContext`'s path to the root. chain: -> x = [] parent = this while parent x.push parent.object parent = parent.parent x # `ContextProxy` is a simple class which assists in pushing dynamic contexts onto the `RenderContext` tree. # This happens when a `data-context` is descended into, for each iteration in a `data-foreach`, # and in other specific HTML bindings like `data-formfor`. `ContextProxy`s use accessors so that if the # value of the object they proxy changes, the changes will be propagated to any thing observing the `ContextProxy`. # This is good because it allows `data-context` to take keys which will change, filtered keys, and even filters # which take keypath arguments. It will calculate the context to descend into when any of those keys change # because it preserves the property of a binding, and importantly it exposes a friendly `Batman.Object` # interface for the rest of the `Binding` code to work with. @ContextProxy = class ContextProxy extends Batman.Object isContextProxy: true # Reveal the binding's final value. @accessor 'proxiedObject', -> @binding.get('filteredValue') # Proxy all gets to the proxied object. @accessor get: (key) -> @get("proxiedObject.#{key}") set: (key, value) -> @set("proxiedObject.#{key}", value) unset: (key) -> @unset("proxiedObject.#{key}") constructor: (@renderContext, @keyPath, @localKey) -> @binding = new Batman.DOM.AbstractBinding(undefined, @keyPath, @renderContext) Batman.RenderContext.base = new Batman.RenderContext(window: Batman.container) Batman.DOM = { # `Batman.DOM.readers` contains the functions used for binding a node's value or innerHTML, showing/hiding nodes, # and any other `data-#{name}=""` style DOM directives. readers: { target: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'nodeChange') true source: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'dataChange') true bind: (node, key, context, renderer, only) -> bindingClass = false switch node.nodeName.toLowerCase() when 'input' switch node.getAttribute('type') when 'checkbox' Batman.DOM.attrReaders.bind(node, 'checked', key, context, renderer, only) return true when 'radio' bindingClass = Batman.DOM.RadioBinding when 'file' bindingClass = Batman.DOM.FileBinding when 'select' bindingClass = Batman.DOM.SelectBinding bindingClass ||= Batman.DOM.Binding new bindingClass(arguments...) true context: (node, key, context, renderer) -> return context.descendWithKey(key) mixin: (node, key, context, renderer) -> new Batman.DOM.MixinBinding(node, key, context.descend(Batman.mixins), renderer) true showif: (node, key, context, parentRenderer, invert) -> new Batman.DOM.ShowHideBinding(node, key, context, parentRenderer, false, invert) true hideif: -> Batman.DOM.readers.showif(arguments..., yes) route: -> new Batman.DOM.RouteBinding(arguments...) true view: -> new Batman.DOM.ViewBinding arguments... false partial: (node, path, context, renderer) -> Batman.DOM.partial node, path, context, renderer true defineview: (node, name, context, renderer) -> $onParseExit(node, -> $removeNode(node)) Batman.View.store.set(Batman.Navigator.normalizePath(name), node.innerHTML) false renderif: (node, key, context, renderer) -> new Batman.DOM.DeferredRenderingBinding(node, key, context, renderer) false yield: (node, key) -> $setImmediate -> Batman.DOM.yield key, node true contentfor: (node, key) -> $setImmediate -> Batman.DOM.contentFor key, node true replace: (node, key) -> $setImmediate -> Batman.DOM.replace key, node true } _yielders: {} # name/fn pairs of yielding functions _yields: {} # name/container pairs of yielding nodes # `Batman.DOM.attrReaders` contains all the DOM directives which take an argument in their name, in the # `data-dosomething-argument="keypath"` style. This means things like foreach, binding attributes like # disabled or anything arbitrary, descending into a context, binding specific classes, or binding to events. attrReaders: { _parseAttribute: (value) -> if value is 'false' then value = false if value is 'true' then value = true value source: (node, attr, key, context, renderer) -> Batman.DOM.attrReaders.bind node, attr, key, context, renderer, 'dataChange' bind: (node, attr, key, context, renderer, only) -> bindingClass = switch attr when 'checked', 'disabled', 'selected' Batman.DOM.CheckedBinding when 'value', 'href', 'src', 'size' Batman.DOM.NodeAttributeBinding when 'class' Batman.DOM.ClassBinding when 'style' Batman.DOM.StyleBinding else Batman.DOM.AttributeBinding new bindingClass(arguments...) true context: (node, contextName, key, context) -> return context.descendWithKey(key, contextName) event: (node, eventName, key, context) -> new Batman.DOM.EventBinding(arguments...) true addclass: (node, className, key, context, parentRenderer, invert) -> new Batman.DOM.AddClassBinding(node, className, key, context, parentRenderer, false, invert) true removeclass: (node, className, key, context, parentRenderer) -> Batman.DOM.attrReaders.addclass node, className, key, context, parentRenderer, yes foreach: (node, iteratorName, key, context, parentRenderer) -> new Batman.DOM.IteratorBinding(arguments...) false # Return false so the Renderer doesn't descend into this node's children. formfor: (node, localName, key, context) -> new Batman.DOM.FormBinding(arguments...) context.descendWithKey(key, localName) view: (node, bindKey, contextKey, context) -> [_, parent] = context.findKey contextKey view = null parent.observeAndFire contextKey, (newValue) -> view ||= Batman.data node, 'view' view?.set bindKey, newValue } # `Batman.DOM.events` contains the helpers used for binding to events. These aren't called by # DOM directives, but are used to handle specific events by the `data-event-#{name}` helper. events: { click: (node, callback, context, eventName = 'click') -> $addEventListener node, eventName, (args...) -> callback node, args..., context $preventDefault args[0] if node.nodeName.toUpperCase() is 'A' and not node.href node.href = '#' node doubleclick: (node, callback, context) -> # The actual DOM event is called `dblclick` Batman.DOM.events.click node, callback, context, 'dblclick' change: (node, callback, context) -> eventNames = switch node.nodeName.toUpperCase() when 'TEXTAREA' then ['keyup', 'change'] when 'INPUT' if node.type.toLowerCase() in Batman.DOM.textInputTypes oldCallback = callback callback = (e) -> return if e.type == 'keyup' && 13 <= e.keyCode <= 14 oldCallback(arguments...) ['keyup', 'change'] else ['change'] else ['change'] for eventName in eventNames $addEventListener node, eventName, (args...) -> callback node, args..., context isEnter: (ev) -> ev.keyCode is 13 || ev.which is 13 || ev.keyIdentifier is 'Enter' || ev.key is 'Enter' submit: (node, callback, context) -> if Batman.DOM.nodeIsEditable(node) $addEventListener node, 'keydown', (args...) -> if Batman.DOM.events.isEnter(args[0]) Batman.DOM._keyCapturingNode = node $addEventListener node, 'keyup', (args...) -> if Batman.DOM.events.isEnter(args[0]) if Batman.DOM._keyCapturingNode is node $preventDefault args[0] callback node, args..., context Batman.DOM._keyCapturingNode = null else $addEventListener node, 'submit', (args...) -> $preventDefault args[0] callback node, args..., context node other: (node, eventName, callback, context) -> $addEventListener node, eventName, (args...) -> callback node, args..., context } # List of input type="types" for which we can use keyup events to track textInputTypes: ['text', 'search', 'tel', 'url', 'email', 'password'] # `yield` and `contentFor` are used to declare partial views and then pull them in elsewhere. # `replace` is used to replace yielded content. # This can be used for abstraction as well as repetition. yield: (name, node) -> Batman.DOM._yields[name] = node # render any content for this yield if yielders = Batman.DOM._yielders[name] fn(node) for fn in yielders contentFor: (name, node, _replaceContent, _yieldChildren) -> yieldingNode = Batman.DOM._yields[name] # Clone the node if it's a child in case the parent gets cleared during the yield if yieldingNode and $isChildOf(yieldingNode, node) node = $cloneNode node yieldFn = (yieldingNode) -> if _replaceContent || !Batman._data(yieldingNode, 'yielded') $setInnerHTML yieldingNode, '', true Batman.DOM.didRemoveNode(child) for child in yieldingNode.children if _yieldChildren while node.childNodes.length > 0 child = node.childNodes[0] view = Batman.data(child, 'view') view?.fire 'beforeAppear', child $appendChild yieldingNode, node.childNodes[0], true view?.fire 'appear', child else view = Batman.data(node, 'view') view?.fire 'beforeAppear', child $appendChild yieldingNode, node, true view?.fire 'appear', child Batman._data node, 'yielded', true Batman._data yieldingNode, 'yielded', true delete Batman.DOM._yielders[name] if contents = Batman.DOM._yielders[name] contents.push yieldFn else Batman.DOM._yielders[name] = [yieldFn] if yieldingNode Batman.DOM.yield name, yieldingNode replace: (name, node, _yieldChildren) -> Batman.DOM.contentFor name, node, true, _yieldChildren partial: (container, path, context, renderer) -> renderer.prevent 'rendered' view = new Batman.View source: path context: context view.on 'ready', -> $setInnerHTML container, '' # Render the partial content into the data-partial node # Text nodes move when they are appended, so copy childNodes children = (node for node in view.get('node').childNodes) $appendChild(container, child) for child in children renderer.allowAndFire 'rendered' # Adds a binding or binding-like object to the `bindings` set in a node's # data, so that upon node removal we can unset the binding and any other objects # it retains. trackBinding: $trackBinding = (binding, node) -> if bindings = Batman._data node, 'bindings' bindings.add binding else Batman._data node, 'bindings', new Batman.SimpleSet(binding) Batman.DOM.fire('bindingAdded', binding) true # Removes listeners and bindings tied to `node`, allowing it to be cleared # or removed without leaking memory unbindNode: $unbindNode = (node) -> # break down all bindings if bindings = Batman._data node, 'bindings' bindings.forEach (binding) -> binding.die() # remove all event listeners if listeners = Batman._data node, 'listeners' for eventName, eventListeners of listeners eventListeners.forEach (listener) -> $removeEventListener node, eventName, listener # remove all bindings and other data associated with this node Batman.removeData node # external data (Batman.data) Batman.removeData node, undefined, true # internal data (Batman._data) # Unbinds the tree rooted at `node`. # When set to `false`, `unbindRoot` skips the `node` before unbinding all of its children. unbindTree: $unbindTree = (node, unbindRoot = true) -> $unbindNode node if unbindRoot $unbindTree(child) for child in node.childNodes # Copy the event handlers from src node to dst node copyNodeEventListeners: $copyNodeEventListeners = (dst, src) -> if listeners = Batman._data src, 'listeners' for eventName, eventListeners of listeners eventListeners.forEach (listener) -> $addEventListener dst, eventName, listener # Copy all event handlers from the src tree to the dst tree. Note that the # trees must have identical structures. copyTreeEventListeners: $copyTreeEventListeners = (dst, src) -> $copyNodeEventListeners dst, src for i in [0...src.childNodes.length] $copyTreeEventListeners dst.childNodes[i], src.childNodes[i] # Enhance the base cloneNode method to copy event handlers over to the new # instance cloneNode: $cloneNode = (node, deep=true) -> newNode = node.cloneNode(deep) if deep $copyTreeEventListeners newNode, node else $copyNodeEventListeners newNode, node newNode # Memory-safe setting of a node's innerHTML property setInnerHTML: $setInnerHTML = (node, html, args...) -> hide.apply(child, args) for child in node.childNodes when hide = Batman.data(child, 'hide') $unbindTree node, false node?.innerHTML = html setStyleProperty: $setStyleProperty = (node, property, value, importance) -> if node.style.setAttribute node.style.setAttribute(property, value, importance) else node.style.setProperty(property, value, importance) # Memory-safe removal of a node from the DOM removeNode: $removeNode = (node) -> node.parentNode?.removeChild node Batman.DOM.didRemoveNode(node) appendChild: $appendChild = (parent, child, args...) -> view = Batman.data(child, 'view') view?.fire 'beforeAppear', child Batman.data(child, 'show')?.apply(child, args) parent.appendChild(child) view?.fire 'appear', child insertBefore: $insertBefore = (parentNode, newNode, referenceNode = null) -> if !referenceNode or parentNode.childNodes.length <= 0 $appendChild parentNode, newNode else parentNode.insertBefore newNode, referenceNode valueForNode: (node, value = '', escapeValue = true) -> isSetting = arguments.length > 1 switch node.nodeName.toUpperCase() when 'INPUT', 'TEXTAREA' if isSetting then (node.value = value) else node.value when 'SELECT' if isSetting then node.value = value else if isSetting $setInnerHTML node, if escapeValue then $escapeHTML(value) else value else node.innerHTML nodeIsEditable: (node) -> node.nodeName.toUpperCase() in ['INPUT', 'TEXTAREA', 'SELECT'] # `$addEventListener uses attachEvent when necessary addEventListener: $addEventListener = (node, eventName, callback) -> # store the listener in Batman.data unless listeners = Batman._data node, 'listeners' listeners = Batman._data node, 'listeners', {} unless listeners[eventName] listeners[eventName] = new Batman.Set listeners[eventName].add callback if $hasAddEventListener node.addEventListener eventName, callback, false else node.attachEvent "on#{eventName}", callback # `$removeEventListener` uses detachEvent when necessary removeEventListener: $removeEventListener = (node, eventName, callback) -> # remove the listener from Batman.data if listeners = Batman._data node, 'listeners' if eventListeners = listeners[eventName] eventListeners.remove callback if $hasAddEventListener node.removeEventListener eventName, callback, false else node.detachEvent 'on'+eventName, callback hasAddEventListener: $hasAddEventListener = !!window?.addEventListener didRemoveNode: (node) -> view = Batman.data node, 'view' view?.fire 'beforeDisappear', node $unbindTree node view?.fire 'disappear', node onParseExit: $onParseExit = (node, callback) -> set = Batman._data(node, 'onParseExit') || Batman._data(node, 'onParseExit', new Batman.SimpleSet) set.add callback if callback? set forgetParseExit: $forgetParseExit = (node, callback) -> Batman.removeData(node, 'onParseExit', true) } $mixin Batman.DOM, Batman.EventEmitter, Batman.Observable Batman.DOM.event('bindingAdded') # Bindings are shortlived objects which manage the observation of any keypaths a `data` attribute depends on. # Bindings parse any keypaths which are filtered and use an accessor to apply the filters, and thus enjoy # the automatic trigger and dependency system that Batman.Objects use. Every, and I really mean every method # which uses filters has to be defined in terms of a new binding. This is so that the proper order of # objects is traversed and any observers are properly attached. class Batman.DOM.AbstractBinding extends Batman.Object # A beastly regular expression for pulling keypaths out of the JSON arguments to a filter. # It makes the following matches: # # + `foo` and `baz.qux` in `foo, "bar", baz.qux` # + `foo.bar.baz` in `true, false, "true", "false", foo.bar.baz` # + `true.bar` in `2, true.bar` # + `truesay` in truesay # + no matches in `"bar", 2, {"x":"y", "Z": foo.bar.baz}, "baz"` keypath_rx = /// (^|,) # Match either the start of an arguments list or the start of a space inbetween commas. \s* # Be insensitive to whitespace between the comma and the actual arguments. (?! # Use a lookahead to ensure we aren't matching true or false: (?:true|false) # Match either true or false ... \s* # and make sure that there's nothing else that comes after the true or false ... (?:$|,) # before the end of this argument in the list. ) ( [a-zA-Z][\w\.]* # Now that true and false can't be matched, match a dot delimited list of keys. [\?\!]? # Allow ? and ! at the end of a keypath to support Ruby's methods ) \s* # Be insensitive to whitespace before the next comma or end of the filter arguments list. (?=$|,) # Match either the next comma or the end of the filter arguments list. ///g # A less beastly pair of regular expressions for pulling out the [] syntax `get`s in a binding string, and # dotted names that follow them. get_dot_rx = /(?:\]\.)(.+?)(?=[\[\.]|\s*\||$)/ get_rx = /(?!^\s*)\[(.*?)\]/g # The `filteredValue` which calculates the final result by reducing the initial value through all the filters. @accessor 'filteredValue' get: -> unfilteredValue = @get('unfilteredValue') self = @ renderContext = @get('renderContext') if @filterFunctions.length > 0 developer.currentFilterStack = renderContext result = @filterFunctions.reduce((value, fn, i) -> # Get any argument keypaths from the context stored at parse time. args = self.filterArguments[i].map (argument) -> if argument._keypath self.renderContext.get(argument._keypath) else argument # Apply the filter. args.unshift value args.push self fn.apply(renderContext, args) , unfilteredValue) developer.currentFilterStack = null result else unfilteredValue # We ignore any filters for setting, because they often aren't reversible. set: (_, newValue) -> @set('unfilteredValue', newValue) # The `unfilteredValue` is whats evaluated each time any dependents change. @accessor 'unfilteredValue' get: -> # If we're working with an `@key` and not an `@value`, find the context the key belongs to so we can # hold a reference to it for passing to the `dataChange` and `nodeChange` observers. if k = @get('key') Batman.RenderContext.deProxy(@get("keyContext.#{k}")) else @get('value') set: (_, value) -> if k = @get('key') keyContext = @get('keyContext') # Supress sets on the window if keyContext != Batman.container @set("keyContext.#{k}", value) else @set('value', value) # The `keyContext` accessor is @accessor 'keyContext', -> @renderContext.findKey(@key)[1] bindImmediately: true shouldSet: true isInputBinding: false escapeValue: true constructor: (@node, @keyPath, @renderContext, @renderer, @only = false) -> # Pull out the `@key` and filter from the `@keyPath`. @parseFilter() # Observe the node and the data. @bind() if @bindImmediately isTwoWay: -> @key? && @filterFunctions.length is 0 bind: -> # Attach the observers. if @node? && @only in [false, 'nodeChange'] and Batman.DOM.nodeIsEditable(@node) Batman.DOM.events.change @node, @_fireNodeChange, @renderContext # Usually, we let the HTML value get updated upon binding by `observeAndFire`ing the dataChange # function below. When dataChange isn't attached, we update the JS land value such that the # sync between DOM and JS is maintained. if @only is 'nodeChange' @_fireNodeChange() # Observe the value of this binding's `filteredValue` and fire it immediately to update the node. if @only in [false, 'dataChange'] @observeAndFire 'filteredValue', @_fireDataChange Batman.DOM.trackBinding(@, @node) if @node? _fireNodeChange: => @shouldSet = false @nodeChange?(@node, @value || @get('keyContext')) @shouldSet = true _fireDataChange: (value) => if @shouldSet @dataChange?(value, @node) die: -> @forget() @_batman.properties?.forEach (key, property) -> property.die() parseFilter: -> # Store the function which does the filtering and the arguments (all except the actual value to apply the # filter to) in these arrays. @filterFunctions = [] @filterArguments = [] # Rewrite [] style gets, replace quotes to be JSON friendly, and split the string by pipes to see if there are any filters. keyPath = @keyPath keyPath = keyPath.replace(get_dot_rx, "]['$1']") while get_dot_rx.test(keyPath) # Stupid lack of lookbehind assertions... filters = keyPath.replace(get_rx, " | get $1 ").replace(/'/g, '"').split(/(?!")\s+\|\s+(?!")/) # The key will is always the first token before the pipe. try key = @parseSegment(orig = filters.shift())[0] catch e developer.warn e developer.error "Error! Couldn't parse keypath in \"#{orig}\". Parsing error above." if key and key._keypath @key = key._keypath else @value = key if filters.length while filterString = filters.shift() # For each filter, get the name and the arguments by splitting on the first space. split = filterString.indexOf(' ') if ~split filterName = filterString.substr(0, split) args = filterString.substr(split) else filterName = filterString # If the filter exists, grab it. if filter = Batman.Filters[filterName] @filterFunctions.push filter # Get the arguments for the filter by parsing the args as JSON, or # just pushing an placeholder array if args try @filterArguments.push @parseSegment(args) catch e developer.error "Bad filter arguments \"#{args}\"!" else @filterArguments.push [] else developer.error "Unrecognized filter '#{filterName}' in key \"#{@keyPath}\"!" true # Turn a piece of a `data` keypath into a usable javascript object. # + replacing keypaths using the above regular expression # + wrapping the `,` delimited list in square brackets # + and `JSON.parse`ing them as an array. parseSegment: (segment) -> JSON.parse( "[" + segment.replace(keypath_rx, "$1{\"_keypath\": \"$2\"}") + "]" ) class Batman.DOM.AbstractAttributeBinding extends Batman.DOM.AbstractBinding constructor: (node, @attributeName, args...) -> super(node, args...) class Batman.DOM.AbstractCollectionBinding extends Batman.DOM.AbstractAttributeBinding bindCollection: (newCollection) -> unless newCollection == @collection @unbindCollection() @collection = newCollection if @collection if @collection.isObservable && @collection.toArray @collection.observe 'toArray', @handleArrayChanged else if @collection.isEventEmitter @collection.on 'itemsWereAdded', @handleItemsWereAdded @collection.on 'itemsWereRemoved', @handleItemsWereRemoved else return false return true return false unbindCollection: -> if @collection if @collection.isObservable && @collection.toArray @collection.forget('toArray', @handleArrayChanged) else if @collection.isEventEmitter @collection.event('itemsWereAdded').removeHandler(@handleItemsWereAdded) @collection.event('itemsWereRemoved').removeHandler(@handleItemsWereRemoved) handleItemsWereAdded: -> handleItemsWereRemoved: -> handleArrayChanged: -> die: -> @unbindCollection() super class Batman.DOM.Binding extends Batman.DOM.AbstractBinding constructor: (node) -> @isInputBinding = node.nodeName.toLowerCase() in ['input', 'textarea'] super nodeChange: (node, context) -> if @isTwoWay() @set 'filteredValue', @node.value dataChange: (value, node) -> Batman.DOM.valueForNode @node, value, @escapeValue class Batman.DOM.AttributeBinding extends Batman.DOM.AbstractAttributeBinding dataChange: (value) -> @node.setAttribute(@attributeName, value) nodeChange: (node) -> if @isTwoWay() @set 'filteredValue', Batman.DOM.attrReaders._parseAttribute(node.getAttribute(@attributeName)) class Batman.DOM.NodeAttributeBinding extends Batman.DOM.AbstractAttributeBinding dataChange: (value = "") -> @node[@attributeName] = value nodeChange: (node) -> if @isTwoWay() @set 'filteredValue', Batman.DOM.attrReaders._parseAttribute(node[@attributeName]) class Batman.DOM.ShowHideBinding extends Batman.DOM.AbstractBinding constructor: (node, className, key, context, parentRenderer, @invert = false) -> display = node.style.display display = '' if not display or display is 'none' @originalDisplay = display super dataChange: (value) -> view = Batman.data @node, 'view' if !!value is not @invert view?.fire 'beforeAppear', @node Batman.data(@node, 'show')?.call(@node) @node.style.display = @originalDisplay view?.fire 'appear', @node else view?.fire 'beforeDisappear', @node if typeof (hide = Batman.data(@node, 'hide')) is 'function' hide.call @node else $setStyleProperty(@node, 'display', 'none', 'important') view?.fire 'disappear', @node class Batman.DOM.CheckedBinding extends Batman.DOM.NodeAttributeBinding isInputBinding: true dataChange: (value) -> @node[@attributeName] = !!value # Update the parent's binding if necessary if @node.parentNode Batman._data(@node.parentNode, 'updateBinding')?() constructor: -> super # Attach this binding to the node under the attribute name so that parent # bindings can query this binding and modify its state. This is useful # for <options> within a select or radio buttons. Batman._data @node, @attributeName, @ class Batman.DOM.ClassBinding extends Batman.DOM.AbstractCollectionBinding dataChange: (value) -> if value? @unbindCollection() if typeof value is 'string' @node.className = value else @bindCollection(value) @updateFromCollection() updateFromCollection: -> if @collection array = if @collection.map @collection.map((x) -> x) else (k for own k,v of @collection) array = array.toArray() if array.toArray? @node.className = array.join ' ' handleArrayChanged: => @updateFromCollection() handleItemsWereRemoved: => @updateFromCollection() handleItemsWereAdded: => @updateFromCollection() class Batman.DOM.DeferredRenderingBinding extends Batman.DOM.AbstractBinding rendered: false constructor: -> super @node.removeAttribute "data-renderif" nodeChange: -> dataChange: (value) -> if value && !@rendered @render() render: -> new Batman.Renderer(@node, null, @renderContext) @rendered = true class Batman.DOM.AddClassBinding extends Batman.DOM.AbstractAttributeBinding constructor: (node, className, keyPath, renderContext, renderer, only, @invert = false) -> names = className.split('|') @classes = for name in names { name: name pattern: new RegExp("(?:^|\\s)#{name}(?:$|\\s)", 'i') } super delete @attributeName dataChange: (value) -> currentName = @node.className for {name, pattern} in @classes includesClassName = pattern.test(currentName) if !!value is !@invert @node.className = "#{currentName} #{name}" if !includesClassName else @node.className = currentName.replace(pattern, '') if includesClassName true class Batman.DOM.EventBinding extends Batman.DOM.AbstractAttributeBinding bindImmediately: false constructor: (node, eventName, key, context) -> super confirmText = @node.getAttribute('data-confirm') callback = => return if confirmText and not confirm(confirmText) @get('filteredValue')?.apply @get('callbackContext'), arguments if attacher = Batman.DOM.events[@attributeName] attacher @node, callback, context else Batman.DOM.events.other @node, @attributeName, callback, context @accessor 'callbackContext', -> contextKeySegments = @key.split('.') contextKeySegments.pop() if contextKeySegments.length > 0 @get('keyContext').get(contextKeySegments.join('.')) else @get('keyContext') class Batman.DOM.RadioBinding extends Batman.DOM.AbstractBinding isInputBinding: true dataChange: (value) -> # don't overwrite `checked` attributes in the HTML unless a bound # value is defined in the context. if no bound value is found, bind # to the key if the node is checked. if (boundValue = @get('filteredValue'))? @node.checked = boundValue == @node.value else if @node.checked @set 'filteredValue', @node.value nodeChange: (node) -> if @isTwoWay() @set('filteredValue', Batman.DOM.attrReaders._parseAttribute(node.value)) class Batman.DOM.FileBinding extends Batman.DOM.AbstractBinding isInputBinding: true nodeChange: (node, subContext) -> return if !@isTwoWay() segments = @key.split('.') if segments.length > 1 keyContext = subContext.get(segments.slice(0, -1).join('.')) else keyContext = subContext actualObject = Batman.RenderContext.deProxy(keyContext) if actualObject.hasStorage && actualObject.hasStorage() for adapter in actualObject._batman.get('storage') when adapter instanceof Batman.RestStorage adapter.defaultRequestOptions.formData = true if node.hasAttribute('multiple') @set 'filteredValue', Array::slice.call(node.files) else @set 'filteredValue', node.files[0] class Batman.DOM.MixinBinding extends Batman.DOM.AbstractBinding dataChange: (value) -> $mixin @node, value if value? class Batman.DOM.SelectBinding extends Batman.DOM.AbstractBinding isInputBinding: true bindImmediately: false firstBind: true constructor: -> super # wait for the select to render before binding to it @renderer.on 'rendered', => if @node? Batman._data @node, 'updateBinding', @updateSelectBinding @bind() dataChange: (newValue) => # For multi-select boxes, the `value` property only holds the first # selection, so go through the child options and update as necessary. if newValue instanceof Array # Use a hash to map values to their nodes to avoid O(n^2). valueToChild = {} for child in @node.children # Clear all options. child.selected = false # Avoid collisions among options with same values. matches = valueToChild[child.value] if matches then matches.push child else matches = [child] valueToChild[child.value] = matches # Select options corresponding to the new values for value in newValue for match in valueToChild[value] match.selected = yes # For a regular select box, update the value. else if typeof newValue is 'undefined' && @firstBind @firstBind = false @set('unfilteredValue', @node.value) else Batman.DOM.valueForNode(@node, newValue, @escapeValue) # Finally, update the options' `selected` bindings @updateOptionBindings() nodeChange: => if @isTwoWay() @updateSelectBinding() @updateOptionBindings() updateSelectBinding: => # Gather the selected options and update the binding selections = if @node.multiple then (c.value for c in @node.children when c.selected) else @node.value selections = selections[0] if typeof selections is Array && selections.length == 1 @set 'unfilteredValue', selections true updateOptionBindings: => # Go through the option nodes and update their bindings using the # context and key attached to the node via Batman.data for child in @node.children if selectedBinding = Batman._data(child, 'selected') selectedBinding.nodeChange(selectedBinding.node) true class Batman.DOM.StyleBinding extends Batman.DOM.AbstractCollectionBinding class @SingleStyleBinding extends Batman.DOM.AbstractAttributeBinding constructor: (args..., @parent) -> super(args...) dataChange: (value) -> @parent.setStyle(@attributeName, value) constructor: -> @oldStyles = {} super dataChange: (value) -> unless value @reapplyOldStyles() return @unbindCollection() if typeof value is 'string' @reapplyOldStyles() for style in value.split(';') # handle a case when css value contains colons itself (absolute URI) # split and rejoin because IE7/8 don't splice values of capturing regexes into split's return array [cssName, colonSplitCSSValues...] = style.split(":") @setStyle cssName, colonSplitCSSValues.join(":") return if value instanceof Batman.Hash if @bindCollection(value) value.forEach (key, value) => @setStyle key, value else if value instanceof Object @reapplyOldStyles() for own key, keyValue of value # Check whether the value is an existing keypath, and if so bind this attribute to it [keypathValue, keypathContext] = @renderContext.findKey(keyValue) if keypathValue @bindSingleAttribute key, keyValue @setStyle key, keypathValue else @setStyle key, keyValue handleItemsWereAdded: (newKey) => @setStyle newKey, @collection.get(newKey); return handleItemsWereRemoved: (oldKey) => @setStyle oldKey, ''; return bindSingleAttribute: (attr, keyPath) -> new @constructor.SingleStyleBinding(@node, attr, keyPath, @renderContext, @renderer, @only, @) setStyle: (key, value) => return unless key key = helpers.camelize(key.trim(), true) @oldStyles[key] = @node.style[key] @node.style[key] = if value then value.trim() else "" reapplyOldStyles: -> @setStyle(cssName, cssValue) for own cssName, cssValue of @oldStyles class Batman.DOM.RouteBinding extends Batman.DOM.AbstractBinding onATag: false @accessor 'dispatcher', -> @renderContext.get('dispatcher') || Batman.App.get('current.dispatcher') bind: -> if @node.nodeName.toUpperCase() is 'A' @onATag = true super Batman.DOM.events.click @node, => params = @pathFromValue(@get('filteredValue')) Batman.redirect params if params? dataChange: (value) -> if value? path = @pathFromValue(value) if @onATag if path? path = Batman.navigator.linkTo path else path = "#" @node.href = path pathFromValue: (value) -> if value.isNamedRouteQuery value.get('path') else @get('dispatcher')?.pathFromParams(value) class Batman.DOM.ViewBinding extends Batman.DOM.AbstractBinding constructor: -> super @renderer.prevent 'rendered' @node.removeAttribute 'data-view' dataChange: (viewClassOrInstance) -> return unless viewClassOrInstance? if viewClassOrInstance.isView @view = viewClassOrInstance @view.set 'node', @node @view.set 'context', @renderContext else @view = new viewClassOrInstance node: @node context: @renderContext parentView: @renderContext.findKey('isView')?[1] Batman.data @node, 'view', @view @view.on 'ready', => @view.awakeFromHTML? @node @view.fire 'beforeAppear', @node @renderer.allowAndFire 'rendered' @view.fire 'appear', @node @die() class Batman.DOM.FormBinding extends Batman.DOM.AbstractAttributeBinding @current: null errorClass: 'error' defaultErrorsListSelector: 'div.errors' @accessor 'errorsListSelector', -> @get('node').getAttribute('data-errors-list') || @defaultErrorsListSelector constructor: (node, contextName, keyPath, renderContext, renderer, only) -> super @contextName = contextName delete @attributeName Batman.DOM.events.submit @get('node'), (node, e) -> $preventDefault e Batman.DOM.on 'bindingAdded', @bindingWasAdded @setupErrorsList() bindingWasAdded: (binding) => if binding.isInputBinding && $isChildOf(@get('node'), binding.get('node')) if ~(index = binding.get('key').indexOf(@contextName)) # If the binding is to a key on the thing passed to formfor node = binding.get('node') field = binding.get('key').slice(index + @contextName.length + 1) # Slice off up until the context and the following dot new Batman.DOM.AddClassBinding(node, @errorClass, @get('keyPath') + " | get 'errors.#{field}.length'", @renderContext, @renderer) setupErrorsList: -> if @errorsListNode = @get('node').querySelector?(@get('errorsListSelector')) $setInnerHTML @errorsListNode, @errorsListHTML() unless @errorsListNode.getAttribute 'data-showif' @errorsListNode.setAttribute 'data-showif', "#{@contextName}.errors.length" errorsListHTML: -> """ <ul> <li data-foreach-error="#{@contextName}.errors" data-bind="error.attribute | append ' ' | append error.message"></li> </ul> """ die: -> Batman.DOM.forget 'bindingAdded', @bindingWasAdded super class Batman.DOM.IteratorBinding extends Batman.DOM.AbstractCollectionBinding deferEvery: 50 currentActionNumber: 0 queuedActionNumber: 0 bindImmediately: false constructor: (sourceNode, @iteratorName, @key, @context, @parentRenderer) -> @nodeMap = new Batman.SimpleHash @actionMap = new Batman.SimpleHash @rendererMap = new Batman.SimpleHash @actions = [] @prototypeNode = sourceNode.cloneNode(true) @prototypeNode.removeAttribute "data-foreach-#{@iteratorName}" @pNode = sourceNode.parentNode previousSiblingNode = sourceNode.nextSibling @siblingNode = document.createComment "end #{@iteratorName}" @siblingNode[Batman.expando] = sourceNode[Batman.expando] delete sourceNode[Batman.expando] if Batman.canDeleteExpando $insertBefore sourceNode.parentNode, @siblingNode, previousSiblingNode # Remove the original node once the parent has moved past it. @parentRenderer.on 'parsed', => # Move any Batman._data from the sourceNode to the sibling; we need to # retain the bindings, and we want to dispose of the node. $removeNode sourceNode # Attach observers. @bind() # Don't let the parent emit its rendered event until all the children have. # This `prevent`'s matching allow is run once the queue is empty in `processActionQueue`. @parentRenderer.prevent 'rendered' # Tie this binding to a node using the default behaviour in the AbstractBinding super(@siblingNode, @iteratorName, @key, @context, @parentRenderer) @fragment = document.createDocumentFragment() parentNode: -> @siblingNode.parentNode die: -> super @dead = true unbindCollection: -> if @collection @nodeMap.forEach (item) => @cancelExistingItem(item) super dataChange: (newCollection) -> if @collection != newCollection @removeAll() @bindCollection(newCollection) # Unbinds the old collection as well. if @collection if @collection.toArray @handleArrayChanged() else if @collection.forEach @collection.forEach (item) => @addOrInsertItem(item) else @addOrInsertItem(key) for own key, value of @collection else developer.warn "Warning! data-foreach-#{@iteratorName} called with an undefined binding. Key was: #{@key}." @processActionQueue() handleItemsWereAdded: (items...) => @addOrInsertItem(item, {fragment: false}) for item in items; return handleItemsWereRemoved: (items...) => @removeItem(item) for item in items; return handleArrayChanged: => newItemsInOrder = @collection.toArray() nodesToRemove = (new Batman.SimpleHash).merge(@nodeMap) for item in newItemsInOrder @addOrInsertItem(item, {fragment: false}) nodesToRemove.unset(item) nodesToRemove.forEach (item, node) => @removeItem(item) addOrInsertItem: (item, options = {}) -> existingNode = @nodeMap.get(item) if existingNode @insertItem(item, existingNode) else @addItem(item, options) addItem: (item, options = {fragment: true}) -> @parentRenderer.prevent 'rendered' # Remove any renderers in progress or actions lined up for an item, since we now know # this item belongs at the end of the queue. @cancelExistingItemActions(item) if @actionMap.get(item)? self = @ options.actionNumber = @queuedActionNumber++ # Render out the child in the custom context, and insert it once the render has completed the parse. childRenderer = new Batman.Renderer @_nodeForItem(item), (-> self.rendererMap.unset(item) self.insertItem(item, @node, options) ), @renderContext.descend(item, @iteratorName) @rendererMap.set(item, childRenderer) finish = => return if @dead @parentRenderer.allowAndFire 'rendered' childRenderer.on 'rendered', finish childRenderer.on 'stopped', => return if @dead @actions[options.actionNumber] = false finish() @processActionQueue() item removeItem: (item) -> return if @dead || !item? oldNode = @nodeMap.unset(item) @cancelExistingItem(item) if oldNode if hideFunction = Batman.data oldNode, 'hide' hideFunction.call(oldNode) else $removeNode(oldNode) removeAll: -> @nodeMap.forEach (item) => @removeItem(item) insertItem: (item, node, options = {}) -> return if @dead if !options.actionNumber? options.actionNumber = @queuedActionNumber++ existingActionNumber = @actionMap.get(item) if existingActionNumber > options.actionNumber # Another action for this item is scheduled for the future, do it then instead of now. Actions # added later enforce order, so we make this one a noop and let the later one have its proper effects. @actions[options.actionNumber] = -> else # Another action has been scheduled for this item. It hasn't been done yet because # its in the actionmap, but this insert is scheduled to happen after it. Skip it since its now defunct. if existingActionNumber @cancelExistingItemActions(item) # Update the action number map to now reflect this new action which will go on the end of the queue. @actionMap.set item, options.actionNumber @actions[options.actionNumber] = -> show = Batman.data node, 'show' if typeof show is 'function' show.call node, before: @siblingNode else if options.fragment @fragment.appendChild node else $insertBefore @parentNode(), node, @siblingNode if addItem = node.getAttribute 'data-additem' [_, context] = @renderer.context.findKey addItem context?[addItem]?(item, node) @actions[options.actionNumber].item = item @processActionQueue() cancelExistingItem: (item) -> @cancelExistingItemActions(item) @cancelExistingItemRender(item) cancelExistingItemActions: (item) -> oldActionNumber = @actionMap.get(item) # Only remove actions which haven't been completed yet. if oldActionNumber? && oldActionNumber >= @currentActionNumber @actions[oldActionNumber] = false @actionMap.unset item cancelExistingItemRender: (item) -> oldRenderer = @rendererMap.get(item) if oldRenderer oldRenderer.stop() $removeNode(oldRenderer.node) @rendererMap.unset item processActionQueue: -> return if @dead unless @actionQueueTimeout # Prevent the parent which will then be allowed when the timeout actually runs @actionQueueTimeout = $setImmediate => return if @dead delete @actionQueueTimeout startTime = new Date while (f = @actions[@currentActionNumber])? delete @actions[@currentActionNumber] @actionMap.unset f.item f.call(@) if f @currentActionNumber++ if @deferEvery && (new Date - startTime) > @deferEvery return @processActionQueue() if @fragment && @rendererMap.length is 0 && @fragment.hasChildNodes() $insertBefore @parentNode(), @fragment, @siblingNode @fragment = document.createDocumentFragment() if @currentActionNumber == @queuedActionNumber @parentRenderer.allowAndFire 'rendered' _nodeForItem: (item) -> newNode = @prototypeNode.cloneNode(true) @nodeMap.set(item, newNode) newNode # Filters # ------- # # `Batman.Filters` contains the simple, determininistic tranforms used in view bindings to # make life a little easier. buntUndefined = (f) -> (value) -> if typeof value is 'undefined' undefined else f.apply(@, arguments) filters = Batman.Filters = raw: buntUndefined (value, binding) -> binding.escapeValue = false value get: buntUndefined (value, key) -> if value.get? value.get(key) else value[key] equals: buntUndefined (lhs, rhs, binding) -> lhs is rhs not: (value, binding) -> ! !!value matches: buntUndefined (value, searchFor) -> value.indexOf(searchFor) isnt -1 truncate: buntUndefined (value, length, end = "...", binding) -> if !binding binding = end end = "..." if value.length > length value = value.substr(0, length-end.length) + end value default: (value, string, binding) -> value || string prepend: (value, string, binding) -> string + value append: (value, string, binding) -> value + string replace: buntUndefined (value, searchFor, replaceWith, flags, binding) -> if !binding binding = flags flags = undefined # Work around FF issue, "foo".replace("foo","bar",undefined) throws an error if flags is undefined value.replace searchFor, replaceWith else value.replace searchFor, replaceWith, flags downcase: buntUndefined (value) -> value.toLowerCase() upcase: buntUndefined (value) -> value.toUpperCase() pluralize: buntUndefined (string, count) -> helpers.pluralize(count, string) join: buntUndefined (value, withWhat = '', binding) -> if !binding binding = withWhat withWhat = '' value.join(withWhat) sort: buntUndefined (value) -> value.sort() map: buntUndefined (value, key) -> value.map((x) -> $get(x, key)) has: (set, item) -> return false unless set? Batman.contains(set, item) first: buntUndefined (value) -> value[0] meta: buntUndefined (value, keypath) -> developer.assert value.meta, "Error, value doesn't have a meta to filter on!" value.meta.get(keypath) interpolate: (string, interpolationKeypaths, binding) -> if not binding binding = interpolationKeypaths interpolationKeypaths = undefined return if not string values = {} for k, v of interpolationKeypaths values[k] = @findKey(v)[0] if !values[k]? Batman.developer.warn "Warning! Undefined interpolation key #{k} for interpolation", string values[k] = '' Batman.helpers.interpolate(string, values) # allows you to curry arguments to a function via a filter withArguments: (block, curryArgs..., binding) -> return if not block return (regularArgs...) -> block.call @, curryArgs..., regularArgs... routeToAction: buntUndefined (model, action) -> params = Batman.Dispatcher.paramsFromArgument(model) params.action = action params escape: buntUndefined($escapeHTML) for k in ['capitalize', 'singularize', 'underscore', 'camelize'] filters[k] = buntUndefined helpers[k] developer.addFilters() # Data # ---- $mixin Batman, cache: {} uuid: 0 expando: "batman" + Math.random().toString().replace(/\D/g, '') # Test to see if it's possible to delete an expando from an element # Fails in Internet Explorer canDeleteExpando: try div = document.createElement 'div' delete div.test catch e Batman.canDeleteExpando = false noData: # these throw exceptions if you attempt to add expandos to them "embed": true, # Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true hasData: (elem) -> elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando]) !!elem and !isEmptyDataObject(elem) data: (elem, name, data, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando getByName = typeof name == "string" cache = Batman.cache # Only defining an ID for JS objects if its cache already exists allows # the code to shortcut on the same path as a DOM node with no cache id = elem[Batman.expando] # Avoid doing any more work than we need to when trying to get data on an # object that has no data at all if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined return unless id # Also check that it's not a text node; IE can't set expandos on them if elem.nodeType isnt 3 elem[Batman.expando] = id = ++Batman.uuid else id = Batman.expando cache[id] = {} unless cache[id] # An object can be passed to Batman._data instead of a key/value pair; this gets # shallow copied over onto the existing cache if typeof name == "object" or typeof name == "function" if pvt cache[id][internalKey] = $mixin(cache[id][internalKey], name) else cache[id] = $mixin(cache[id], name) thisCache = cache[id] # Internal Batman data is stored in a separate object inside the object's data # cache in order to avoid key collisions between internal data and user-defined # data if pvt thisCache[internalKey] ||= {} thisCache = thisCache[internalKey] if data != undefined thisCache[name] = data # Check for both converted-to-camel and non-converted data property names # If a data property was specified if getByName # First try to find as-is property data ret = thisCache[name] else ret = thisCache return ret removeData: (elem, name, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando isNode = elem.nodeType # non DOM-nodes have their data attached directly cache = Batman.cache id = elem[Batman.expando] # If there is already no cache entry for this object, there is no # purpose in continuing return unless cache[id] if name thisCache = if pvt then cache[id][internalKey] else cache[id] if thisCache # Support interoperable removal of hyphenated or camelcased keys delete thisCache[name] # If there is no data left in the cache, we want to continue # and let the cache object itself get destroyed return unless isEmptyDataObject(thisCache) if pvt delete cache[id][internalKey] # Don't destroy the parent cache unless the internal data object # had been the only thing left in it return unless isEmptyDataObject(cache[id]) internalCache = cache[id][internalKey] # Browsers that fail expando deletion also refuse to delete expandos on # the window, but it will allow it on all other JS objects; other browsers # don't care # Ensure that `cache` is not a window object if Batman.canDeleteExpando or !cache.setInterval delete cache[id] else cache[id] = null # We destroyed the entire user cache at once because it's faster than # iterating through each key, but we need to continue to persist internal # data if it existed if internalCache cache[id] = {} cache[id][internalKey] = internalCache # Otherwise, we need to eliminate the expando on the node to avoid # false lookups in the cache for entries that no longer exist else if Batman.canDeleteExpando delete elem[Batman.expando] else if elem.removeAttribute elem.removeAttribute Batman.expando else elem[Batman.expando] = null # For internal use only _data: (elem, name, data) -> Batman.data elem, name, data, true # A method for determining if a DOM node can handle the data expando acceptData: (elem) -> if elem.nodeName match = Batman.noData[elem.nodeName.toLowerCase()] if match return !(match == true or elem.getAttribute("classid") != match) return true isEmptyDataObject = (obj) -> for name of obj return false return true # Mixins # ------ mixins = Batman.mixins = new Batman.Object() # Encoders # ------ Batman.Encoders = {} class Batman.Paginator extends Batman.Object class @Range constructor: (@offset, @limit) -> @reach = offset + limit coversOffsetAndLimit: (offset, limit) -> offset >= @offset and (offset + limit) <= @reach class @Cache extends @Range constructor: (@offset, @limit, @items) -> super @length = items.length itemsForOffsetAndLimit: (offset, limit) -> begin = offset-@offset end = begin + limit if begin < 0 padding = new Array(-begin) begin = 0 slice = @items.slice(begin, end) if padding padding.concat(slice) else slice offset: 0 limit: 10 totalCount: 0 markAsLoadingOffsetAndLimit: (offset, limit) -> @loadingRange = new Batman.Paginator.Range(offset, limit) markAsFinishedLoading: -> delete @loadingRange offsetFromPageAndLimit: (page, limit) -> Math.round((+page - 1) * limit) pageFromOffsetAndLimit: (offset, limit) -> offset / limit + 1 _load: (offset, limit) -> return if @loadingRange?.coversOffsetAndLimit(offset, limit) @markAsLoadingOffsetAndLimit(offset, limit) @loadItemsForOffsetAndLimit(offset, limit) toArray: -> cache = @get('cache') offset = @get('offset') limit = @get('limit') @_load(offset, limit) unless cache?.coversOffsetAndLimit(offset, limit) cache?.itemsForOffsetAndLimit(offset, limit) or [] page: -> @pageFromOffsetAndLimit(@get('offset'), @get('limit')) pageCount: -> Math.ceil(@get('totalCount') / @get('limit')) previousPage: -> @set('page', @get('page')-1) nextPage: -> @set('page', @get('page')+1) loadItemsForOffsetAndLimit: (offset, limit) -> # override on subclasses or instances updateCache: (offset, limit, items) -> cache = new Batman.Paginator.Cache(offset, limit, items) return if @loadingRange? and not cache.coversOffsetAndLimit(@loadingRange.offset, @loadingRange.limit) @markAsFinishedLoading() @set('cache', cache) @accessor 'toArray', @::toArray @accessor 'offset', 'limit', 'totalCount' get: Batman.Property.defaultAccessor.get set: (key, value) -> Batman.Property.defaultAccessor.set.call(this, key, +value) @accessor 'page', get: @::page set: (_,value) -> value = +value @set('offset', @offsetFromPageAndLimit(value, @get('limit'))) value @accessor 'pageCount', @::pageCount class Batman.ModelPaginator extends Batman.Paginator cachePadding: 0 paddedOffset: (offset) -> offset -= @cachePadding if offset < 0 then 0 else offset paddedLimit: (limit) -> limit + @cachePadding * 2 loadItemsForOffsetAndLimit: (offset, limit) -> params = @paramsForOffsetAndLimit(offset, limit) params[k] = v for k,v of @params @model.load params, (err, records) => if err? @markAsFinishedLoading() @fire('error', err) else @updateCache(@offsetFromParams(params), @limitFromParams(params), records) # override these to fetch records however you like: paramsForOffsetAndLimit: (offset, limit) -> offset: @paddedOffset(offset), limit: @paddedLimit(limit) offsetFromParams: (params) -> params.offset limitFromParams: (params) -> params.limit # Support AMD loaders if typeof define is 'function' define 'batman', [], -> Batman # Optionally export global sugar. Not sure what to do with this. Batman.exportHelpers = (onto) -> for k in ['mixin', 'unmixin', 'route', 'redirect', 'typeOf', 'redirect', 'setImmediate'] onto["$#{k}"] = Batman[k] onto Batman.exportGlobals = () -> Batman.exportHelpers(Batman.container)
60733
# # batman.js # # Created by <NAME> # Copyright 2011, Shopify # # The global namespace, the `Batman` function will also create also create a new # instance of Batman.Object and mixin all arguments to it. Batman = (mixins...) -> new Batman.Object mixins... Batman.version = '0.8.0' Batman.config = pathPrefix: '/' usePushState: no Batman.container = if exports? module.exports = Batman global else window.Batman = Batman window # Global Helpers # ------- # `$typeOf` returns a string that contains the built-in class of an object # like `String`, `Array`, or `Object`. Note that only `Object` will be returned for # the entire prototype chain. Batman.typeOf = $typeOf = (object) -> return "Undefined" if typeof object == 'undefined' _objectToString.call(object).slice(8, -1) # Cache this function to skip property lookups. _objectToString = Object.prototype.toString # `$mixin` applies every key from every argument after the first to the # first argument. If a mixin has an `initialize` method, it will be called in # the context of the `to` object, and it's key/values won't be applied. Batman.mixin = $mixin = (to, mixins...) -> hasSet = typeof to.set is 'function' for mixin in mixins continue if $typeOf(mixin) isnt 'Object' for own key, value of mixin continue if key in ['initialize', 'uninitialize', 'prototype'] if hasSet to.set(key, value) else if to.nodeName? Batman.data to, key, value else to[key] = value if typeof mixin.initialize is 'function' mixin.initialize.call to to # `$unmixin` removes every key/value from every argument after the first # from the first argument. If a mixin has a `deinitialize` method, it will be # called in the context of the `from` object and won't be removed. Batman.unmixin = $unmixin = (from, mixins...) -> for mixin in mixins for key of mixin continue if key in ['initialize', 'uninitialize'] delete from[key] if typeof mixin.uninitialize is 'function' mixin.uninitialize.call from from # `$functionName` returns the name of a given function, if any # Used to deal with functions not having the `name` property in IE Batman._functionName = $functionName = (f) -> return f.__name__ if f.__name__ return f.name if f.name f.toString().match(/\W*function\s+([\w\$]+)\(/)?[1] # `$preventDefault` checks for preventDefault, since it's not # always available across all browsers Batman._preventDefault = $preventDefault = (e) -> if typeof e.preventDefault is "function" then e.preventDefault() else e.returnValue = false Batman._isChildOf = $isChildOf = (parentNode, childNode) -> node = childNode.parentNode while node return true if node == parentNode node = node.parentNode false $setImmediate = $clearImmediate = null _implementImmediates = (container) -> canUsePostMessage = -> return false unless container.postMessage async = true oldMessage = container.onmessage container.onmessage = -> async = false container.postMessage("","*") container.onmessage = oldMessage async tasks = new Batman.SimpleHash count = 0 getHandle = -> "go#{++count}" if container.setImmediate $setImmediate = container.setImmediate $clearImmediate = container.clearImmediate else if container.msSetImmediate $setImmediate = msSetImmediate $clearImmediate = msClearImmediate else if canUsePostMessage() prefix = 'com.batman.' functions = new Batman.SimpleHash handler = (e) -> return unless ~e.data.search(prefix) handle = e.data.substring(prefix.length) tasks.unset(handle)?() if container.addEventListener container.addEventListener('message', handler, false) else container.attachEvent('onmessage', handler) $setImmediate = (f) -> tasks.set(handle = getHandle(), f) container.postMessage(prefix+handle, "*") handle $clearImmediate = (handle) -> tasks.unset(handle) else if typeof document isnt 'undefined' && "onreadystatechange" in document.createElement("script") $setImmediate = (f) -> handle = getHandle() script = document.createElement("script") script.onreadystatechange = -> tasks.get(handle)?() script.onreadystatechange = null script.parentNode.removeChild(script) script = null document.documentElement.appendChild(script) handle $clearImmediate = (handle) -> tasks.unset(handle) else $setImmediate = (f) -> setTimeout(f, 0) $clearImmediate = (handle) -> clearTimeout(handle) Batman.setImmediate = $setImmediate Batman.clearImmediate = $clearImmediate Batman.setImmediate = $setImmediate = -> _implementImmediates(Batman.container) Batman.setImmediate.apply(@, arguments) Batman.clearImmediate = $clearImmediate = -> _implementImmediates(Batman.container) Batman.clearImmediate.apply(@, arguments) Batman.forEach = $forEach = (container, iterator, ctx) -> if container.forEach container.forEach(iterator, ctx) else if container.indexOf iterator.call(ctx, e, i, container) for e,i in container else iterator.call(ctx, k, v, container) for k,v of container Batman.objectHasKey = $objectHasKey = (object, key) -> if typeof object.hasKey is 'function' object.hasKey(key) else key of object Batman.contains = $contains = (container, item) -> if container.indexOf item in container else if typeof container.has is 'function' container.has(item) else $objectHasKey(container, item) Batman.get = $get = (base, key) -> if typeof base.get is 'function' base.get(key) else Batman.Property.forBaseAndKey(base, key).getValue() Batman.escapeHTML = $escapeHTML = do -> replacements = "&": "&amp;" "<": "&lt;" ">": "&gt;" "\"": "&#34;" "'": "&#39;" return (s) -> (""+s).replace(/[&<>'"]/g, (c) -> replacements[c]) # `translate` is hook for the i18n extra to override and implemnent. All strings which might # be shown to the user pass through this method. `translate` is aliased to `t` internally. Batman.translate = (x, values = {}) -> helpers.interpolate($get(Batman.translate.messages, x), values) Batman.translate.messages = {} t = -> Batman.translate(arguments...) # Developer Tooling # ----------------- Batman.developer = suppressed: false DevelopmentError: (-> DevelopmentError = (@message) -> @name = "DevelopmentError" DevelopmentError:: = Error:: DevelopmentError )() _ie_console: (f, args) -> console?[f] "...#{f} of #{args.length} items..." unless args.length == 1 console?[f] arg for arg in args suppress: (f) -> developer.suppressed = true if f f() developer.suppressed = false unsuppress: -> developer.suppressed = false log: -> return if developer.suppressed or !(console?.log?) if console.log.apply then console.log(arguments...) else developer._ie_console "log", arguments warn: -> return if developer.suppressed or !(console?.warn?) if console.warn.apply then console.warn(arguments...) else developer._ie_console "warn", arguments error: (message) -> throw new developer.DevelopmentError(message) assert: (result, message) -> developer.error(message) unless result do: (f) -> f() unless developer.suppressed addFilters: -> $mixin Batman.Filters, log: (value, key) -> console?.log? arguments value logStack: (value) -> console?.log? developer.currentFilterStack value developer = Batman.developer developer.assert (->).bind, "Error! Batman needs Function.bind to work! Please shim it using something like es5-shim or augmentjs!" # Helpers # ------- # Just a few random Rails-style string helpers. You can add more # to the Batman.helpers object. class Batman.Inflector plural: [] singular: [] uncountable: [] @plural: (regex, replacement) -> @::plural.unshift [regex, replacement] @singular: (regex, replacement) -> @::singular.unshift [regex, replacement] @irregular: (singular, plural) -> if singular.charAt(0) == plural.charAt(0) @plural new RegExp("(#{singular.charAt(0)})#{singular.slice(1)}$", "i"), "$1" + plural.slice(1) @plural new RegExp("(#{singular.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + plural.slice(1) @singular new RegExp("(#{plural.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + singular.slice(1) else @plural new RegExp("#{singular}$", 'i'), plural @plural new RegExp("#{plural}$", 'i'), plural @singular new RegExp("#{plural}$", 'i'), singular @uncountable: (strings...) -> @::uncountable = @::uncountable.concat(strings.map((x) -> new RegExp("#{x}$", 'i'))) @plural(/$/, 's') @plural(/s$/i, 's') @plural(/(ax|test)is$/i, '$1es') @plural(/(octop|vir)us$/i, '$1i') @plural(/(octop|vir)i$/i, '$1i') @plural(/(alias|status)$/i, '$1es') @plural(/(bu)s$/i, '$1ses') @plural(/(buffal|tomat)o$/i, '$1oes') @plural(/([ti])um$/i, '$1a') @plural(/([ti])a$/i, '$1a') @plural(/sis$/i, 'ses') @plural(/(?:([^f])fe|([lr])f)$/i, '$1$2ves') @plural(/(hive)$/i, '$1s') @plural(/([^aeiouy]|qu)y$/i, '$1ies') @plural(/(x|ch|ss|sh)$/i, '$1es') @plural(/(matr|vert|ind)(?:ix|ex)$/i, '$1ices') @plural(/([m|l])ouse$/i, '$1ice') @plural(/([m|l])ice$/i, '$1ice') @plural(/^(ox)$/i, '$1en') @plural(/^(oxen)$/i, '$1') @plural(/(quiz)$/i, '$1zes') @singular(/s$/i, '') @singular(/(n)ews$/i, '$1ews') @singular(/([ti])a$/i, '$1um') @singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '$1$2sis') @singular(/(^analy)ses$/i, '$1sis') @singular(/([^f])ves$/i, '$1fe') @singular(/(hive)s$/i, '$1') @singular(/(tive)s$/i, '$1') @singular(/([lr])ves$/i, '$1f') @singular(/([^aeiouy]|qu)ies$/i, '$1y') @singular(/(s)eries$/i, '$1eries') @singular(/(m)ovies$/i, '$1ovie') @singular(/(x|ch|ss|sh)es$/i, '$1') @singular(/([m|l])ice$/i, '$1ouse') @singular(/(bus)es$/i, '$1') @singular(/(o)es$/i, '$1') @singular(/(shoe)s$/i, '$1') @singular(/(cris|ax|test)es$/i, '$1is') @singular(/(octop|vir)i$/i, '$1us') @singular(/(alias|status)es$/i, '$1') @singular(/^(ox)en/i, '$1') @singular(/(vert|ind)ices$/i, '$1ex') @singular(/(matr)ices$/i, '$1ix') @singular(/(quiz)zes$/i, '$1') @singular(/(database)s$/i, '$1') @irregular('person', 'people') @irregular('man', 'men') @irregular('child', 'children') @irregular('sex', 'sexes') @irregular('move', 'moves') @irregular('cow', 'kine') @irregular('zombie', 'zombies') @uncountable('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans') ordinalize: (number) -> absNumber = Math.abs(parseInt(number)) if absNumber % 100 in [11..13] number + "th" else switch absNumber % 10 when 1 number + "st" when 2 number + "nd" when 3 number + "rd" else number + "th" pluralize: (word) -> for uncountableRegex in @uncountable return word if uncountableRegex.test(word) for [regex, replace_string] in @plural return word.replace(regex, replace_string) if regex.test(word) word singularize: (word) -> for uncountableRegex in @uncountable return word if uncountableRegex.test(word) for [regex, replace_string] in @singular return word.replace(regex, replace_string) if regex.test(word) word camelize_rx = /(?:^|_|\-)(.)/g capitalize_rx = /(^|\s)([a-z])/g underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g underscore_rx2 = /([a-z\d])([A-Z])/g helpers = Batman.helpers = inflector: new Batman.Inflector ordinalize: -> helpers.inflector.ordinalize.apply helpers.inflector, arguments singularize: -> helpers.inflector.singularize.apply helpers.inflector, arguments pluralize: (count, singular, plural) -> if arguments.length < 2 helpers.inflector.pluralize count else "#{count || 0} " + if +count is 1 then singular else (plural || helpers.inflector.pluralize(singular)) camelize: (string, firstLetterLower) -> string = string.replace camelize_rx, (str, p1) -> p1.toUpperCase() if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string underscore: (string) -> string.replace(underscore_rx1, '$1_$2') .replace(underscore_rx2, '$1_$2') .replace('-', '_').toLowerCase() capitalize: (string) -> string.replace capitalize_rx, (m,p1,p2) -> p1 + p2.toUpperCase() trim: (string) -> if string then string.trim() else "" interpolate: (stringOrObject, keys) -> if typeof stringOrObject is 'object' string = stringOrObject[keys.count] unless string string = stringOrObject['other'] else string = stringOrObject for key, value of keys string = string.replace(new RegExp("%\\{#{key}\\}", "g"), value) string class Batman.Event @forBaseAndKey: (base, key) -> if base.isEventEmitter base.event(key) else new Batman.Event(base, key) constructor: (@base, @key) -> @handlers = new Batman.SimpleSet @_preventCount = 0 isEvent: true isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key hashKey: -> @hashKey = -> key key = "<Batman.Event base: #{Batman.Hash::hashKeyFor(@base)}, key: \"#{Batman.Hash::<KEY>KeyFor(@key)}\">" addHandler: (handler) -> @handlers.add(handler) @autofireHandler(handler) if @oneShot this removeHandler: (handler) -> @handlers.remove(handler) this eachHandler: (iterator) -> @handlers.forEach(iterator) if @base?.isEventEmitter key = @key @base._batman.ancestors (ancestor) -> if ancestor.isEventEmitter and ancestor.hasEvent(key) handlers = ancestor.event(key).handlers handlers.forEach(iterator) handlerContext: -> @base prevent: -> ++@_preventCount allow: -> --@_preventCount if @_preventCount @_preventCount isPrevented: -> @_preventCount > 0 autofireHandler: (handler) -> if @_oneShotFired and @_oneShotArgs? handler.apply(@handlerContext(), @_oneShotArgs) resetOneShot: -> @_oneShotFired = false @_oneShotArgs = null fire: -> return false if @isPrevented() or @_oneShotFired context = @handlerContext() args = arguments if @oneShot @_oneShotFired = true @_oneShotArgs = arguments @eachHandler (handler) -> handler.apply(context, args) allowAndFire: -> @allow() @fire(arguments...) Batman.EventEmitter = isEventEmitter: true hasEvent: (key) -> @_batman?.get?('events')?.hasKey(key) event: (key) -> Batman.initializeObject @ eventClass = @eventClass or Batman.Event events = @_batman.events ||= new Batman.SimpleHash if events.hasKey(key) existingEvent = events.get(key) else existingEvents = @_batman.get('events') newEvent = events.set(key, new eventClass(this, key)) newEvent.oneShot = existingEvents?.get(key)?.oneShot newEvent on: (key, handler) -> @event(key).addHandler(handler) registerAsMutableSource: -> Batman.Property.registerSource(@) mutation: (wrappedFunction) -> -> result = wrappedFunction.apply(this, arguments) @event('change').fire(this, this) result prevent: (key) -> @event(key).prevent() @ allow: (key) -> @event(key).allow() @ isPrevented: (key) -> @event(key).isPrevented() fire: (key, args...) -> @event(key).fire(args...) allowAndFire: (key, args...) -> @event(key).allowAndFire(args...) class Batman.PropertyEvent extends Batman.Event eachHandler: (iterator) -> @base.eachObserver(iterator) handlerContext: -> @base.base class Batman.Property $mixin @prototype, Batman.EventEmitter @_sourceTrackerStack: [] @sourceTracker: -> (stack = @_sourceTrackerStack)[stack.length - 1] @defaultAccessor: get: (key) -> @[key] set: (key, val) -> @[key] = val unset: (key) -> x = @[key]; delete @[key]; x cachable: no @forBaseAndKey: (base, key) -> if base.isObservable base.property(key) else new Batman.Keypath(base, key) @withoutTracking: (block) -> @pushDummySourceTracker() try block() finally @popSourceTracker() @registerSource: (obj) -> return unless obj.isEventEmitter @sourceTracker()?.add(obj) @pushSourceTracker: -> Batman.Property._sourceTrackerStack.push(new Batman.SimpleSet) @pushDummySourceTracker: -> Batman.Property._sourceTrackerStack.push(null) @popSourceTracker: -> Batman.Property._sourceTrackerStack.pop() constructor: (@base, @key) -> developer.do => keyType = $typeOf(@key) if keyType in ['Array', 'Object'] developer.log "Accessing a property with an #{keyType} key. This is okay, but could be a source of memory leaks if you aren't careful." _isolationCount: 0 cached: no value: null sources: null isProperty: true isDead: false eventClass: Batman.PropertyEvent isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key hashKey: -> @hashKey = -> key key = "<<KEY>.Property base: #{B<KEY>.<KEY>(@base)}, key: \"<KEY> changeEvent: -> event = @event('change') @changeEvent = -> event event accessor: -> keyAccessors = @base._batman?.get('keyAccessors') accessor = if keyAccessors && (val = keyAccessors.get(@key)) val else @base._batman?.getFirst('defaultAccessor') or Batman.Property.defaultAccessor @accessor = -> accessor accessor eachObserver: (iterator) -> key = @key @changeEvent().handlers.forEach(iterator) if @base.isObservable @base._batman.ancestors (ancestor) -> if ancestor.isObservable and ancestor.hasProperty(key) property = ancestor.property(key) handlers = property.changeEvent().handlers handlers.forEach(iterator) observers: -> results = [] @eachObserver (observer) -> results.push(observer) results hasObservers: -> @observers().length > 0 updateSourcesFromTracker: -> newSources = @constructor.popSourceTracker() handler = @sourceChangeHandler() @_eachSourceChangeEvent (e) -> e.removeHandler(handler) @sources = newSources @_eachSourceChangeEvent (e) -> e.addHandler(handler) _eachSourceChangeEvent: (iterator) -> return unless @sources? @sources.forEach (source) -> iterator(source.event('change')) getValue: -> @registerAsMutableSource() unless @isCached() @constructor.pushSourceTracker() try @value = @valueFromAccessor() @cached = yes finally @updateSourcesFromTracker() @value isCachable: -> return true if @isFinal() cachable = @accessor().cachable if cachable? then !!cachable else true isCached: -> @isCachable() and @cached isFinal: -> !!@accessor()['final'] refresh: -> @cached = no previousValue = @value value = @getValue() if value isnt previousValue and not @isIsolated() @fire(value, previousValue) @lockValue() if @value isnt undefined and @isFinal() sourceChangeHandler: -> handler = => @_handleSourceChange() @sourceChangeHandler = -> handler handler _handleSourceChange: -> if @isIsolated() @_needsRefresh = yes else if not @isFinal() && not @hasObservers() @cached = no else @refresh() valueFromAccessor: -> @accessor().get?.call(@base, @key) setValue: (val) -> return unless set = @accessor().set @_changeValue -> set.call(@base, @key, val) unsetValue: -> return unless unset = @accessor().unset @_changeValue -> unset.call(@base, @key) _changeValue: (block) -> @cached = no @constructor.pushDummySourceTracker() try result = block.apply(this) @refresh() finally @constructor.popSourceTracker() @die() unless @isCached() or @hasObservers() result forget: (handler) -> if handler? @changeEvent().removeHandler(handler) else @changeEvent().handlers.clear() observeAndFire: (handler) -> @observe(handler) handler.call(@base, @value, @value) observe: (handler) -> @changeEvent().addHandler(handler) @getValue() unless @sources? this _removeHandlers: -> handler = @sourceChangeHandler() @_eachSourceChangeEvent (e) -> e.removeHandler(handler) delete @sources @changeEvent().handlers.clear() lockValue: -> @_removeHandlers() @getValue = -> @value @setValue = @unsetValue = @refresh = @observe = -> die: -> @_removeHandlers() @base._batman?.properties?.unset(@key) @isDead = true fire: -> @changeEvent().fire(arguments...) isolate: -> if @_isolationCount is 0 @_preIsolationValue = @getValue() @_isolationCount++ expose: -> if @_isolationCount is 1 @_isolationCount-- if @_needsRefresh @value = @_preIsolationValue @refresh() else if @value isnt @_preIsolationValue @fire(@value, @_preIsolationValue) @_preIsolationValue = null else if @_isolationCount > 0 @_isolationCount-- isIsolated: -> @_isolationCount > 0 # Keypaths # -------- class Batman.Keypath extends Batman.Property constructor: (base, key) -> if $typeOf(key) is 'String' @segments = key.split('.') @depth = @segments.length else @segments = [key] @depth = 1 super slice: (begin, end=@depth) -> base = @base for segment in @segments.slice(0, begin) return unless base? and base = $get(base, segment) propertyClass = base.propertyClass or Batman.Keypath remainingSegments = @segments.slice(begin, end) remainingPath = remainingSegments.join('.') if propertyClass is Batman.Keypath or remainingSegments.length is 1 Batman.Keypath.forBaseAndKey(base, remainingPath) else new Batman.Keypath(base, remainingPath) terminalProperty: -> @slice -1 valueFromAccessor: -> if @depth is 1 then super else @terminalProperty()?.getValue() setValue: (val) -> if @depth is 1 then super else @terminalProperty()?.setValue(val) unsetValue: -> if @depth is 1 then super else @terminalProperty()?.unsetValue() # Observable # ---------- # Batman.Observable is a generic mixin that can be applied to any object to allow it to be bound to. # It is applied by default to every instance of `Batman.Object` and subclasses. Batman.Observable = isObservable: true hasProperty: (key) -> @_batman?.properties?.hasKey?(key) property: (key) -> Batman.initializeObject @ propertyClass = @propertyClass or Batman.Keypath properties = @_batman.properties ||= new Batman.SimpleHash properties.get(key) or properties.set(key, new propertyClass(this, key)) get: (key) -> @property(key).getValue() set: (key, val) -> @property(key).setValue(val) unset: (key) -> @property(key).unsetValue() getOrSet: (key, valueFunction) -> currentValue = @get(key) unless currentValue currentValue = valueFunction() @set(key, currentValue) currentValue # `forget` removes an observer from an object. If the callback is passed in, # its removed. If no callback but a key is passed in, all the observers on # that key are removed. If no key is passed in, all observers are removed. forget: (key, observer) -> if key @property(key).forget(observer) else @_batman.properties?.forEach (key, property) -> property.forget() @ # `fire` tells any observers attached to a key to fire, manually. # `prevent` stops of a given binding from firing. `prevent` calls can be repeated such that # the same number of calls to allow are needed before observers can be fired. # `allow` unblocks a property for firing observers. Every call to prevent # must have a matching call to allow later if observers are to be fired. # `observe` takes a key and a callback. Whenever the value for that key changes, your # callback will be called in the context of the original object. observe: (key, args...) -> @property(key).observe(args...) @ observeAndFire: (key, args...) -> @property(key).observeAndFire(args...) @ # Objects # ------- # `Batman.initializeObject` is called by all the methods in Batman.Object to ensure that the # object's `_batman` property is initialized and it's own. Classes extending Batman.Object inherit # methods like `get`, `set`, and `observe` by default on the class and prototype levels, such that # both instances and the class respond to them and can be bound to. However, CoffeeScript's static # class inheritance copies over all class level properties indiscriminately, so a parent class' # `_batman` object will get copied to its subclasses, transferring all the information stored there and # allowing subclasses to mutate parent state. This method prevents this undesirable behaviour by tracking # which object the `_batman_` object was initialized upon, and reinitializing if that has changed since # initialization. Batman.initializeObject = (object) -> if object._batman? object._batman.check(object) else object._batman = new _Batman(object) # _Batman provides a convienient, parent class and prototype aware place to store hidden # object state. Things like observers, accessors, and states belong in the `_batman` object # attached to every Batman.Object subclass and subclass instance. Batman._Batman = class _Batman constructor: (@object, mixins...) -> $mixin(@, mixins...) if mixins.length > 0 # Used by `Batman.initializeObject` to ensure that this `_batman` was created referencing # the object it is pointing to. check: (object) -> if object != @object object._batman = new _Batman(object) return false return true # `get` is a prototype and class aware property access method. `get` will traverse the prototype chain, asking # for the passed key at each step, and then attempting to merge the results into one object. # It can only do this if at each level an `Array`, `Hash`, or `Set` is found, so try to use # those if you need `_batman` inhertiance. get: (key) -> # Get all the keys from the ancestor chain results = @getAll(key) switch results.length when 0 undefined when 1 results[0] else # And then try to merge them if there is more than one. Use `concat` on arrays, and `merge` on # sets and hashes. if results[0].concat? results = results.reduceRight (a, b) -> a.concat(b) else if results[0].merge? results = results.reduceRight (a, b) -> a.merge(b) results # `getFirst` is a prototype and class aware property access method. `getFirst` traverses the prototype chain, # and returns the value of the first `_batman` object which defines the passed key. Useful for # times when the merged value doesn't make sense or the value is a primitive. getFirst: (key) -> results = @getAll(key) results[0] # `getAll` is a prototype and class chain iterator. When passed a key or function, it applies it to each # parent class or parent prototype, and returns the undefined values, closest ancestor first. getAll: (keyOrGetter) -> # Get a function which pulls out the key from the ancestor's `_batman` or use the passed function. if typeof keyOrGetter is 'function' getter = keyOrGetter else getter = (ancestor) -> ancestor._batman?[keyOrGetter] # Apply it to all the ancestors, and then this `_batman`'s object. results = @ancestors(getter) if val = getter(@object) results.unshift val results # `ancestors` traverses the prototype or class chain and returns the application of a function to each # object in the chain. `ancestors` does this _only_ to the `@object`'s ancestors, and not the `@object` # itsself. ancestors: (getter = (x) -> x) -> results = [] # Decide if the object is a class or not, and pull out the first ancestor isClass = !!@object.prototype parent = if isClass @object.__super__?.constructor else if (proto = Object.getPrototypeOf(@object)) == @object @object.constructor.__super__ else proto if parent? parent._batman?.check(parent) # Apply the function and store the result if it isn't undefined. val = getter(parent) results.push(val) if val? # Use a recursive call to `_batman.ancestors` on the ancestor, which will take the next step up the chain. if parent._batman? results = results.concat(parent._batman.ancestors(getter)) results set: (key, value) -> @[key] = value # `Batman.Object` is the base class for all other Batman objects. It is not abstract. class BatmanObject extends Object Batman.initializeObject(this) Batman.initializeObject(@prototype) # Setting `isGlobal` to true will cause the class name to be defined on the # global object. For example, Batman.Model will be aliased to window.Model. # This should be used sparingly; it's mostly useful for debugging. @global: (isGlobal) -> return if isGlobal is false Batman.container[$functionName(@)] = @ # Apply mixins to this class. @classMixin: -> $mixin @, arguments... # Apply mixins to instances of this class. @mixin: -> @classMixin.apply @prototype, arguments mixin: @classMixin counter = 0 _objectID: -> @_objectID = -> c c = counter++ hashKey: -> return if typeof @isEqual is 'function' @hashKey = -> key key = "<Batman.Object #{@_objectID()}>" toJSON: -> obj = {} for own key, value of @ when key not in ["_batman", "hashKey", "_objectID"] obj[key] = if value?.toJSON then value.toJSON() else value obj # Accessor implementation. Accessors are used to create properties on a class or prototype which can be fetched # with get, but are computed instead of just stored. This is a batman and old browser friendly version of # `defineProperty` without as much goodness. # # Accessors track which other properties they rely on for computation, and when those other properties change, # an accessor will recalculate its value and notifiy its observers. This way, when a source value is changed, # any dependent accessors will automatically update any bindings to them with a new value. Accessors accomplish # this feat by tracking `get` calls, do be sure to use `get` to retrieve properties inside accessors. # # `@accessor` or `@classAccessor` can be called with zero, one, or many keys to attach the accessor to. This # has the following effects: # # * zero: create a `defaultAccessor`, which will be called when no other properties or accessors on an object # match a keypath. This is similar to `method_missing` in Ruby or `#doesNotUnderstand` in Smalltalk. # * one: create a `keyAccessor` at the given key, which will only be called when that key is `get`ed. # * many: create `keyAccessors` for each given key, which will then be called whenever each key is `get`ed. # # Note: This function gets called in all sorts of different contexts by various # other pointers to it, but it acts the same way on `this` in all cases. getAccessorObject = (accessor) -> accessor = {get: accessor} if !accessor.get && !accessor.set && !accessor.unset accessor @classAccessor: (keys..., accessor) -> Batman.initializeObject @ # Create a default accessor if no keys have been given. if keys.length is 0 # The `accessor` argument is wrapped in `getAccessorObject` which allows functions to be passed in # as a shortcut to {get: function} @_batman.defaultAccessor = getAccessorObject(accessor) else # Otherwise, add key accessors for each key given. @_batman.keyAccessors ||= new Batman.SimpleHash @_batman.keyAccessors.set(key, getAccessorObject(accessor)) for key in keys # Support adding accessors to the prototype from within class defintions or after the class has been created # with `KlassExtendingBatmanObject.accessor(keys..., accessorObject)` @accessor: -> @classAccessor.apply @prototype, arguments # Support adding accessors to instances after creation accessor: @classAccessor constructor: (mixins...) -> @_batman = new _Batman(@) @mixin mixins... # Make every subclass and their instances observable. @classMixin Batman.EventEmitter, Batman.Observable @mixin Batman.EventEmitter, Batman.Observable # Observe this property on every instance of this class. @observeAll: -> @::observe.apply @prototype, arguments @singleton: (singletonMethodName="sharedInstance") -> @classAccessor singletonMethodName, get: -> @["_#{singletonMethodName}"] ||= new @ Batman.Object = BatmanObject class Batman.Accessible extends Batman.Object constructor: -> @accessor.apply(@, arguments) class Batman.TerminalAccessible extends Batman.Accessible propertyClass: Batman.Property # Collections Batman.Enumerable = isEnumerable: true map: (f, ctx = Batman.container) -> r = []; @forEach(-> r.push f.apply(ctx, arguments)); r mapToProperty: (key) -> r = []; @forEach((item) -> r.push item.get(key)); r every: (f, ctx = Batman.container) -> r = true; @forEach(-> r = r && f.apply(ctx, arguments)); r some: (f, ctx = Batman.container) -> r = false; @forEach(-> r = r || f.apply(ctx, arguments)); r reduce: (f, r) -> count = 0 self = @ @forEach -> if r? then r = f(r, arguments..., count, self) else r = arguments[0] r filter: (f) -> r = new @constructor if r.add wrap = (r, e) -> r.add(e) if f(e); r else if r.set wrap = (r, k, v) -> r.set(k, v) if f(k, v); r else r = [] unless r.push wrap = (r, e) -> r.push(e) if f(e); r @reduce wrap, r # Provide this simple mixin ability so that during bootstrapping we don't have to use `$mixin`. `$mixin` # will correctly attempt to use `set` on the mixinee, which ends up requiring the definition of # `SimpleSet` to be complete during its definition. $extendsEnumerable = (onto) -> onto[k] = v for k,v of Batman.Enumerable class Batman.SimpleHash constructor: (obj) -> @_storage = {} @length = 0 @update(obj) if obj? $extendsEnumerable(@::) propertyClass: Batman.Property hasKey: (key) -> if pairs = @_storage[@hashKeyFor(key)] for pair in pairs return true if @equality(pair[0], key) return false get: (key) -> if pairs = @_storage[@hashKeyFor(key)] for pair in pairs return pair[1] if @equality(pair[0], key) set: (key, val) -> pairs = @_storage[@hashKeyFor(key)] ||= [] for pair in pairs if @equality(pair[0], key) return pair[1] = val @length++ pairs.push([key, val]) val unset: (key) -> hashKey = @hashKeyFor(key) if pairs = @_storage[hashKey] for [obj,value], index in pairs if @equality(obj, key) pair = pairs.splice(index,1) delete @_storage[hashKey] unless pairs.length @length-- return pair[0][1] getOrSet: Batman.Observable.getOrSet hashKeyFor: (obj) -> obj?.hashKey?() or obj equality: (lhs, rhs) -> return true if lhs is rhs return true if lhs isnt lhs and rhs isnt rhs # when both are NaN return true if lhs?.isEqual?(rhs) and rhs?.isEqual?(lhs) return false forEach: (iterator, ctx) -> for key, values of @_storage iterator.call(ctx, obj, value, this) for [obj, value] in values.slice() keys: -> result = [] # Explicitly reference this foreach so that if it's overriden in subclasses the new implementation isn't used. Batman.SimpleHash::forEach.call @, (key) -> result.push key result clear: -> @_storage = {} @length = 0 isEmpty: -> @length is 0 merge: (others...) -> merged = new @constructor others.unshift(@) for hash in others hash.forEach (obj, value) -> merged.set obj, value merged update: (object) -> @set(k,v) for k,v of object replace: (object) -> @forEach (key, value) => @unset(key) unless key of object @update(object) toObject: -> obj = {} for key, pair of @_storage obj[key] = pair[0][1] # the first value for this key obj toJSON: @::toObject class Batman.Hash extends Batman.Object class @Metadata extends Batman.Object constructor: (@hash) -> @accessor 'length', -> @hash.registerAsMutableSource() @hash.length @accessor 'isEmpty', -> @hash.isEmpty() @accessor 'keys', -> @hash.keys() constructor: -> @meta = new @constructor.Metadata(this) Batman.SimpleHash.apply(@, arguments) super $extendsEnumerable(@::) propertyClass: Batman.Property @accessor get: Batman.SimpleHash::get set: @mutation (key, value) -> result = Batman.SimpleHash::set.call(@, key, value) @fire 'itemsWereAdded', key result unset: @mutation (key) -> result = Batman.SimpleHash::unset.call(@, key) @fire 'itemsWereRemoved', key if result? result cachable: false _preventMutationEvents: (block) -> @prevent 'change' @prevent 'itemsWereAdded' @prevent 'itemsWereRemoved' try block.call(this) finally @allow 'change' @allow 'itemsWereAdded' @allow 'itemsWereRemoved' clear: @mutation -> keys = @keys() @_preventMutationEvents -> @forEach (k) => @unset(k) result = Batman.SimpleHash::clear.call(@) @fire 'itemsWereRemoved', keys... result update: @mutation (object) -> addedKeys = [] @_preventMutationEvents -> Batman.forEach object, (k,v) => addedKeys.push(k) unless @hasKey(k) @set(k,v) @fire('itemsWereAdded', addedKeys...) if addedKeys.length > 0 replace: @mutation (object) -> addedKeys = [] removedKeys = [] @_preventMutationEvents -> @forEach (k, _) => unless Batman.objectHasKey(object, k) @unset(k) removedKeys.push(k) Batman.forEach object, (k,v) => addedKeys.push(k) unless @hasKey(k) @set(k,v) @fire('itemsWereAdded', addedKeys...) if addedKeys.length > 0 @fire('itemsWereRemoved', removedKeys...) if removedKeys.length > 0 equality: Batman.SimpleHash::equality hashKeyFor: Batman.SimpleHash::hashKeyFor for k in ['hasKey', 'forEach', 'isEmpty', 'keys', 'merge', 'toJSON', 'toObject'] proto = @prototype do (k) -> proto[k] = -> @registerAsMutableSource() Batman.SimpleHash::[k].apply(@, arguments) class Batman.SimpleSet constructor: -> @_storage = new Batman.SimpleHash @_indexes = new Batman.SimpleHash @_uniqueIndexes = new Batman.SimpleHash @_sorts = new Batman.SimpleHash @length = 0 @add.apply @, arguments if arguments.length > 0 $extendsEnumerable(@::) has: (item) -> @_storage.hasKey item add: (items...) -> addedItems = [] for item in items when !@_storage.hasKey(item) @_storage.set item, true addedItems.push item @length++ if @fire and addedItems.length isnt 0 @fire('change', this, this) @fire('itemsWereAdded', addedItems...) addedItems remove: (items...) -> removedItems = [] for item in items when @_storage.hasKey(item) @_storage.unset item removedItems.push item @length-- if @fire and removedItems.length isnt 0 @fire('change', this, this) @fire('itemsWereRemoved', removedItems...) removedItems find: (f) -> ret = undefined @forEach (item) -> if ret is undefined && f(item) is true ret = item ret forEach: (iterator, ctx) -> container = this @_storage.forEach (key) -> iterator.call(ctx, key, null, container) isEmpty: -> @length is 0 clear: -> items = @toArray() @_storage = new Batman.SimpleHash @length = 0 if @fire and items.length isnt 0 @fire('change', this, this) @fire('itemsWereRemoved', items...) items replace: (other) -> try @prevent?('change') @clear() @add(other.toArray()...) finally @allowAndFire?('change', this, this) toArray: -> @_storage.keys() merge: (others...) -> merged = new @constructor others.unshift(@) for set in others set.forEach (v) -> merged.add v merged indexedBy: (key) -> @_indexes.get(key) or @_indexes.set(key, new Batman.SetIndex(@, key)) indexedByUnique: (key) -> @_uniqueIndexes.get(key) or @_uniqueIndexes.set(key, new Batman.UniqueSetIndex(@, key)) sortedBy: (key, order="asc") -> order = if order.toLowerCase() is "desc" then "desc" else "asc" sortsForKey = @_sorts.get(key) or @_sorts.set(key, new Batman.Object) sortsForKey.get(order) or sortsForKey.set(order, new Batman.SetSort(@, key, order)) class Batman.Set extends Batman.Object constructor: -> Batman.SimpleSet.apply @, arguments $extendsEnumerable(@::) for k in ['add', 'remove', 'find', 'clear', 'replace', 'indexedBy', 'indexedByUnique', 'sortedBy'] @::[k] = Batman.SimpleSet::[k] for k in ['merge', 'forEach', 'toArray', 'isEmpty', 'has'] proto = @prototype do (k) -> proto[k] = -> @registerAsMutableSource() Batman.SimpleSet::[k].apply(@, arguments) toJSON: @::toArray applySetAccessors = (klass) -> klass.accessor 'first', -> @toArray()[0] klass.accessor 'last', -> @toArray()[@length - 1] klass.accessor 'indexedBy', -> new Batman.TerminalAccessible (key) => @indexedBy(key) klass.accessor 'indexedByUnique', -> new Batman.TerminalAccessible (key) => @indexedByUnique(key) klass.accessor 'sortedBy', -> new Batman.TerminalAccessible (key) => @sortedBy(key) klass.accessor 'sortedByDescending', -> new Batman.TerminalAccessible (key) => @sortedBy(key, 'desc') klass.accessor 'isEmpty', -> @isEmpty() klass.accessor 'toArray', -> @toArray() klass.accessor 'length', -> @registerAsMutableSource() @length applySetAccessors(Batman.Set) class Batman.SetObserver extends Batman.Object constructor: (@base) -> @_itemObservers = new Batman.SimpleHash @_setObservers = new Batman.SimpleHash @_setObservers.set "itemsWereAdded", => @fire('itemsWereAdded', arguments...) @_setObservers.set "itemsWereRemoved", => @fire('itemsWereRemoved', arguments...) @on 'itemsWereAdded', @startObservingItems.bind(@) @on 'itemsWereRemoved', @stopObservingItems.bind(@) observedItemKeys: [] observerForItemAndKey: (item, key) -> _getOrSetObserverForItemAndKey: (item, key) -> @_itemObservers.getOrSet item, => observersByKey = new Batman.SimpleHash observersByKey.getOrSet key, => @observerForItemAndKey(item, key) startObserving: -> @_manageItemObservers("observe") @_manageSetObservers("addHandler") stopObserving: -> @_manageItemObservers("forget") @_manageSetObservers("removeHandler") startObservingItems: (items...) -> @_manageObserversForItem(item, "observe") for item in items stopObservingItems: (items...) -> @_manageObserversForItem(item, "forget") for item in items _manageObserversForItem: (item, method) -> return unless item.isObservable for key in @observedItemKeys item[method] key, @_getOrSetObserverForItemAndKey(item, key) @_itemObservers.unset(item) if method is "forget" _manageItemObservers: (method) -> @base.forEach (item) => @_manageObserversForItem(item, method) _manageSetObservers: (method) -> return unless @base.isObservable @_setObservers.forEach (key, observer) => @base.event(key)[method](observer) class Batman.SetProxy extends Batman.Object constructor: () -> super() @length = 0 @base.on 'itemsWereAdded', (items...) => @fire('itemsWereAdded', items...) @base.on 'itemsWereRemoved', (items...) => @fire('itemsWereRemoved', items...) $extendsEnumerable(@::) filter: (f) -> r = new Batman.Set() @reduce(((r, e) -> r.add(e) if f(e); r), r) for k in ['add', 'remove', 'find', 'clear', 'replace'] do (k) => @::[k] = -> results = @base[k](arguments...) @length = @set('length', @base.get 'length') results for k in ['has', 'merge', 'toArray', 'isEmpty', 'indexedBy', 'indexedByUnique', 'sortedBy'] do (k) => @::[k] = -> @base[k](arguments...) applySetAccessors(@) @accessor 'length', get: -> @registerAsMutableSource() @length set: (_, v) -> @length = v class Batman.SetSort extends Batman.SetProxy constructor: (@base, @key, order="asc") -> super() @descending = order.toLowerCase() is "desc" if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] boundReIndex = @_reIndex.bind(@) @_setObserver.observerForItemAndKey = -> boundReIndex @_setObserver.on 'itemsWereAdded', boundReIndex @_setObserver.on 'itemsWereRemoved', boundReIndex @startObserving() @_reIndex() startObserving: -> @_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() toArray: -> @get('_storage') forEach: (iterator, ctx) -> iterator.call(ctx,e,i,this) for e,i in @get('_storage') compare: (a,b) -> return 0 if a is b return 1 if a is undefined return -1 if b is undefined return 1 if a is null return -1 if b is null return 1 if a is false return -1 if b is false return 1 if a is true return -1 if b is true if a isnt a if b isnt b return 0 # both are NaN else return 1 # a is NaN return -1 if b isnt b # b is NaN return 1 if a > b return -1 if a < b return 0 _reIndex: -> newOrder = @base.toArray().sort (a,b) => valueA = $get(a, @key) valueA = valueA.valueOf() if valueA? valueB = $get(b, @key) valueB = valueB.valueOf() if valueB? multiple = if @descending then -1 else 1 @compare.call(@, valueA, valueB) * multiple @_setObserver?.startObservingItems(newOrder...) @set('_storage', newOrder) class Batman.SetIndex extends Batman.Object propertyClass: Batman.Property constructor: (@base, @key) -> super() @_storage = new Batman.SimpleHash if @base.isEventEmitter @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] @_setObserver.observerForItemAndKey = @observerForItemAndKey.bind(@) @_setObserver.on 'itemsWereAdded', (items...) => @_addItem(item) for item in items @_setObserver.on 'itemsWereRemoved', (items...) => @_removeItem(item) for item in items @base.forEach @_addItem.bind(@) @startObserving() @accessor (key) -> @_resultSetForKey(key) startObserving: ->@_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() observerForItemAndKey: (item, key) -> (newValue, oldValue) => @_removeItemFromKey(item, oldValue) @_addItemToKey(item, newValue) _addItem: (item) -> @_addItemToKey(item, @_keyForItem(item)) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item _removeItem: (item) -> @_removeItemFromKey(item, @_keyForItem(item)) _removeItemFromKey: (item, key) -> @_resultSetForKey(key).remove(item) _resultSetForKey: (key) -> @_storage.getOrSet(key, -> new Batman.Set) _keyForItem: (item) -> Batman.Keypath.forBaseAndKey(item, @key).getValue() class Batman.UniqueSetIndex extends Batman.SetIndex constructor: -> @_uniqueIndex = new Batman.Hash super @accessor (key) -> @_uniqueIndex.get(key) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item unless @_uniqueIndex.hasKey(key) @_uniqueIndex.set(key, item) _removeItemFromKey: (item, key) -> resultSet = @_resultSetForKey(key) super if resultSet.isEmpty() @_uniqueIndex.unset(key) else @_uniqueIndex.set(key, resultSet.toArray()[0]) class Batman.BinarySetOperation extends Batman.Set constructor: (@left, @right) -> super() @_setup @left, @right @_setup @right, @left _setup: (set, opposite) => set.on 'itemsWereAdded', (items...) => @_itemsWereAddedToSource(set, opposite, items...) set.on 'itemsWereRemoved', (items...) => @_itemsWereRemovedFromSource(set, opposite, items...) @_itemsWereAddedToSource set, opposite, set.toArray()... merge: (others...) -> merged = new Batman.Set others.unshift(@) for set in others set.forEach (v) -> merged.add v merged filter: Batman.SetProxy::filter class Batman.SetUnion extends Batman.BinarySetOperation _itemsWereAddedToSource: (source, opposite, items...) -> @add items... _itemsWereRemovedFromSource: (source, opposite, items...) -> itemsToRemove = (item for item in items when !opposite.has(item)) @remove itemsToRemove... class Batman.SetIntersection extends Batman.BinarySetOperation _itemsWereAddedToSource: (source, opposite, items...) -> itemsToAdd = (item for item in items when opposite.has(item)) @add itemsToAdd... _itemsWereRemovedFromSource: (source, opposite, items...) -> @remove items... # State Machines # -------------- Batman.StateMachine = { initialize: -> Batman.initializeObject @ if not @_batman.states @_batman.states = new Batman.SimpleHash state: (name, callback) -> Batman.StateMachine.initialize.call @ return @_batman.getFirst 'state' unless name developer.assert @isEventEmitter, "StateMachine requires EventEmitter" @[name] ||= (callback) -> _stateMachine_setState.call(@, name) @on(name, callback) if typeof callback is 'function' transition: (from, to, callback) -> Batman.StateMachine.initialize.call @ @state from @state to @on("#{from}->#{to}", callback) if callback } # A special method to alias state machine methods to class methods Batman.Object.actsAsStateMachine = (includeInstanceMethods=true) -> Batman.StateMachine.initialize.call @ Batman.StateMachine.initialize.call @prototype @classState = -> Batman.StateMachine.state.apply @, arguments @state = -> @classState.apply @prototype, arguments @::state = @classState if includeInstanceMethods @classTransition = -> Batman.StateMachine.transition.apply @, arguments @transition = -> @classTransition.apply @prototype, arguments @::transition = @classTransition if includeInstanceMethods # This is cached here so it doesn't need to be recompiled for every setter _stateMachine_setState = (newState) -> Batman.StateMachine.initialize.call @ if @_batman.isTransitioning (@_batman.nextState ||= []).push(newState) return false @_batman.isTransitioning = yes oldState = @state() @_batman.state = newState if newState and oldState @fire("#{oldState}->#{newState}", newState, oldState) if newState @fire(newState, newState, oldState) @_batman.isTransitioning = no @[@_batman.nextState.shift()]() if @_batman.nextState?.length newState # App, Requests, and Routing # -------------------------- # `Batman.Request` is a normalizer for XHR requests in the Batman world. class Batman.Request extends Batman.Object @objectToFormData: (data) -> pairForList = (key, object, first = false) -> list = switch Batman.typeOf(object) when 'Object' list = for k, v of object pairForList((if first then k else "#{key}[#{k}]"), v) list.reduce((acc, list) -> acc.concat list , []) when 'Array' object.reduce((acc, element) -> acc.concat pairForList("#{key}[]", element) , []) else [[key, object]] formData = new Batman.container.FormData() for [key, val] in pairForList("", data, true) formData.append(key, val) formData url: '' data: '' method: 'GET' formData: false response: null status: null headers: {} @accessor 'method', $mixin {}, Batman.Property.defaultAccessor, set: (k,val) -> @[k] = val?.toUpperCase?() # Set the content type explicitly for PUT and POST requests. contentType: 'application/x-www-form-urlencoded' constructor: (options) -> handlers = {} for k, handler of options when k in ['success', 'error', 'loading', 'loaded'] handlers[k] = handler delete options[k] super(options) @on k, handler for k, handler of handlers # After the URL gets set, we'll try to automatically send # your request after a short period. If this behavior is # not desired, use @cancel() after setting the URL. @observeAll 'url', (url) -> @_autosendTimeout = $setImmediate => @send() # `send` is implmented in the platform layer files. One of those must be required for # `Batman.Request` to be useful. send: -> developer.error "Please source a dependency file for a request implementation" cancel: -> $clearImmediate(@_autosendTimeout) if @_autosendTimeout ## Routes class Batman.Route extends Batman.Object # Route regexes courtesy of Backbone @regexps = namedParam: /:([\w\d]+)/g splatParam: /\*([\w\d]+)/g queryParam: '(?:\\?.+)?' namedOrSplat: /[:|\*]([\w\d]+)/g namePrefix: '[:|\*]' escapeRegExp: /[-[\]{}()+?.,\\^$|#\s]/g optionKeys: ['member', 'collection'] testKeys: ['controller', 'action'] isRoute: true constructor: (templatePath, baseParams) -> regexps = @constructor.regexps templatePath = "/#{templatePath}" if templatePath.indexOf('/') isnt 0 pattern = templatePath.replace(regexps.escapeRegExp, '\\$&') regexp = /// ^ #{pattern .replace(regexps.namedParam, '([^\/]+)') .replace(regexps.splatParam, '(.*?)') } #{regexps.queryParam} $ /// namedArguments = (matches[1] while matches = regexps.namedOrSplat.exec(pattern)) properties = {templatePath, pattern, regexp, namedArguments, baseParams} for k in @optionKeys properties[k] = baseParams[k] delete baseParams[k] super(properties) paramsFromPath: (path) -> [path, query] = path.split '?' namedArguments = @get('namedArguments') params = $mixin {path}, @get('baseParams') matches = @get('regexp').exec(path).slice(1) for match, index in matches name = namedArguments[index] params[name] = match if query for pair in query.split('&') [key, value] = pair.split '=' params[key] = value params pathFromParams: (argumentParams) -> params = $mixin {}, argumentParams path = @get('templatePath') # Replace the names in the template with their values from params for name in @get('namedArguments') regexp = ///#{@constructor.regexps.namePrefix}#{name}/// newPath = path.replace regexp, (if params[name]? then params[name] else '') if newPath != path delete params[name] path = newPath for key in @testKeys delete params[key] # Append the rest of the params as a query string queryParams = ("#{key}=#{value}" for key, value of params) if queryParams.length > 0 path += "?" + queryParams.join("&") path test: (pathOrParams) -> if typeof pathOrParams is 'string' path = pathOrParams else if pathOrParams.path? path = pathOrParams.path else path = @pathFromParams(pathOrParams) for key in @testKeys if (value = @get(key))? return false unless pathOrParams[key] == value @get('regexp').test(path) dispatch: (pathOrParams) -> return false unless @test(pathOrParams) if typeof pathOrParams is 'string' params = @paramsFromPath(pathOrParams) path = pathOrParams else params = pathOrParams path = @pathFromParams(pathOrParams) @get('callback')(params) return path callback: -> throw new Batman.DevelopmentError "Override callback in a Route subclass" class Batman.CallbackActionRoute extends Batman.Route optionKeys: ['member', 'collection', 'callback', 'app'] controller: false action: false class Batman.ControllerActionRoute extends Batman.Route optionKeys: ['member', 'collection', 'app', 'controller', 'action'] constructor: (templatePath, options) -> if options.signature [controller, action] = options.signature.split('#') action ||= 'index' options.controller = controller options.action = action delete options.signature super(templatePath, options) callback: (params) => controller = @get("app.dispatcher.controllers.#{@get('controller')}") controller.dispatch(@get('action'), params) class Batman.Dispatcher extends Batman.Object @canInferRoute: (argument) -> argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy || argument.prototype instanceof Batman.Model @paramsFromArgument: (argument) -> resourceNameFromModel = (model) -> helpers.underscore(helpers.pluralize($functionName(model))) return argument unless @canInferRoute(argument) if argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy argument = argument.get('target') if argument.isProxy if argument? { controller: resourceNameFromModel(argument.constructor) action: 'show' id: argument.get('id') } else {} else if argument.prototype instanceof Batman.Model { controller: resourceNameFromModel(argument) action: 'index' } else argument class ControllerDirectory extends Batman.Object @accessor '__app', Batman.Property.defaultAccessor @accessor (key) -> @get("__app.#{helpers.capitalize(key)}Controller.sharedController") @accessor 'controllers', -> new ControllerDirectory(__app: @get('app')) constructor: (app, routeMap) -> super({app, routeMap}) routeForParams: (params) -> params = @constructor.paramsFromArgument(params) @get('routeMap').routeForParams(params) pathFromParams: (params) -> return params if typeof params is 'string' params = @constructor.paramsFromArgument(params) @routeForParams(params)?.pathFromParams(params) dispatch: (params) -> inferredParams = @constructor.paramsFromArgument(params) route = @routeForParams(inferredParams) if route path = route.dispatch(inferredParams) else # No route matching the parameters was found, but an object which might be for # use with the params replacer has been passed. If its an object like a model # or a record we could have inferred a route for it (but didn't), so we make # sure that it isn't by running it through canInferRoute. if $typeOf(params) is 'Object' && !@constructor.canInferRoute(params) return @get('app.currentParams').replace(params) else @get('app.currentParams').clear() return Batman.redirect('/404') unless path is '/404' or params is '/404' @set 'app.currentURL', path @set 'app.currentRoute', route path class Batman.RouteMap memberRoute: null collectionRoute: null constructor: -> @childrenByOrder = [] @childrenByName = {} routeForParams: (params) -> for route in @childrenByOrder return route if route.test(params) return undefined addRoute: (name, route) -> @childrenByOrder.push(route) if name.length > 0 && (names = name.split('.')).length > 0 base = names.shift() unless @childrenByName[base] @childrenByName[base] = new Batman.RouteMap @childrenByName[base].addRoute(names.join('.'), route) else if route.get('member') developer.do => Batman.developer.error("Member route with name #{name} already exists!") if @memberRoute @memberRoute = route else developer.do => Batman.developer.error("Collection route with name #{name} already exists!") if @collectionRoute @collectionRoute = route true class Batman.NamedRouteQuery extends Batman.Object isNamedRouteQuery: true developer.do => class NonWarningProperty extends Batman.Keypath constructor: -> developer.suppress() super developer.unsuppress() @::propertyClass = NonWarningProperty constructor: (routeMap, args = []) -> super({routeMap, args}) @accessor 'route', -> {memberRoute, collectionRoute} = @get('routeMap') for route in [memberRoute, collectionRoute] when route? return route if route.namedArguments.length == @get('args').length return collectionRoute || memberRoute @accessor 'path', -> params = {} namedArguments = @get('route.namedArguments') for argumentName, index in namedArguments if (argumentValue = @get('args')[index])? params[argumentName] = @_toParam(argumentValue) @get('route').pathFromParams(params) @accessor 'routeMap', 'args', 'cardinality', Batman.Property.defaultAccessor @accessor get: (key) -> return if !key? if typeof key is 'string' @nextQueryForName(key) else @nextQueryWithArgument(key) set: -> cacheable: false nextQueryForName: (key) -> if map = @get('routeMap').childrenByName[key] return new Batman.NamedRouteQuery(map, @args) else Batman.developer.error "Couldn't find a route for the name #{key}!" nextQueryWithArgument: (arg) -> args = @args.slice(0) args.push arg @clone(args) _toParam: (arg) -> if arg instanceof Batman.AssociationProxy arg = arg.get('target') if arg.toParam isnt 'undefined' then arg.toParam() else arg _paramName: (arg) -> string = helpers.singularize($functionName(arg)) + "Id" string.charAt(0).toLowerCase() + string.slice(1) clone: (args = @args) -> new Batman.NamedRouteQuery(@routeMap, args) class Batman.RouteMapBuilder @BUILDER_FUNCTIONS = ['resources', 'member', 'collection', 'route', 'root'] @ROUTES = index: cardinality: 'collection' path: (resource) -> resource name: (resource) -> resource new: cardinality: 'collection' path: (resource) -> "#{resource}/new" name: (resource) -> "#{resource}.new" show: cardinality: 'member' path: (resource) -> "#{resource}/:id" name: (resource) -> resource edit: cardinality: 'member' path: (resource) -> "#{resource}/:id/edit" name: (resource) -> "#{resource}.edit" collection: cardinality: 'collection' path: (resource, name) -> "#{resource}/#{name}" name: (resource, name) -> "#{resource}.#{name}" member: cardinality: 'member' path: (resource, name) -> "#{resource}/:id/#{name}" name: (resource, name) -> "#{resource}.#{name}" constructor: (@app, @routeMap, @parent, @baseOptions = {}) -> if @parent @rootPath = @parent._nestingPath() @rootName = @parent._nestingName() else @rootPath = '' @rootName = '' resources: (args...) -> resourceNames = (arg for arg in args when typeof arg is 'string') callback = args.pop() if typeof args[args.length - 1] is 'function' if typeof args[args.length - 1] is 'object' options = args.pop() else options = {} actions = {index: true, new: true, show: true, edit: true} if options.except actions[k] = false for k in options.except delete options.except else if options.only actions[k] = false for k, v of actions actions[k] = true for k in options.only delete options.only for resourceName in resourceNames controller = resourceRoot = helpers.pluralize(resourceName) childBuilder = @_childBuilder({controller}) # Call the callback so that routes defined within it are matched # before the standard routes defined by `resources`. callback?.call(childBuilder) for action, included of actions when included route = @constructor.ROUTES[action] as = route.name(resourceRoot) path = route.path(resourceRoot) routeOptions = $mixin {controller, action, path, as}, options childBuilder[route.cardinality](action, routeOptions) true member: -> @_addRoutesWithCardinality('member', arguments...) collection: -> @_addRoutesWithCardinality('collection', arguments...) root: (signature, options) -> @route '/', signature, options route: (path, signature, options, callback) -> if !callback if typeof options is 'function' callback = options options = undefined else if typeof signature is 'function' callback = signature signature = undefined if !options if typeof signature is 'string' options = {signature} else options = signature options ||= {} else options.signature = signature if signature options.callback = callback if callback options.as ||= @_nameFromPath(path) options.path = path @_addRoute(options) _addRoutesWithCardinality: (cardinality, names..., options) -> if typeof options is 'string' names.push options options = {} options = $mixin {}, @baseOptions, options options[cardinality] = true route = @constructor.ROUTES[cardinality] resourceRoot = options.controller for name in names routeOptions = $mixin {action: name}, options unless routeOptions.path? routeOptions.path = route.path(resourceRoot, name) unless routeOptions.as? routeOptions.as = route.name(resourceRoot, name) @_addRoute(routeOptions) true _addRoute: (options = {}) -> path = @rootPath + options.path name = @rootName + options.as delete options.as delete options.path klass = if options.callback then Batman.CallbackActionRoute else Batman.ControllerActionRoute options.app = @app route = new klass(path, options) @routeMap.addRoute(name, route) _nameFromPath: (path) -> underscored = path .replace(Batman.Route.regexps.namedOrSplat, '') .replace(/\/+/g, '_') .replace(/(^_)|(_$)/g, '') name = helpers.camelize(underscored) name.charAt(0).toLowerCase() + name.slice(1) _nestingPath: -> unless @parent "" else nestingParam = ":" + helpers.singularize(@baseOptions.controller) + "Id" "#{@parent._nestingPath()}/#{@baseOptions.controller}/#{nestingParam}/" _nestingName: -> unless @parent "" else @baseOptions.controller + "." _childBuilder: (baseOptions = {}) -> new Batman.RouteMapBuilder(@app, @routeMap, @, baseOptions) class Batman.Navigator @defaultClass: -> if Batman.config.usePushState and Batman.PushStateNavigator.isSupported() Batman.PushStateNavigator else Batman.HashbangNavigator @forApp: (app) -> new (@defaultClass())(app) constructor: (@app) -> start: -> return if typeof window is 'undefined' return if @started @started = yes @startWatching() Batman.currentApp.prevent 'ready' $setImmediate => if @started && Batman.currentApp @handleCurrentLocation() Batman.currentApp.allowAndFire 'ready' stop: -> @stopWatching() @started = no handleLocation: (location) -> path = @pathFromLocation(location) return if path is @cachedPath @dispatch(path) handleCurrentLocation: => @handleLocation(window.location) dispatch: (params) -> @cachedPath = @app.get('dispatcher').dispatch(params) push: (params) -> path = @dispatch(params) @pushState(null, '', path) path replace: (params) -> path = @dispatch(params) @replaceState(null, '', path) path redirect: @::push normalizePath: (segments...) -> segments = for seg, i in segments "#{seg}".replace(/^(?!\/)/, '/').replace(/\/+$/,'') segments.join('') or '/' @normalizePath: @::normalizePath class Batman.PushStateNavigator extends Batman.Navigator @isSupported: -> window?.history?.pushState? startWatching: -> $addEventListener window, 'popstate', @handleCurrentLocation stopWatching: -> $removeEventListener window, 'popstate', @handleCurrentLocation pushState: (stateObject, title, path) -> window.history.pushState(stateObject, title, @linkTo(path)) replaceState: (stateObject, title, path) -> window.history.replaceState(stateObject, title, @linkTo(path)) linkTo: (url) -> @normalizePath(Batman.config.pathPrefix, url) pathFromLocation: (location) -> fullPath = "#{location.pathname or ''}#{location.search or ''}" prefixPattern = new RegExp("^#{@normalizePath(Batman.config.pathPrefix)}") @normalizePath(fullPath.replace(prefixPattern, '')) handleLocation: (location) -> path = @pathFromLocation(location) if path is '/' and (hashbangPath = Batman.HashbangNavigator::pathFromLocation(location)) isnt '/' @replace(hashbangPath) else super class Batman.HashbangNavigator extends Batman.Navigator HASH_PREFIX: '#!' if window? and 'onhashchange' of window @::startWatching = -> $addEventListener window, 'hashchange', @handleCurrentLocation @::stopWatching = -> $removeEventListener window, 'hashchange', @handleCurrentLocation else @::startWatching = -> @interval = setInterval @handleCurrentLocation, 100 @::stopWatching = -> @interval = clearInterval @interval pushState: (stateObject, title, path) -> window.location.hash = @linkTo(path) replaceState: (stateObject, title, path) -> loc = window.location loc.replace("#{loc.pathname}#{loc.search}#{@linkTo(path)}") linkTo: (url) -> @HASH_PREFIX + url pathFromLocation: (location) -> hash = location.hash if hash?.substr(0,2) is @HASH_PREFIX @normalizePath(hash.substr(2)) else '/' handleLocation: (location) -> return super unless Batman.config.usePushState realPath = Batman.PushStateNavigator::pathFromLocation(location) if realPath is '/' super else location.replace(@normalizePath("#{Batman.config.pathPrefix}#{@linkTo(realPath)}")) Batman.redirect = $redirect = (url) -> Batman.navigator?.redirect url class Batman.ParamsReplacer extends Batman.Object constructor: (@navigator, @params) -> redirect: -> @navigator.replace(@toObject()) replace: (params) -> @params.replace(params) @redirect() update: (params) -> @params.update(params) @redirect() clear: () -> @params.clear() @redirect() toObject: -> @params.toObject() @accessor get: (k) -> @params.get(k) set: (k,v) -> oldValue = @params.get(k) result = @params.set(k,v) @redirect() if oldValue isnt v result unset: (k) -> hadKey = @params.hasKey(k) result = @params.unset(k) @redirect() if hadKey result class Batman.ParamsPusher extends Batman.ParamsReplacer redirect: -> @navigator.push(@toObject()) # `Batman.App` manages requiring files and acts as a namespace for all code subclassing # Batman objects. class Batman.App extends Batman.Object @classAccessor 'currentParams', get: -> new Batman.Hash 'final': true @classAccessor 'paramsManager', get: -> return unless nav = @get('navigator') params = @get('currentParams') params.replacer = new Batman.ParamsReplacer(nav, params) 'final': true @classAccessor 'paramsPusher', get: -> return unless nav = @get('navigator') params = @get('currentParams') params.pusher = new Batman.ParamsPusher(nav, params) 'final': true @classAccessor 'routes', -> new Batman.NamedRouteQuery(@get('routeMap')) @classAccessor 'routeMap', -> new Batman.RouteMap @classAccessor 'routeMapBuilder', -> new Batman.RouteMapBuilder(@, @get('routeMap')) @classAccessor 'dispatcher', -> new Batman.Dispatcher(@, @get('routeMap')) @classAccessor 'controllers', -> @get('dispatcher.controllers') @classAccessor '_renderContext', -> Batman.RenderContext.base.descend(@) # Require path tells the require methods which base directory to look in. @requirePath: '' # The require class methods (`controller`, `model`, `view`) simply tells # your app where to look for coffeescript source files. This # implementation may change in the future. developer.do => App.require = (path, names...) -> base = @requirePath + path for name in names @prevent 'run' path = base + '/' + name + '.coffee' new Batman.Request url: path type: 'html' success: (response) => CoffeeScript.eval response @allow 'run' if not @isPrevented 'run' @fire 'loaded' @run() if @wantsToRun @ @controller = (names...) -> names = names.map (n) -> n + '_controller' @require 'controllers', names... @model = -> @require 'models', arguments... @view = -> @require 'views', arguments... # Layout is the base view that other views can be yielded into. The # default behavior is that when `app.run()` is called, a new view will # be created for the layout using the `document` node as its content. # Use `MyApp.layout = null` to turn off the default behavior. @layout: undefined # Routes for the app are built using a RouteMapBuilder, so delegate the # functions used to build routes to it. for name in Batman.RouteMapBuilder.BUILDER_FUNCTIONS do (name) => @[name] = -> @get('routeMapBuilder')[name](arguments...) # Call `MyApp.run()` to start up an app. Batman level initializers will # be run to bootstrap the application. @event('ready').oneShot = true @event('run').oneShot = true @run: -> if Batman.currentApp return if Batman.currentApp is @ Batman.currentApp.stop() return false if @hasRun if @isPrevented 'run' @wantsToRun = true return false else delete @wantsToRun Batman.currentApp = @ Batman.App.set('current', @) unless @get('dispatcher')? @set 'dispatcher', new Batman.Dispatcher(@, @get('routeMap')) @set 'controllers', @get('dispatcher.controllers') unless @get('navigator')? @set('navigator', Batman.Navigator.forApp(@)) @on 'run', => Batman.navigator = @get('navigator') Batman.navigator.start() if Object.keys(@get('dispatcher').routeMap).length > 0 @observe 'layout', (layout) => layout?.on 'ready', => @fire 'ready' if typeof @layout is 'undefined' @set 'layout', new Batman.View context: @ node: document else if typeof @layout is 'string' @set 'layout', new @[helpers.camelize(@layout) + 'View'] @hasRun = yes @fire('run') @ @event('ready').oneShot = true @event('stop').oneShot = true @stop: -> @navigator?.stop() Batman.navigator = null @hasRun = no @fire('stop') @ # Controllers # ----------- class Batman.Controller extends Batman.Object @singleton 'sharedController' @accessor 'controllerName', -> @_controllerName ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) @accessor '_renderContext', -> Batman.RenderContext.root().descend(@) @beforeFilter: (options, nameOrFunction) -> if not nameOrFunction nameOrFunction = options options = {} else options.only = [options.only] if options.only and $typeOf(options.only) isnt 'Array' options.except = [options.except] if options.except and $typeOf(options.except) isnt 'Array' Batman.initializeObject @ options.block = nameOrFunction filters = @_batman.beforeFilters ||= new Batman.Hash filters.set(nameOrFunction, options) @afterFilter: (options, nameOrFunction) -> if not nameOrFunction nameOrFunction = options options = {} else options.only = [options.only] if options.only and $typeOf(options.only) isnt 'Array' options.except = [options.except] if options.except and $typeOf(options.except) isnt 'Array' Batman.initializeObject @ options.block = nameOrFunction filters = @_batman.afterFilters ||= new Batman.Hash filters.set(nameOrFunction, options) runFilters: (params, filters) -> action = params.action if filters = @constructor._batman?.get(filters) filters.forEach (_, options) => return if options.only and action not in options.only return if options.except and action in options.except block = options.block if typeof block is 'function' then block.call(@, params) else @[block]?(params) # You shouldn't call this method directly. It will be called by the dispatcher when a route is called. # If you need to call a route manually, use `$redirect()`. dispatch: (action, params = {}) -> params.controller ||= @get 'controllerName' params.action ||= action params.target ||= @ oldRedirect = Batman.navigator?.redirect Batman.navigator?.redirect = @redirect @_inAction = yes @_actedDuringAction = no @set 'action', action @set 'params', params @runFilters params, 'beforeFilters' developer.assert @[action], "Error! Controller action #{@get 'controllerName'}.#{action} couldn't be found!" @[action](params) if not @_actedDuringAction @render() @runFilters params, 'afterFilters' delete @_actedDuringAction delete @_inAction Batman.navigator?.redirect = oldRedirect redirectTo = @_afterFilterRedirect delete @_afterFilterRedirect $redirect(redirectTo) if redirectTo redirect: (url) => if @_actedDuringAction && @_inAction developer.warn "Warning! Trying to redirect but an action has already be taken during #{@get('controllerName')}.#{@get('action')}}" if @_inAction @_actedDuringAction = yes @_afterFilterRedirect = url else if $typeOf(url) is 'Object' url.controller = @ if not url.controller $redirect url render: (options = {}) -> if @_actedDuringAction && @_inAction developer.warn "Warning! Trying to render but an action has already be taken during #{@get('controllerName')}.#{@get('action')}" @_actedDuringAction = yes return if options is false if not options.view options.context ||= @get('_renderContext') options.source ||= helpers.underscore(@get('controllerName') + '/' + @get('action')) options.view = new (Batman.currentApp?[helpers.camelize("#{@get('controllerName')}_#{@get('action')}_view")] || Batman.View)(options) if view = options.view Batman.currentApp?.prevent 'ready' view.on 'ready', => Batman.DOM.replace options.into || 'main', view.get('node'), view.hasContainer Batman.currentApp?.allowAndFire 'ready' view.ready?(@params) view # Models # ------ class Batman.Model extends Batman.Object # ## Model API # Override this property if your model is indexed by a key other than `id` @primaryKey: 'id' # Override this property to define the key which storage adapters will use to store instances of this model under. # - For RestStorage, this ends up being part of the url built to store this model # - For LocalStorage, this ends up being the namespace in localStorage in which JSON is stored @storageKey: null # Pick one or many mechanisms with which this model should be persisted. The mechanisms # can be already instantiated or just the class defining them. @persist: (mechanisms...) -> Batman.initializeObject @prototype storage = @::_batman.storage ||= [] results = for mechanism in mechanisms mechanism = if mechanism.isStorageAdapter then mechanism else new mechanism(@) storage.push mechanism mechanism if results.length > 1 results else results[0] # Encoders are the tiny bits of logic which manage marshalling Batman models to and from their # storage representations. Encoders do things like stringifying dates and parsing them back out again, # pulling out nested model collections and instantiating them (and JSON.stringifying them back again), # and marshalling otherwise un-storable object. @encode: (keys..., encoderOrLastKey) -> Batman.initializeObject @prototype @::_batman.encoders ||= new Batman.SimpleHash @::_batman.decoders ||= new Batman.SimpleHash encoder = {} switch $typeOf(encoderOrLastKey) when 'String' keys.push encoderOrLastKey when 'Function' encoder.encode = encoderOrLastKey else encoder.encode = encoderOrLastKey.encode encoder.decode = encoderOrLastKey.decode encoder = $mixin {}, @defaultEncoder, encoder for operation in ['encode', 'decode'] for key in keys hash = @::_batman["#{operation}rs"] if encoder[operation] hash.set(key, encoder[operation]) else hash.unset(key) #true # Set up the unit functions as the default for both @defaultEncoder: encode: (x) -> x decode: (x) -> x # Attach encoders and decoders for the primary key, and update them if the primary key changes. @observeAndFire 'primaryKey', (newPrimaryKey) -> @encode newPrimaryKey, {encode: false, decode: @defaultEncoder.decode} # Validations allow a model to be marked as 'valid' or 'invalid' based on a set of programmatic rules. # By validating our data before it gets to the server we can provide immediate feedback to the user about # what they have entered and forgo waiting on a round trip to the server. # `validate` allows the attachment of validations to the model on particular keys, where the validation is # either a built in one (by use of options to pass to them) or a custom one (by use of a custom function as # the second argument). Custom validators should have the signature `(errors, record, key, callback)`. They # should add strings to the `errors` set based on the record (maybe depending on the `key` they were attached # to) and then always call the callback. Again: the callback must always be called. @validate: (keys..., optionsOrFunction) -> Batman.initializeObject @prototype validators = @::_batman.validators ||= [] if typeof optionsOrFunction is 'function' # Given a function, use that as the actual validator, expecting it to conform to the API # the built in validators do. validators.push keys: keys callback: optionsOrFunction else # Given options, find the validations which match the given options, and add them to the validators # array. options = optionsOrFunction for validator in Validators if (matches = validator.matches(options)) delete options[match] for match in matches validators.push keys: keys validator: new validator(matches) @urlNestsUnder: (key) -> parent = Batman.helpers.pluralize(key) children = Batman.helpers.pluralize(Batman._functionName(@).toLowerCase()) @url = (options) -> parentID = options.data[key + '_id'] delete options.data[key + '_id'] "#{parent}/#{parentID}/#{children}" @::url = -> url = "#{parent}/#{@get(key + '_id')}/#{children}" if id = @get('id') url += '/' + id url # ### Query methods @classAccessor 'all', get: -> @load() if @::hasStorage() and @classState() not in ['loaded', 'loading'] @get('loaded') set: (k, v) -> @set('loaded', v) @classAccessor 'loaded', get: -> @_loaded ||= new Batman.Set set: (k, v) -> @_loaded = v @classAccessor 'first', -> @get('all').toArray()[0] @classAccessor 'last', -> x = @get('all').toArray(); x[x.length - 1] @clear: -> Batman.initializeObject(@) result = @get('loaded').clear() @_batman.get('associations')?.reset() result @find: (id, callback) -> developer.assert callback, "Must call find with a callback!" record = new @() record.set 'id', id newRecord = @_mapIdentity(record) newRecord.load callback return newRecord # `load` fetches records from all sources possible @load: (options, callback) -> if typeof options in ['function', 'undefined'] callback = options options = {} developer.assert @::_batman.getAll('storage').length, "Can't load model #{$functionName(@)} without any storage adapters!" @loading() @::_doStorageOperation 'readAll', options, (err, records) => if err? callback?(err, []) else mappedRecords = (@_mapIdentity(record) for record in records) @loaded() callback?(err, mappedRecords) # `create` takes an attributes hash, creates a record from it, and saves it given the callback. @create: (attrs, callback) -> if !callback [attrs, callback] = [{}, attrs] obj = new this(attrs) obj.save(callback) obj # `findOrCreate` takes an attributes hash, optionally containing a primary key, and returns to you a saved record # representing those attributes, either from the server or from the identity map. @findOrCreate: (attrs, callback) -> record = new this(attrs) if record.isNew() record.save(callback) else foundRecord = @_mapIdentity(record) foundRecord.updateAttributes(attrs) callback(undefined, foundRecord) @_mapIdentity: (record) -> if typeof (id = record.get('id')) == 'undefined' || id == '' return record else existing = @get("loaded.indexedBy.id").get(id)?.toArray()[0] if existing existing.updateAttributes(record._batman.attributes || {}) return existing else @get('loaded').add(record) return record associationProxy: (association) -> Batman.initializeObject(@) proxies = @_batman.associationProxies ||= new Batman.SimpleHash proxies.get(association.label) or proxies.set(association.label, new association.proxyClass(association, @)) # ### Record API # Add a universally accessible accessor for retrieving the primrary key, regardless of which key its stored under. @accessor 'id', get: -> pk = @constructor.primaryKey if pk == 'id' @id else @get(pk) set: (k, v) -> # naively coerce string ids into integers if typeof v is "string" and v.match(/[^0-9]/) is null v = parseInt(v, 10) pk = @constructor.primaryKey if pk == 'id' @id = v else @set(pk, v) # Add normal accessors for the dirty keys and errors attributes of a record, so these accesses don't fall to the # default accessor. @accessor 'dirtyKeys', 'errors', Batman.Property.defaultAccessor # Add an accessor for the internal batman state under `batmanState`, so that the `state` key can be a valid # attribute. @accessor 'batmanState' get: -> @state() set: (k, v) -> @state(v) # Add a default accessor to make models store their attributes under a namespace by default. @accessor Model.defaultAccessor = get: (k) -> attribute = (@_batman.attributes ||= {})[k] if typeof attribute isnt 'undefined' attribute else @[k] set: (k, v) -> (@_batman.attributes ||= {})[k] = v unset: (k) -> x = (@_batman.attributes ||={})[k] delete @_batman.attributes[k] x # New records can be constructed by passing either an ID or a hash of attributes (potentially # containing an ID) to the Model constructor. By not passing an ID, the model is marked as new. constructor: (idOrAttributes = {}) -> developer.assert @ instanceof Batman.Object, "constructors must be called with new" # We have to do this ahead of super, because mixins will call set which calls things on dirtyKeys. @dirtyKeys = new Batman.Hash @errors = new Batman.ErrorsSet # Find the ID from either the first argument or the attributes. if $typeOf(idOrAttributes) is 'Object' super(idOrAttributes) else super() @set('id', idOrAttributes) @empty() if not @state() # Override the `Batman.Observable` implementation of `set` to implement dirty tracking. set: (key, value) -> # Optimize setting where the value is the same as what's already been set. oldValue = @get(key) return if oldValue is value # Actually set the value and note what the old value was in the tracking array. result = super @dirtyKeys.set(key, oldValue) # Mark the model as dirty if isn't already. @dirty() unless @state() in ['dirty', 'loading', 'creating'] result updateAttributes: (attrs) -> @mixin(attrs) @ toString: -> "#{$functionName(@constructor)}: #{@get('id')}" # `toJSON` uses the various encoders for each key to grab a storable representation of the record. toJSON: -> obj = {} # Encode each key into a new object encoders = @_batman.get('encoders') unless !encoders or encoders.isEmpty() encoders.forEach (key, encoder) => val = @get key if typeof val isnt 'undefined' encodedVal = encoder(val, key, obj, @) if typeof encodedVal isnt 'undefined' obj[key] = encodedVal if @constructor.primaryKey isnt 'id' obj[@constructor.primaryKey] = @get('id') delete obj.id obj # `fromJSON` uses the various decoders for each key to generate a record instance from the JSON # stored in whichever storage mechanism. fromJSON: (data) -> obj = {} decoders = @_batman.get('decoders') # If no decoders were specified, do the best we can to interpret the given JSON by camelizing # each key and just setting the values. if !decoders or decoders.isEmpty() for key, value of data obj[key] = value else # If we do have decoders, use them to get the data. decoders.forEach (key, decoder) => obj[key] = decoder(data[key], key, data, obj, @) unless typeof data[key] is 'undefined' if @constructor.primaryKey isnt 'id' obj.id = data[@constructor.primaryKey] developer.do => if (!decoders) || decoders.length <= 1 developer.warn "Warning: Model #{$functionName(@constructor)} has suspiciously few decoders!" # Mixin the buffer object to use optimized and event-preventing sets used by `mixin`. @mixin obj toParam: -> @get('id') # Each model instance (each record) can be in one of many states throughout its lifetime. Since various # operations on the model are asynchronous, these states are used to indicate exactly what point the # record is at in it's lifetime, which can often be during a save or load operation. @actsAsStateMachine yes # Add the various states to the model. for k in ['empty', 'dirty', 'loading', 'loaded', 'saving', 'saved', 'creating', 'created', 'validating', 'validated', 'destroying', 'destroyed'] @state k for k in ['loading', 'loaded'] @classState k _doStorageOperation: (operation, options, callback) -> developer.assert @hasStorage(), "Can't #{operation} model #{$functionName(@constructor)} without any storage adapters!" adapters = @_batman.get('storage') for adapter in adapters adapter.perform operation, @, {data: options}, callback true hasStorage: -> (@_batman.get('storage') || []).length > 0 # `load` fetches the record from all sources possible load: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't load a destroyed record!")) return @loading() @_doStorageOperation 'read', {}, (err, record) => unless err @loaded() record = @constructor._mapIdentity(record) callback?(err, record) # `save` persists a record to all the storage mechanisms added using `@persist`. `save` will only save # a model if it is valid. save: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't save a destroyed record!")) return @validate (isValid, errors) => if !isValid callback?(errors) return creating = @isNew() do @saving do @creating if creating associations = @constructor._batman.get('associations') # Save belongsTo models immediately since we don't need this model's id associations?.getByType('belongsTo')?.forEach (association, label) => association.apply(@) @_doStorageOperation (if creating then 'create' else 'update'), {}, (err, record) => unless err if creating do @created do @saved @dirtyKeys.clear() associations?.getByType('hasOne')?.forEach (association) -> association.apply(err, record) associations?.getByType('hasMany')?.forEach (association) -> association.apply(err, record) record = @constructor._mapIdentity(record) callback?(err, record) # `destroy` destroys a record in all the stores. destroy: (callback) => do @destroying @_doStorageOperation 'destroy', {}, (err, record) => unless err @constructor.get('all').remove(@) do @destroyed callback?(err) # `validate` performs the record level validations determining the record's validity. These may be asynchronous, # in which case `validate` has no useful return value. Results from asynchronous validations can be received by # listening to the `afterValidation` lifecycle callback. validate: (callback) -> oldState = @state() @errors.clear() do @validating finish = () => do @validated @[oldState]() callback?(@errors.length == 0, @errors) validators = @_batman.get('validators') || [] unless validators.length > 0 finish() else count = validators.length validationCallback = => if --count == 0 finish() for validator in validators v = validator.validator # Run the validator `v` or the custom callback on each key it validates by instantiating a new promise # and passing it to the appropriate function along with the key and the value to be validated. for key in validator.keys if v v.validateEach @errors, @, key, validationCallback else validator.callback @errors, @, key, validationCallback return isNew: -> typeof @get('id') is 'undefined' # ## Associations class Batman.AssociationProxy extends Batman.Object isProxy: true constructor: (@association, @model) -> loaded: false toJSON: -> target = @get('target') @get('target').toJSON() if target? load: (callback) -> @fetch (err, proxiedRecord) => unless err @set 'loaded', true @set 'target', proxiedRecord callback?(err, proxiedRecord) @get('target') fetch: (callback) -> unless (@get('foreignValue') || @get('primaryValue'))? return callback(undefined, undefined) record = @fetchFromLocal() if record return callback(undefined, record) else @fetchFromRemote(callback) @accessor 'loaded', Batman.Property.defaultAccessor @accessor 'target', get: -> @fetchFromLocal() set: (_, v) -> v # This just needs to bust the cache @accessor get: (k) -> @get('target')?.get(k) set: (k, v) -> @get('target')?.set(k, v) class Batman.BelongsToProxy extends Batman.AssociationProxy @accessor 'foreignValue', -> @model.get(@association.foreignKey) fetchFromLocal: -> @association.setIndex().get(@get('foreignValue')) fetchFromRemote: (callback) -> @association.getRelatedModel().find @get('foreignValue'), (error, loadedRecord) => throw error if error callback undefined, loadedRecord class Batman.HasOneProxy extends Batman.AssociationProxy @accessor 'primaryValue', -> @model.get(@association.primaryKey) fetchFromLocal: -> @association.setIndex().get(@get('primaryValue')) fetchFromRemote: (callback) -> loadOptions = {} loadOptions[@association.foreignKey] = @get('primaryValue') @association.getRelatedModel().load loadOptions, (error, loadedRecords) => throw error if error if !loadedRecords or loadedRecords.length <= 0 callback new Error("Couldn't find related record!"), undefined else callback undefined, loadedRecords[0] class Batman.AssociationSet extends Batman.SetSort constructor: (@value, @association) -> base = new Batman.Set super(base, 'hashKey') loaded: false load: (callback) -> return callback(undefined, @) unless @value? loadOptions = {} loadOptions[@association.foreignKey] = @value @association.getRelatedModel().load loadOptions, (err, records) => @loaded = true unless err @fire 'loaded' callback(err, @) class Batman.UniqueAssociationSetIndex extends Batman.UniqueSetIndex constructor: (@association, key) -> super @association.getRelatedModel().get('loaded'), key class Batman.AssociationSetIndex extends Batman.SetIndex constructor: (@association, key) -> super @association.getRelatedModel().get('loaded'), key _resultSetForKey: (key) -> @_storage.getOrSet key, => new Batman.AssociationSet(key, @association) _setResultSet: (key, set) -> @_storage.set key, set class Batman.AssociationCurator extends Batman.SimpleHash @availableAssociations: ['belongsTo', 'hasOne', 'hasMany'] constructor: (@model) -> super() # Contains (association, label) pairs mapped by association type # ie. @storage = {<Association.associationType>: [<Association>, <Association>]} @_byTypeStorage = new Batman.SimpleHash add: (association) -> @set association.label, association unless associationTypeSet = @_byTypeStorage.get(association.associationType) associationTypeSet = new Batman.SimpleSet @_byTypeStorage.set association.associationType, associationTypeSet associationTypeSet.add association getByType: (type) -> @_byTypeStorage.get(type) getByLabel: (label) -> @get(label) reset: -> @forEach (label, association) -> association.reset() true merge: (others...) -> result = super result._byTypeStorage = @_byTypeStorage.merge(others.map (other) -> other._byTypeStorage) result class Batman.Association associationType: '' defaultOptions: saveInline: true autoload: true constructor: (@model, @label, options = {}) -> defaultOptions = namespace: Batman.currentApp name: helpers.camelize(helpers.singularize(@label)) @options = $mixin defaultOptions, @defaultOptions, options # Setup encoders and accessors for this association. The accessor needs reference to this # association object, so curry the association info into the getAccessor, which has the # model applied as the context @model.encode label, @encoder() self = @ getAccessor = -> return self.getAccessor.call(@, self, @model, @label) @model.accessor @label, get: getAccessor set: model.defaultAccessor.set unset: model.defaultAccessor.unset if @url @model.url ||= (recordOptions) -> return self.url(recordOptions) getRelatedModel: -> scope = @options.namespace or Batman.currentApp modelName = @options.name relatedModel = scope?[modelName] developer.do -> if Batman.currentApp? and not relatedModel developer.warn "Related model #{modelName} hasn't loaded yet." relatedModel getFromAttributes: (record) -> record.constructor.defaultAccessor.get.call(record, @label) setIntoAttributes: (record, value) -> record.constructor.defaultAccessor.set.call(record, @label, value) encoder: -> developer.error "You must override encoder in Batman.Association subclasses." setIndex: -> developer.error "You must override setIndex in Batman.Association subclasses." inverse: -> if relatedAssocs = @getRelatedModel()._batman.get('associations') if @options.inverseOf return relatedAssocs.getByLabel(@options.inverseOf) inverse = null relatedAssocs.forEach (label, assoc) => if assoc.getRelatedModel() is @model inverse = assoc inverse reset: -> delete @index true class Batman.SingularAssociation extends Batman.Association isSingular: true getAccessor: (self, model, label) -> # Check whether the relation has already been set on this model if recordInAttributes = self.getFromAttributes(@) return recordInAttributes # Make sure the related model has been loaded if self.getRelatedModel() proxy = @associationProxy(self) Batman.Property.withoutTracking -> if not proxy.get('loaded') and self.options.autoload proxy.load() proxy setIndex: -> @index ||= new Batman.UniqueAssociationSetIndex(@, @[@indexRelatedModelOn]) @index class Batman.PluralAssociation extends Batman.Association isSingular: false setForRecord: (record) -> Batman.Property.withoutTracking => if id = record.get(@primaryKey) @setIndex().get(id) else new Batman.AssociationSet(undefined, @) getAccessor: (self, model, label) -> return unless self.getRelatedModel() # Check whether the relation has already been set on this model if setInAttributes = self.getFromAttributes(@) setInAttributes else relatedRecords = self.setForRecord(@) self.setIntoAttributes(@, relatedRecords) Batman.Property.withoutTracking => if self.options.autoload and not @isNew() and not relatedRecords.loaded relatedRecords.load (error, records) -> throw error if error relatedRecords setIndex: -> @index ||= new Batman.AssociationSetIndex(@, @[@indexRelatedModelOn]) @index class Batman.BelongsToAssociation extends Batman.SingularAssociation associationType: 'belongsTo' proxyClass: Batman.BelongsToProxy indexRelatedModelOn: 'primaryKey' defaultOptions: saveInline: false autoload: true constructor: -> super @foreignKey = @options.foreignKey or "#{@label}_id" @primaryKey = @options.primaryKey or "id" @model.encode @foreignKey url: (recordOptions) -> if inverse = @inverse() root = Batman.helpers.pluralize(@label) id = recordOptions.data?["#{@label}_id"] helper = if inverse.isSingular then "singularize" else "pluralize" ending = Batman.helpers[helper](inverse.label) return "/#{root}/#{id}/#{ending}" encoder: -> association = @ encoder = encode: false decode: (data, _, __, ___, childRecord) -> relatedModel = association.getRelatedModel() record = new relatedModel() record.fromJSON(data) record = relatedModel._mapIdentity(record) if association.options.inverseOf if inverse = association.inverse() if inverse instanceof Batman.HasManyAssociation # Rely on the parent's set index to get this out. childRecord.set(association.foreignKey, record.get(association.primaryKey)) else record.set(inverse.label, childRecord) childRecord.set(association.label, record) record if @options.saveInline encoder.encode = (val) -> val.toJSON() encoder apply: (base) -> if model = base.get(@label) foreignValue = model.get(@primaryKey) if foreignValue isnt undefined base.set @foreignKey, foreignValue class Batman.HasOneAssociation extends Batman.SingularAssociation associationType: 'hasOne' proxyClass: Batman.HasOneProxy indexRelatedModelOn: 'foreignKey' constructor: -> super @primaryKey = @options.primaryKey or "id" @foreignKey = @options.foreignKey or "#{helpers.underscore($functionName(@model))}_id" apply: (baseSaveError, base) -> if relation = @getFromAttributes(base) relation.set @foreignKey, base.get(@primaryKey) encoder: -> association = @ return { encode: (val, key, object, record) -> return unless association.options.saveInline if json = val.toJSON() json[association.foreignKey] = record.get(association.primaryKey) json decode: (data, _, __, ___, parentRecord) -> relatedModel = association.getRelatedModel() record = new (relatedModel)() record.fromJSON(data) if association.options.inverseOf record.set association.options.inverseOf, parentRecord record = relatedModel._mapIdentity(record) record } class Batman.HasManyAssociation extends Batman.PluralAssociation associationType: 'hasMany' indexRelatedModelOn: 'foreignKey' constructor: -> super @primaryKey = @options.primaryKey or "<KEY>" @foreignKey = @options.foreignKey or "#{helpers.underscore($functionName(@model))}_<KEY>" apply: (baseSaveError, base) -> unless baseSaveError if relations = @getFromAttributes(base) relations.forEach (model) => model.set @foreignKey, base.get(@primaryKey) base.set @label, @setForRecord(base) encoder: -> association = @ return { encode: (relationSet, _, __, record) -> return if association._beingEncoded association._beingEncoded = true return unless association.options.saveInline if relationSet? jsonArray = [] relationSet.forEach (relation) -> relationJSON = relation.toJSON() relationJSON[association.foreignKey] = record.get(association.primaryKey) jsonArray.push relationJSON delete association._beingEncoded jsonArray decode: (data, key, _, __, parentRecord) -> if relatedModel = association.getRelatedModel() existingRelations = association.getFromAttributes(parentRecord) || association.setForRecord(parentRecord) existingArray = existingRelations?.toArray() for jsonObject, i in data record = if existingArray && existingArray[i] existing = true existingArray[i] else existing = false new relatedModel() record.fromJSON jsonObject if association.options.inverseOf record.set association.options.inverseOf, parentRecord record = relatedModel._mapIdentity(record) existingRelations.add record else developer.error "Can't decode model #{association.options.name} because it hasn't been loaded yet!" existingRelations } # ### Model Associations API for k in Batman.AssociationCurator.availableAssociations do (k) => Batman.Model[k] = (label, scope) -> Batman.initializeObject(@) collection = @_batman.associations ||= new Batman.AssociationCurator(@) collection.add new Batman["#{helpers.capitalize(k)}Association"](@, label, scope) class Batman.ValidationError extends Batman.Object constructor: (attribute, message) -> super({attribute, message}) # `ErrorSet` is a simple subclass of `Set` which makes it a bit easier to # manage the errors on a model. class Batman.ErrorsSet extends Batman.Set # Define a default accessor to get the set of errors on a key @accessor (key) -> @indexedBy('attribute').get(key) # Define a shorthand method for adding errors to a key. add: (key, error) -> super(new Batman.ValidationError(key, error)) class Batman.Validator extends Batman.Object constructor: (@options, mixins...) -> super mixins... validate: (record) -> developer.error "You must override validate in Batman.Validator subclasses." format: (key, messageKey, interpolations) -> t('errors.format', {attribute: key, message: t("errors.messages.#{messageKey}", interpolations)}) @options: (options...) -> Batman.initializeObject @ if @_batman.options then @_batman.options.concat(options) else @_batman.options = options @matches: (options) -> results = {} shouldReturn = no for key, value of options if ~@_batman?.options?.indexOf(key) results[key] = value shouldReturn = yes return results if shouldReturn Validators = Batman.Validators = [ class Batman.LengthValidator extends Batman.Validator @options 'minLength', 'maxLength', 'length', 'lengthWithin', 'lengthIn' constructor: (options) -> if range = (options.lengthIn or options.lengthWithin) options.minLength = range[0] options.maxLength = range[1] || -1 delete options.lengthWithin delete options.lengthIn super validateEach: (errors, record, key, callback) -> options = @options value = record.get(key) ? [] if options.minLength and value.length < options.minLength errors.add key, @format(key, 'too_short', {count: options.minLength}) if options.maxLength and value.length > options.maxLength errors.add key, @format(key, 'too_long', {count: options.maxLength}) if options.length and value.length isnt options.length errors.add key, @format(key, 'wrong_length', {count: options.length}) callback() class Batman.PresenceValidator extends Batman.Validator @options 'presence' validateEach: (errors, record, key, callback) -> value = record.get(key) if @options.presence && (!value? || value is '') errors.add key, @format(key, 'blank') callback() ] $mixin Batman.translate.messages, errors: format: "%{attribute} %{message}" messages: too_short: "must be at least %{count} characters" too_long: "must be less than %{count} characters" wrong_length: "must be %{count} characters" blank: "can't be blank" class Batman.StorageAdapter extends Batman.Object class @StorageError extends Error name: "StorageError" constructor: (message) -> super @message = message class @RecordExistsError extends @StorageError name: 'RecordExistsError' constructor: (message) -> super(message || "Can't create this record because it already exists in the store!") class @NotFoundError extends @StorageError name: 'NotFoundError' constructor: (message) -> super(message || "Record couldn't be found in storage!") constructor: (model) -> super(model: model) isStorageAdapter: true storageKey: (record) -> model = record?.constructor || @model model.get('storageKey') || helpers.pluralize(helpers.underscore($functionName(model))) getRecordFromData: (attributes, constructor = @model) -> record = new constructor() record.fromJSON(attributes) record @skipIfError: (f) -> return (env, next) -> if env.error? next() else f.call(@, env, next) before: -> @_addFilter('before', arguments...) after: -> @_addFilter('after', arguments...) _inheritFilters: -> if !@_batman.check(@) || !@_batman.filters oldFilters = @_batman.getFirst('filters') @_batman.filters = {before: {}, after: {}} if oldFilters? for position, filtersByKey of oldFilters for key, filtersList of filtersByKey @_batman.filters[position][key] = filtersList.slice(0) _addFilter: (position, keys..., filter) -> @_inheritFilters() for key in keys @_batman.filters[position][key] ||= [] @_batman.filters[position][key].push filter true runFilter: (position, action, env, callback) -> @_inheritFilters() allFilters = @_batman.filters[position].all || [] actionFilters = @_batman.filters[position][action] || [] env.action = action # Action specific filters execute first, and then the `all` filters. filters = actionFilters.concat(allFilters) next = (newEnv) => env = newEnv if newEnv? if (nextFilter = filters.shift())? nextFilter.call @, env, next else callback.call @, env next() runBeforeFilter: -> @runFilter 'before', arguments... runAfterFilter: (action, env, callback) -> @runFilter 'after', action, env, @exportResult(callback) exportResult: (callback) -> (env) -> callback(env.error, env.result, env) _jsonToAttributes: (json) -> JSON.parse(json) perform: (key, recordOrProto, options, callback) -> options ||= {} env = {options} if key == '<KEY>' env.proto = recordOrProto else env.record = recordOrProto next = (newEnv) => env = newEnv if newEnv? @runAfterFilter key, env, callback @runBeforeFilter key, env, (env) -> @[key](env, next) class Batman.LocalStorage extends Batman.StorageAdapter constructor: -> return null if typeof window.localStorage is 'undefined' super @storage = localStorage storageRegExpForRecord: (record) -> new RegExp("^#{@storageKey(record)}(\\d+)$") nextIdForRecord: (record) -> re = @storageRegExpForRecord(record) nextId = 1 @_forAllStorageEntries (k, v) -> if matches = re.exec(k) nextId = Math.max(nextId, parseInt(matches[1], 10) + 1) nextId _forAllStorageEntries: (iterator) -> for i in [0...@storage.length] key = @storage.key(i) iterator.call(@, key, @storage.getItem(key)) true _storageEntriesMatching: (proto, options) -> re = @storageRegExpForRecord(proto) records = [] @_forAllStorageEntries (storageKey, storageString) -> if keyMatches = re.exec(storageKey) data = @_jsonToAttributes(storageString) data[proto.constructor.primaryKey] = keyMatches[1] records.push data if @_dataMatches(options, data) records _dataMatches: (conditions, data) -> match = true for k, v of conditions if data[k] != v match = false break match @::before 'read', 'create', 'update', 'destroy', @skipIfError (env, next) -> if env.action == 'create' env.id = env.record.get('id') || env.record.set('id', @nextIdForRecord(env.record)) else env.id = env.record.get('id') unless env.id? env.error = new @constructor.StorageError("Couldn't get/set record primary key on #{env.action}!") else env.key = @storageKey(env.record) + env.id next() @::before 'create', 'update', @skipIfError (env, next) -> env.recordAttributes = JSON.stringify(env.record) next() @::after 'read', @skipIfError (env, next) -> if typeof env.recordAttributes is 'string' try env.recordAttributes = @_jsonToAttributes(env.recordAttributes) catch error env.error = error return next() env.record.fromJSON env.recordAttributes next() @::after 'read', 'create', 'update', 'destroy', @skipIfError (env, next) -> env.result = env.record next() @::after 'readAll', @skipIfError (env, next) -> env.result = env.records = for recordAttributes in env.recordsAttributes @getRecordFromData(recordAttributes, env.proto.constructor) next() read: @skipIfError (env, next) -> env.recordAttributes = @storage.getItem(env.key) if !env.recordAttributes env.error = new @constructor.NotFoundError() next() create: @skipIfError ({key, recordAttributes}, next) -> if @storage.getItem(key) arguments[0].error = new @constructor.RecordExistsError else @storage.setItem(key, recordAttributes) next() update: @skipIfError ({key, recordAttributes}, next) -> @storage.setItem(key, recordAttributes) next() destroy: @skipIfError ({key}, next) -> @storage.removeItem(key) next() readAll: @skipIfError ({proto, options}, next) -> try arguments[0].recordsAttributes = @_storageEntriesMatching(proto, options.data) catch error arguments[0].error = error next() class Batman.SessionStorage extends Batman.LocalStorage constructor: -> if typeof window.sessionStorage is 'undefined' return null super @storage = sessionStorage class Batman.RestStorage extends Batman.StorageAdapter @JSONContentType: 'application/json' @PostBodyContentType: 'application/x-www-form-urlencoded' defaultRequestOptions: type: 'json' serializeAsForm: true constructor: -> super @defaultRequestOptions = $mixin {}, @defaultRequestOptions recordJsonNamespace: (record) -> helpers.singularize(@storageKey(record)) collectionJsonNamespace: (proto) -> helpers.pluralize(@storageKey(proto)) _execWithOptions: (object, key, options) -> if typeof object[key] is 'function' then object[key](options) else object[key] _defaultCollectionUrl: (record) -> "/#{@storageKey(record)}" urlForRecord: (record, env) -> if record.url url = @_execWithOptions(record, 'url', env.options) else url = if record.constructor.url @_execWithOptions(record.constructor, 'url', env.options) else @_defaultCollectionUrl(record) if env.action != 'create' if (id = record.get('id'))? url = url + "/" + id else throw new @constructor.StorageError("Couldn't get/set record primary key on #{env.action}!") @urlPrefix(record, env) + url + @urlSuffix(record, env) urlForCollection: (model, env) -> url = if model.url @_execWithOptions(model, 'url', env.options) else @_defaultCollectionUrl(model::, env.options) @urlPrefix(model, env) + url + @urlSuffix(model, env) urlPrefix: (object, env) -> @_execWithOptions(object, 'urlPrefix', env.options) || '' urlSuffix: (object, env) -> @_execWithOptions(object, 'urlSuffix', env.options) || '' request: (env, next) -> options = $mixin env.options, success: (data) -> env.data = data error: (error) -> env.error = error loaded: -> env.response = req.get('response') next() req = new Batman.Request(options) perform: (key, record, options, callback) -> $mixin (options ||= {}), @defaultRequestOptions super @::before 'create', 'read', 'update', 'destroy', @skipIfError (env, next) -> try env.options.url = @urlForRecord(env.record, env) catch error env.error = error next() @::before 'readAll', @skipIfError (env, next) -> try env.options.url = @urlForCollection(env.proto.constructor, env) catch error env.error = error next() @::before 'create', 'update', @skipIfError (env, next) -> json = env.record.toJSON() if namespace = @recordJsonNamespace(env.record) data = {} data[namespace] = json else data = json if @serializeAsForm # Leave the POJO in the data for the request adapter to serialize to a body env.options.contentType = @constructor.PostBodyContentType else data = JSON.stringify(data) env.options.contentType = @constructor.JSONContentType env.options.data = data next() @::after 'create', 'read', 'update', @skipIfError (env, next) -> if typeof env.data is 'string' try json = @_jsonToAttributes(env.data) catch error env.error = error return next() else json = env.data namespace = @recordJsonNamespace(env.record) json = json[namespace] if namespace && json[namespace]? env.record.fromJSON(json) env.result = env.record next() @::after 'readAll', @skipIfError (env, next) -> if typeof env.data is 'string' try env.data = JSON.parse(env.env) catch jsonError env.error = jsonError return next() namespace = @collectionJsonNamespace(env.proto) env.recordsAttributes = if namespace && env.data[namespace]? env.data[namespace] else env.data env.result = env.records = for jsonRecordAttributes in env.recordsAttributes @getRecordFromData(jsonRecordAttributes, env.proto.constructor) next() @HTTPMethods = create: 'POST' update: 'PUT' read: 'GET' readAll: 'GET' destroy: 'DELETE' for key in ['create', 'read', 'update', 'destroy', 'readAll'] do (key) => @::[key] = @skipIfError (env, next) -> env.options.method = @constructor.HTTPMethods[key] @request(env, next) # Views # ----------- class Batman.ViewStore extends Batman.Object @prefix: 'views' constructor: -> super @_viewContents = {} @_requestedPaths = new Batman.SimpleSet propertyClass: Batman.Property fetchView: (path) -> developer.do -> unless typeof Batman.View::prefix is 'undefined' developer.warn "Batman.View.prototype.prefix has been removed, please use Batman.ViewStore.prefix instead." new Batman.Request url: Batman.Navigator.normalizePath(@constructor.prefix, "#{path}.html") type: 'html' success: (response) => @set(path, response) error: (response) -> throw new Error("Could not load view from #{path}") @accessor 'final': true get: (path) -> return @get("/#{path}") unless path[0] is '/' return @_viewContents[path] if @_viewContents[path] return if @_requestedPaths.has(path) @fetchView(path) return set: (path, content) -> return @set("/#{path}", content) unless path[0] is '/' @_requestedPaths.add(path) @_viewContents[path] = content prefetch: (path) -> @get(path) true # A `Batman.View` can function two ways: a mechanism to load and/or parse html files # or a root of a subclass hierarchy to create rich UI classes, like in Cocoa. class Batman.View extends Batman.Object isView: true constructor: (options = {}) -> context = options.context if context unless context instanceof Batman.RenderContext context = Batman.RenderContext.root().descend(context) else context = Batman.RenderContext.root() options.context = context.descend(@) super(options) # Start the rendering by asking for the node Batman.Property.withoutTracking => if node = @get('node') @render node else @observe 'node', (node) => @render(node) @store: new Batman.ViewStore() # Set the source attribute to an html file to have that file loaded. source: '' # Set the html to a string of html to have that html parsed. html: '' # Set an existing DOM node to parse immediately. node: null # Fires once a node is parsed. @::event('ready').oneShot = true @accessor 'html', get: -> return @html if @html && @html.length > 0 return unless source = @get 'source' source = Batman.Navigator.normalizePath(source) @html = @constructor.store.get(source) set: (_, html) -> @html = html @accessor 'node' get: -> unless @node html = @get('html') return unless html && html.length > 0 @hasContainer = true @node = document.createElement 'div' $setInnerHTML(@node, html) if @node.children.length > 0 Batman.data(@node.children[0], 'view', @) return @node set: (_, node) -> @node = node Batman.data(@node, 'view', @) updateHTML = (html) => if html? $setInnerHTML(@get('node'), html) @forget('html', updateHTML) @observeAndFire 'html', updateHTML render: (node) -> @event('ready').resetOneShot() @_renderer?.forgetAll() # We use a renderer with the continuation style rendering engine to not # block user interaction for too long during the render. if node @_renderer = new Batman.Renderer(node, null, @context, @) @_renderer.on 'rendered', => @fire('ready', node) @::on 'appear', -> @viewDidAppear? arguments... @::on 'disappear', -> @viewDidDisappear? arguments... @::on 'beforeAppear', -> @viewWillAppear? arguments... @::on 'beforeDisappear', -> @viewWillDisappear? arguments... # DOM Helpers # ----------- # `Batman.Renderer` will take a node and parse all recognized data attributes out of it and its children. # It is a continuation style parser, designed not to block for longer than 50ms at a time if the document # fragment is particularly long. class Batman.Renderer extends Batman.Object deferEvery: 50 constructor: (@node, callback, @context, view) -> super() @on('parsed', callback) if callback? developer.error "Must pass a RenderContext to a renderer for rendering" unless @context instanceof Batman.RenderContext @immediate = $setImmediate @start start: => @startTime = new Date @parseNode @node resume: => @startTime = new Date @parseNode @resumeNode finish: -> @startTime = null @prevent 'stopped' @fire 'parsed' @fire 'rendered' stop: -> $clearImmediate @immediate @fire 'stopped' forgetAll: -> for k in ['parsed', 'rendered', 'stopped'] @::event(k).oneShot = true bindingRegexp = /^data\-(.*)/ bindingSortOrder = ["renderif", "foreach", "formfor", "context", "bind", "source", "target"] bindingSortPositions = {} bindingSortPositions[name] = pos for name, pos in bindingSortOrder _sortBindings: (a,b) -> aindex = bindingSortPositions[a[0]] bindex = bindingSortPositions[b[0]] aindex ?= bindingSortOrder.length # put unspecified bindings last bindex ?= bindingSortOrder.length if aindex > bindex 1 else if bindex > aindex -1 else if a[0] > b[0] 1 else if b[0] > a[0] -1 else 0 parseNode: (node) -> if @deferEvery && (new Date - @startTime) > @deferEvery @resumeNode = node @timeout = $setImmediate @resume return if node.getAttribute and node.attributes bindings = for attr in node.attributes name = attr.nodeName.match(bindingRegexp)?[1] continue if not name if ~(varIndex = name.indexOf('-')) [name.substr(0, varIndex), name.substr(varIndex + 1), attr.value] else [name, attr.value] for readerArgs in bindings.sort(@_sortBindings) key = readerArgs[1] result = if readerArgs.length == 2 Batman.DOM.readers[readerArgs[0]]?(node, key, @context, @) else Batman.DOM.attrReaders[readerArgs[0]]?(node, key, readerArgs[2], @context, @) if result is false skipChildren = true break else if result instanceof Batman.RenderContext oldContext = @context @context = result $onParseExit(node, => @context = oldContext) if (nextNode = @nextNode(node, skipChildren)) then @parseNode(nextNode) else @finish() nextNode: (node, skipChildren) -> if not skipChildren children = node.childNodes return children[0] if children?.length sibling = node.nextSibling # Grab the reference before onParseExit may remove the node $onParseExit(node).forEach (callback) -> callback() $forgetParseExit(node) return if @node == node return sibling if sibling nextParent = node while nextParent = nextParent.parentNode $onParseExit(nextParent).forEach (callback) -> callback() $forgetParseExit(nextParent) return if @node == nextParent parentSibling = nextParent.nextSibling return parentSibling if parentSibling return # The RenderContext class manages the stack of contexts accessible to a view during rendering. class Batman.RenderContext @deProxy: (object) -> if object? && object.isContextProxy then object.get('proxiedObject') else object @root: -> if Batman.currentApp? Batman.currentApp.get('_renderContext') else @base constructor: (@object, @parent) -> findKey: (key) -> base = key.split('.')[0].split('|')[0].trim() currentNode = @ while currentNode # We define the behaviour of the context stack as latching a get when the first key exists, # so we need to check only if the basekey exists, not if all intermediary keys do as well. val = $get(currentNode.object, base) if typeof val isnt 'undefined' val = $get(currentNode.object, key) return [val, currentNode.object].map(@constructor.deProxy) currentNode = currentNode.parent @windowWrapper ||= window: Batman.container [$get(@windowWrapper, key), @windowWrapper] get: (key) -> @findKey(key)[0] # Below are the three primitives that all the `Batman.DOM` helpers are composed of. # `descend` takes an `object`, and optionally a `scopedKey`. It creates a new `RenderContext` leaf node # in the tree with either the object available on the stack or the object available at the `scopedKey` # on the stack. descend: (object, scopedKey) -> if scopedKey oldObject = object object = new Batman.Object() object[scopedKey] = oldObject return new @constructor(object, @) # `descendWithKey` takes a `key` and optionally a `scopedKey`. It creates a new `RenderContext` leaf node # with the runtime value of the `key` available on the stack or under the `scopedKey` if given. This # differs from a normal `descend` in that it looks up the `key` at runtime (in the parent `RenderContext`) # and will correctly reflect changes if the value at the `key` changes. A normal `descend` takes a concrete # reference to an object which never changes. descendWithKey: (key, scopedKey) -> proxy = new ContextProxy(@, key) return @descend(proxy, scopedKey) # `chain` flattens a `RenderContext`'s path to the root. chain: -> x = [] parent = this while parent x.push parent.object parent = parent.parent x # `ContextProxy` is a simple class which assists in pushing dynamic contexts onto the `RenderContext` tree. # This happens when a `data-context` is descended into, for each iteration in a `data-foreach`, # and in other specific HTML bindings like `data-formfor`. `ContextProxy`s use accessors so that if the # value of the object they proxy changes, the changes will be propagated to any thing observing the `ContextProxy`. # This is good because it allows `data-context` to take keys which will change, filtered keys, and even filters # which take keypath arguments. It will calculate the context to descend into when any of those keys change # because it preserves the property of a binding, and importantly it exposes a friendly `Batman.Object` # interface for the rest of the `Binding` code to work with. @ContextProxy = class ContextProxy extends Batman.Object isContextProxy: true # Reveal the binding's final value. @accessor 'proxiedObject', -> @binding.get('filteredValue') # Proxy all gets to the proxied object. @accessor get: (key) -> @get("proxiedObject.#{key}") set: (key, value) -> @set("proxiedObject.#{key}", value) unset: (key) -> @unset("proxiedObject.#{key}") constructor: (@renderContext, @keyPath, @localKey) -> @binding = new Batman.DOM.AbstractBinding(undefined, @keyPath, @renderContext) Batman.RenderContext.base = new Batman.RenderContext(window: Batman.container) Batman.DOM = { # `Batman.DOM.readers` contains the functions used for binding a node's value or innerHTML, showing/hiding nodes, # and any other `data-#{name}=""` style DOM directives. readers: { target: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'nodeChange') true source: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'dataChange') true bind: (node, key, context, renderer, only) -> bindingClass = false switch node.nodeName.toLowerCase() when 'input' switch node.getAttribute('type') when 'checkbox' Batman.DOM.attrReaders.bind(node, 'checked', key, context, renderer, only) return true when 'radio' bindingClass = Batman.DOM.RadioBinding when 'file' bindingClass = Batman.DOM.FileBinding when 'select' bindingClass = Batman.DOM.SelectBinding bindingClass ||= Batman.DOM.Binding new bindingClass(arguments...) true context: (node, key, context, renderer) -> return context.descendWithKey(key) mixin: (node, key, context, renderer) -> new Batman.DOM.MixinBinding(node, key, context.descend(Batman.mixins), renderer) true showif: (node, key, context, parentRenderer, invert) -> new Batman.DOM.ShowHideBinding(node, key, context, parentRenderer, false, invert) true hideif: -> Batman.DOM.readers.showif(arguments..., yes) route: -> new Batman.DOM.RouteBinding(arguments...) true view: -> new Batman.DOM.ViewBinding arguments... false partial: (node, path, context, renderer) -> Batman.DOM.partial node, path, context, renderer true defineview: (node, name, context, renderer) -> $onParseExit(node, -> $removeNode(node)) Batman.View.store.set(Batman.Navigator.normalizePath(name), node.innerHTML) false renderif: (node, key, context, renderer) -> new Batman.DOM.DeferredRenderingBinding(node, key, context, renderer) false yield: (node, key) -> $setImmediate -> Batman.DOM.yield key, node true contentfor: (node, key) -> $setImmediate -> Batman.DOM.contentFor key, node true replace: (node, key) -> $setImmediate -> Batman.DOM.replace key, node true } _yielders: {} # name/fn pairs of yielding functions _yields: {} # name/container pairs of yielding nodes # `Batman.DOM.attrReaders` contains all the DOM directives which take an argument in their name, in the # `data-dosomething-argument="keypath"` style. This means things like foreach, binding attributes like # disabled or anything arbitrary, descending into a context, binding specific classes, or binding to events. attrReaders: { _parseAttribute: (value) -> if value is 'false' then value = false if value is 'true' then value = true value source: (node, attr, key, context, renderer) -> Batman.DOM.attrReaders.bind node, attr, key, context, renderer, 'dataChange' bind: (node, attr, key, context, renderer, only) -> bindingClass = switch attr when 'checked', 'disabled', 'selected' Batman.DOM.CheckedBinding when 'value', 'href', 'src', 'size' Batman.DOM.NodeAttributeBinding when 'class' Batman.DOM.ClassBinding when 'style' Batman.DOM.StyleBinding else Batman.DOM.AttributeBinding new bindingClass(arguments...) true context: (node, contextName, key, context) -> return context.descendWithKey(key, contextName) event: (node, eventName, key, context) -> new Batman.DOM.EventBinding(arguments...) true addclass: (node, className, key, context, parentRenderer, invert) -> new Batman.DOM.AddClassBinding(node, className, key, context, parentRenderer, false, invert) true removeclass: (node, className, key, context, parentRenderer) -> Batman.DOM.attrReaders.addclass node, className, key, context, parentRenderer, yes foreach: (node, iteratorName, key, context, parentRenderer) -> new Batman.DOM.IteratorBinding(arguments...) false # Return false so the Renderer doesn't descend into this node's children. formfor: (node, localName, key, context) -> new Batman.DOM.FormBinding(arguments...) context.descendWithKey(key, localName) view: (node, bindKey, contextKey, context) -> [_, parent] = context.findKey contextKey view = null parent.observeAndFire contextKey, (newValue) -> view ||= Batman.data node, 'view' view?.set bindKey, newValue } # `Batman.DOM.events` contains the helpers used for binding to events. These aren't called by # DOM directives, but are used to handle specific events by the `data-event-#{name}` helper. events: { click: (node, callback, context, eventName = 'click') -> $addEventListener node, eventName, (args...) -> callback node, args..., context $preventDefault args[0] if node.nodeName.toUpperCase() is 'A' and not node.href node.href = '#' node doubleclick: (node, callback, context) -> # The actual DOM event is called `dblclick` Batman.DOM.events.click node, callback, context, 'dblclick' change: (node, callback, context) -> eventNames = switch node.nodeName.toUpperCase() when 'TEXTAREA' then ['keyup', 'change'] when 'INPUT' if node.type.toLowerCase() in Batman.DOM.textInputTypes oldCallback = callback callback = (e) -> return if e.type == 'keyup' && 13 <= e.keyCode <= 14 oldCallback(arguments...) ['keyup', 'change'] else ['change'] else ['change'] for eventName in eventNames $addEventListener node, eventName, (args...) -> callback node, args..., context isEnter: (ev) -> ev.keyCode is 13 || ev.which is 13 || ev.keyIdentifier is 'Enter' || ev.key is 'Enter' submit: (node, callback, context) -> if Batman.DOM.nodeIsEditable(node) $addEventListener node, 'keydown', (args...) -> if Batman.DOM.events.isEnter(args[0]) Batman.DOM._keyCapturingNode = node $addEventListener node, 'keyup', (args...) -> if Batman.DOM.events.isEnter(args[0]) if Batman.DOM._keyCapturingNode is node $preventDefault args[0] callback node, args..., context Batman.DOM._keyCapturingNode = null else $addEventListener node, 'submit', (args...) -> $preventDefault args[0] callback node, args..., context node other: (node, eventName, callback, context) -> $addEventListener node, eventName, (args...) -> callback node, args..., context } # List of input type="types" for which we can use keyup events to track textInputTypes: ['text', 'search', 'tel', 'url', 'email', 'password'] # `yield` and `contentFor` are used to declare partial views and then pull them in elsewhere. # `replace` is used to replace yielded content. # This can be used for abstraction as well as repetition. yield: (name, node) -> Batman.DOM._yields[name] = node # render any content for this yield if yielders = Batman.DOM._yielders[name] fn(node) for fn in yielders contentFor: (name, node, _replaceContent, _yieldChildren) -> yieldingNode = Batman.DOM._yields[name] # Clone the node if it's a child in case the parent gets cleared during the yield if yieldingNode and $isChildOf(yieldingNode, node) node = $cloneNode node yieldFn = (yieldingNode) -> if _replaceContent || !Batman._data(yieldingNode, 'yielded') $setInnerHTML yieldingNode, '', true Batman.DOM.didRemoveNode(child) for child in yieldingNode.children if _yieldChildren while node.childNodes.length > 0 child = node.childNodes[0] view = Batman.data(child, 'view') view?.fire 'beforeAppear', child $appendChild yieldingNode, node.childNodes[0], true view?.fire 'appear', child else view = Batman.data(node, 'view') view?.fire 'beforeAppear', child $appendChild yieldingNode, node, true view?.fire 'appear', child Batman._data node, 'yielded', true Batman._data yieldingNode, 'yielded', true delete Batman.DOM._yielders[name] if contents = Batman.DOM._yielders[name] contents.push yieldFn else Batman.DOM._yielders[name] = [yieldFn] if yieldingNode Batman.DOM.yield name, yieldingNode replace: (name, node, _yieldChildren) -> Batman.DOM.contentFor name, node, true, _yieldChildren partial: (container, path, context, renderer) -> renderer.prevent 'rendered' view = new Batman.View source: path context: context view.on 'ready', -> $setInnerHTML container, '' # Render the partial content into the data-partial node # Text nodes move when they are appended, so copy childNodes children = (node for node in view.get('node').childNodes) $appendChild(container, child) for child in children renderer.allowAndFire 'rendered' # Adds a binding or binding-like object to the `bindings` set in a node's # data, so that upon node removal we can unset the binding and any other objects # it retains. trackBinding: $trackBinding = (binding, node) -> if bindings = Batman._data node, 'bindings' bindings.add binding else Batman._data node, 'bindings', new Batman.SimpleSet(binding) Batman.DOM.fire('bindingAdded', binding) true # Removes listeners and bindings tied to `node`, allowing it to be cleared # or removed without leaking memory unbindNode: $unbindNode = (node) -> # break down all bindings if bindings = Batman._data node, 'bindings' bindings.forEach (binding) -> binding.die() # remove all event listeners if listeners = Batman._data node, 'listeners' for eventName, eventListeners of listeners eventListeners.forEach (listener) -> $removeEventListener node, eventName, listener # remove all bindings and other data associated with this node Batman.removeData node # external data (Batman.data) Batman.removeData node, undefined, true # internal data (Batman._data) # Unbinds the tree rooted at `node`. # When set to `false`, `unbindRoot` skips the `node` before unbinding all of its children. unbindTree: $unbindTree = (node, unbindRoot = true) -> $unbindNode node if unbindRoot $unbindTree(child) for child in node.childNodes # Copy the event handlers from src node to dst node copyNodeEventListeners: $copyNodeEventListeners = (dst, src) -> if listeners = Batman._data src, 'listeners' for eventName, eventListeners of listeners eventListeners.forEach (listener) -> $addEventListener dst, eventName, listener # Copy all event handlers from the src tree to the dst tree. Note that the # trees must have identical structures. copyTreeEventListeners: $copyTreeEventListeners = (dst, src) -> $copyNodeEventListeners dst, src for i in [0...src.childNodes.length] $copyTreeEventListeners dst.childNodes[i], src.childNodes[i] # Enhance the base cloneNode method to copy event handlers over to the new # instance cloneNode: $cloneNode = (node, deep=true) -> newNode = node.cloneNode(deep) if deep $copyTreeEventListeners newNode, node else $copyNodeEventListeners newNode, node newNode # Memory-safe setting of a node's innerHTML property setInnerHTML: $setInnerHTML = (node, html, args...) -> hide.apply(child, args) for child in node.childNodes when hide = Batman.data(child, 'hide') $unbindTree node, false node?.innerHTML = html setStyleProperty: $setStyleProperty = (node, property, value, importance) -> if node.style.setAttribute node.style.setAttribute(property, value, importance) else node.style.setProperty(property, value, importance) # Memory-safe removal of a node from the DOM removeNode: $removeNode = (node) -> node.parentNode?.removeChild node Batman.DOM.didRemoveNode(node) appendChild: $appendChild = (parent, child, args...) -> view = Batman.data(child, 'view') view?.fire 'beforeAppear', child Batman.data(child, 'show')?.apply(child, args) parent.appendChild(child) view?.fire 'appear', child insertBefore: $insertBefore = (parentNode, newNode, referenceNode = null) -> if !referenceNode or parentNode.childNodes.length <= 0 $appendChild parentNode, newNode else parentNode.insertBefore newNode, referenceNode valueForNode: (node, value = '', escapeValue = true) -> isSetting = arguments.length > 1 switch node.nodeName.toUpperCase() when 'INPUT', 'TEXTAREA' if isSetting then (node.value = value) else node.value when 'SELECT' if isSetting then node.value = value else if isSetting $setInnerHTML node, if escapeValue then $escapeHTML(value) else value else node.innerHTML nodeIsEditable: (node) -> node.nodeName.toUpperCase() in ['INPUT', 'TEXTAREA', 'SELECT'] # `$addEventListener uses attachEvent when necessary addEventListener: $addEventListener = (node, eventName, callback) -> # store the listener in Batman.data unless listeners = Batman._data node, 'listeners' listeners = Batman._data node, 'listeners', {} unless listeners[eventName] listeners[eventName] = new Batman.Set listeners[eventName].add callback if $hasAddEventListener node.addEventListener eventName, callback, false else node.attachEvent "on#{eventName}", callback # `$removeEventListener` uses detachEvent when necessary removeEventListener: $removeEventListener = (node, eventName, callback) -> # remove the listener from Batman.data if listeners = Batman._data node, 'listeners' if eventListeners = listeners[eventName] eventListeners.remove callback if $hasAddEventListener node.removeEventListener eventName, callback, false else node.detachEvent 'on'+eventName, callback hasAddEventListener: $hasAddEventListener = !!window?.addEventListener didRemoveNode: (node) -> view = Batman.data node, 'view' view?.fire 'beforeDisappear', node $unbindTree node view?.fire 'disappear', node onParseExit: $onParseExit = (node, callback) -> set = Batman._data(node, 'onParseExit') || Batman._data(node, 'onParseExit', new Batman.SimpleSet) set.add callback if callback? set forgetParseExit: $forgetParseExit = (node, callback) -> Batman.removeData(node, 'onParseExit', true) } $mixin Batman.DOM, Batman.EventEmitter, Batman.Observable Batman.DOM.event('bindingAdded') # Bindings are shortlived objects which manage the observation of any keypaths a `data` attribute depends on. # Bindings parse any keypaths which are filtered and use an accessor to apply the filters, and thus enjoy # the automatic trigger and dependency system that Batman.Objects use. Every, and I really mean every method # which uses filters has to be defined in terms of a new binding. This is so that the proper order of # objects is traversed and any observers are properly attached. class Batman.DOM.AbstractBinding extends Batman.Object # A beastly regular expression for pulling keypaths out of the JSON arguments to a filter. # It makes the following matches: # # + `foo` and `baz.qux` in `foo, "bar", baz.qux` # + `foo.bar.baz` in `true, false, "true", "false", foo.bar.baz` # + `true.bar` in `2, true.bar` # + `truesay` in truesay # + no matches in `"bar", 2, {"x":"y", "Z": foo.bar.baz}, "baz"` keypath_rx = /// (^|,) # Match either the start of an arguments list or the start of a space inbetween commas. \s* # Be insensitive to whitespace between the comma and the actual arguments. (?! # Use a lookahead to ensure we aren't matching true or false: (?:true|false) # Match either true or false ... \s* # and make sure that there's nothing else that comes after the true or false ... (?:$|,) # before the end of this argument in the list. ) ( [a-zA-Z][\w\.]* # Now that true and false can't be matched, match a dot delimited list of keys. [\?\!]? # Allow ? and ! at the end of a keypath to support Ruby's methods ) \s* # Be insensitive to whitespace before the next comma or end of the filter arguments list. (?=$|,) # Match either the next comma or the end of the filter arguments list. ///g # A less beastly pair of regular expressions for pulling out the [] syntax `get`s in a binding string, and # dotted names that follow them. get_dot_rx = /(?:\]\.)(.+?)(?=[\[\.]|\s*\||$)/ get_rx = /(?!^\s*)\[(.*?)\]/g # The `filteredValue` which calculates the final result by reducing the initial value through all the filters. @accessor 'filteredValue' get: -> unfilteredValue = @get('unfilteredValue') self = @ renderContext = @get('renderContext') if @filterFunctions.length > 0 developer.currentFilterStack = renderContext result = @filterFunctions.reduce((value, fn, i) -> # Get any argument keypaths from the context stored at parse time. args = self.filterArguments[i].map (argument) -> if argument._keypath self.renderContext.get(argument._keypath) else argument # Apply the filter. args.unshift value args.push self fn.apply(renderContext, args) , unfilteredValue) developer.currentFilterStack = null result else unfilteredValue # We ignore any filters for setting, because they often aren't reversible. set: (_, newValue) -> @set('unfilteredValue', newValue) # The `unfilteredValue` is whats evaluated each time any dependents change. @accessor 'unfilteredValue' get: -> # If we're working with an `@key` and not an `@value`, find the context the key belongs to so we can # hold a reference to it for passing to the `dataChange` and `nodeChange` observers. if k = @get('key') Batman.RenderContext.deProxy(@get("keyContext.#{k}")) else @get('value') set: (_, value) -> if k = @get('key') keyContext = @get('keyContext') # Supress sets on the window if keyContext != Batman.container @set("keyContext.#{k}", value) else @set('value', value) # The `keyContext` accessor is @accessor 'keyContext', -> @renderContext.findKey(@key)[1] bindImmediately: true shouldSet: true isInputBinding: false escapeValue: true constructor: (@node, @keyPath, @renderContext, @renderer, @only = false) -> # Pull out the `@key` and filter from the `@keyPath`. @parseFilter() # Observe the node and the data. @bind() if @bindImmediately isTwoWay: -> @key? && @filterFunctions.length is 0 bind: -> # Attach the observers. if @node? && @only in [false, 'nodeChange'] and Batman.DOM.nodeIsEditable(@node) Batman.DOM.events.change @node, @_fireNodeChange, @renderContext # Usually, we let the HTML value get updated upon binding by `observeAndFire`ing the dataChange # function below. When dataChange isn't attached, we update the JS land value such that the # sync between DOM and JS is maintained. if @only is 'nodeChange' @_fireNodeChange() # Observe the value of this binding's `filteredValue` and fire it immediately to update the node. if @only in [false, 'dataChange'] @observeAndFire 'filteredValue', @_fireDataChange Batman.DOM.trackBinding(@, @node) if @node? _fireNodeChange: => @shouldSet = false @nodeChange?(@node, @value || @get('keyContext')) @shouldSet = true _fireDataChange: (value) => if @shouldSet @dataChange?(value, @node) die: -> @forget() @_batman.properties?.forEach (key, property) -> property.die() parseFilter: -> # Store the function which does the filtering and the arguments (all except the actual value to apply the # filter to) in these arrays. @filterFunctions = [] @filterArguments = [] # Rewrite [] style gets, replace quotes to be JSON friendly, and split the string by pipes to see if there are any filters. keyPath = @keyPath keyPath = keyPath.replace(get_dot_rx, "]['$1']") while get_dot_rx.test(keyPath) # Stupid lack of lookbehind assertions... filters = keyPath.replace(get_rx, " | get $1 ").replace(/'/g, '"').split(/(?!")\s+\|\s+(?!")/) # The key will is always the first token before the pipe. try key = @parseSegment(orig = filters.shift())[0] catch e developer.warn e developer.error "Error! Couldn't parse keypath in \"#{orig}\". Parsing error above." if key and key._keypath @key = key._keypath else @value = key if filters.length while filterString = filters.shift() # For each filter, get the name and the arguments by splitting on the first space. split = filterString.indexOf(' ') if ~split filterName = filterString.substr(0, split) args = filterString.substr(split) else filterName = filterString # If the filter exists, grab it. if filter = Batman.Filters[filterName] @filterFunctions.push filter # Get the arguments for the filter by parsing the args as JSON, or # just pushing an placeholder array if args try @filterArguments.push @parseSegment(args) catch e developer.error "Bad filter arguments \"#{args}\"!" else @filterArguments.push [] else developer.error "Unrecognized filter '#{filterName}' in key \"#{@keyPath}\"!" true # Turn a piece of a `data` keypath into a usable javascript object. # + replacing keypaths using the above regular expression # + wrapping the `,` delimited list in square brackets # + and `JSON.parse`ing them as an array. parseSegment: (segment) -> JSON.parse( "[" + segment.replace(keypath_rx, "$1{\"_keypath\": \"$2\"}") + "]" ) class Batman.DOM.AbstractAttributeBinding extends Batman.DOM.AbstractBinding constructor: (node, @attributeName, args...) -> super(node, args...) class Batman.DOM.AbstractCollectionBinding extends Batman.DOM.AbstractAttributeBinding bindCollection: (newCollection) -> unless newCollection == @collection @unbindCollection() @collection = newCollection if @collection if @collection.isObservable && @collection.toArray @collection.observe 'toArray', @handleArrayChanged else if @collection.isEventEmitter @collection.on 'itemsWereAdded', @handleItemsWereAdded @collection.on 'itemsWereRemoved', @handleItemsWereRemoved else return false return true return false unbindCollection: -> if @collection if @collection.isObservable && @collection.toArray @collection.forget('toArray', @handleArrayChanged) else if @collection.isEventEmitter @collection.event('itemsWereAdded').removeHandler(@handleItemsWereAdded) @collection.event('itemsWereRemoved').removeHandler(@handleItemsWereRemoved) handleItemsWereAdded: -> handleItemsWereRemoved: -> handleArrayChanged: -> die: -> @unbindCollection() super class Batman.DOM.Binding extends Batman.DOM.AbstractBinding constructor: (node) -> @isInputBinding = node.nodeName.toLowerCase() in ['input', 'textarea'] super nodeChange: (node, context) -> if @isTwoWay() @set 'filteredValue', @node.value dataChange: (value, node) -> Batman.DOM.valueForNode @node, value, @escapeValue class Batman.DOM.AttributeBinding extends Batman.DOM.AbstractAttributeBinding dataChange: (value) -> @node.setAttribute(@attributeName, value) nodeChange: (node) -> if @isTwoWay() @set 'filteredValue', Batman.DOM.attrReaders._parseAttribute(node.getAttribute(@attributeName)) class Batman.DOM.NodeAttributeBinding extends Batman.DOM.AbstractAttributeBinding dataChange: (value = "") -> @node[@attributeName] = value nodeChange: (node) -> if @isTwoWay() @set 'filteredValue', Batman.DOM.attrReaders._parseAttribute(node[@attributeName]) class Batman.DOM.ShowHideBinding extends Batman.DOM.AbstractBinding constructor: (node, className, key, context, parentRenderer, @invert = false) -> display = node.style.display display = '' if not display or display is 'none' @originalDisplay = display super dataChange: (value) -> view = Batman.data @node, 'view' if !!value is not @invert view?.fire 'beforeAppear', @node Batman.data(@node, 'show')?.call(@node) @node.style.display = @originalDisplay view?.fire 'appear', @node else view?.fire 'beforeDisappear', @node if typeof (hide = Batman.data(@node, 'hide')) is 'function' hide.call @node else $setStyleProperty(@node, 'display', 'none', 'important') view?.fire 'disappear', @node class Batman.DOM.CheckedBinding extends Batman.DOM.NodeAttributeBinding isInputBinding: true dataChange: (value) -> @node[@attributeName] = !!value # Update the parent's binding if necessary if @node.parentNode Batman._data(@node.parentNode, 'updateBinding')?() constructor: -> super # Attach this binding to the node under the attribute name so that parent # bindings can query this binding and modify its state. This is useful # for <options> within a select or radio buttons. Batman._data @node, @attributeName, @ class Batman.DOM.ClassBinding extends Batman.DOM.AbstractCollectionBinding dataChange: (value) -> if value? @unbindCollection() if typeof value is 'string' @node.className = value else @bindCollection(value) @updateFromCollection() updateFromCollection: -> if @collection array = if @collection.map @collection.map((x) -> x) else (k for own k,v of @collection) array = array.toArray() if array.toArray? @node.className = array.join ' ' handleArrayChanged: => @updateFromCollection() handleItemsWereRemoved: => @updateFromCollection() handleItemsWereAdded: => @updateFromCollection() class Batman.DOM.DeferredRenderingBinding extends Batman.DOM.AbstractBinding rendered: false constructor: -> super @node.removeAttribute "data-renderif" nodeChange: -> dataChange: (value) -> if value && !@rendered @render() render: -> new Batman.Renderer(@node, null, @renderContext) @rendered = true class Batman.DOM.AddClassBinding extends Batman.DOM.AbstractAttributeBinding constructor: (node, className, keyPath, renderContext, renderer, only, @invert = false) -> names = className.split('|') @classes = for name in names { name: name pattern: new RegExp("(?:^|\\s)#{name}(?:$|\\s)", 'i') } super delete @attributeName dataChange: (value) -> currentName = @node.className for {name, pattern} in @classes includesClassName = pattern.test(currentName) if !!value is !@invert @node.className = "#{currentName} #{name}" if !includesClassName else @node.className = currentName.replace(pattern, '') if includesClassName true class Batman.DOM.EventBinding extends Batman.DOM.AbstractAttributeBinding bindImmediately: false constructor: (node, eventName, key, context) -> super confirmText = @node.getAttribute('data-confirm') callback = => return if confirmText and not confirm(confirmText) @get('filteredValue')?.apply @get('callbackContext'), arguments if attacher = Batman.DOM.events[@attributeName] attacher @node, callback, context else Batman.DOM.events.other @node, @attributeName, callback, context @accessor 'callbackContext', -> contextKeySegments = @key.split('.') contextKeySegments.pop() if contextKeySegments.length > 0 @get('keyContext').get(contextKeySegments.join('.')) else @get('keyContext') class Batman.DOM.RadioBinding extends Batman.DOM.AbstractBinding isInputBinding: true dataChange: (value) -> # don't overwrite `checked` attributes in the HTML unless a bound # value is defined in the context. if no bound value is found, bind # to the key if the node is checked. if (boundValue = @get('filteredValue'))? @node.checked = boundValue == @node.value else if @node.checked @set 'filteredValue', @node.value nodeChange: (node) -> if @isTwoWay() @set('filteredValue', Batman.DOM.attrReaders._parseAttribute(node.value)) class Batman.DOM.FileBinding extends Batman.DOM.AbstractBinding isInputBinding: true nodeChange: (node, subContext) -> return if !@isTwoWay() segments = @key.split('.') if segments.length > 1 keyContext = subContext.get(segments.slice(0, -1).join('.')) else keyContext = subContext actualObject = Batman.RenderContext.deProxy(keyContext) if actualObject.hasStorage && actualObject.hasStorage() for adapter in actualObject._batman.get('storage') when adapter instanceof Batman.RestStorage adapter.defaultRequestOptions.formData = true if node.hasAttribute('multiple') @set 'filteredValue', Array::slice.call(node.files) else @set 'filteredValue', node.files[0] class Batman.DOM.MixinBinding extends Batman.DOM.AbstractBinding dataChange: (value) -> $mixin @node, value if value? class Batman.DOM.SelectBinding extends Batman.DOM.AbstractBinding isInputBinding: true bindImmediately: false firstBind: true constructor: -> super # wait for the select to render before binding to it @renderer.on 'rendered', => if @node? Batman._data @node, 'updateBinding', @updateSelectBinding @bind() dataChange: (newValue) => # For multi-select boxes, the `value` property only holds the first # selection, so go through the child options and update as necessary. if newValue instanceof Array # Use a hash to map values to their nodes to avoid O(n^2). valueToChild = {} for child in @node.children # Clear all options. child.selected = false # Avoid collisions among options with same values. matches = valueToChild[child.value] if matches then matches.push child else matches = [child] valueToChild[child.value] = matches # Select options corresponding to the new values for value in newValue for match in valueToChild[value] match.selected = yes # For a regular select box, update the value. else if typeof newValue is 'undefined' && @firstBind @firstBind = false @set('unfilteredValue', @node.value) else Batman.DOM.valueForNode(@node, newValue, @escapeValue) # Finally, update the options' `selected` bindings @updateOptionBindings() nodeChange: => if @isTwoWay() @updateSelectBinding() @updateOptionBindings() updateSelectBinding: => # Gather the selected options and update the binding selections = if @node.multiple then (c.value for c in @node.children when c.selected) else @node.value selections = selections[0] if typeof selections is Array && selections.length == 1 @set 'unfilteredValue', selections true updateOptionBindings: => # Go through the option nodes and update their bindings using the # context and key attached to the node via Batman.data for child in @node.children if selectedBinding = Batman._data(child, 'selected') selectedBinding.nodeChange(selectedBinding.node) true class Batman.DOM.StyleBinding extends Batman.DOM.AbstractCollectionBinding class @SingleStyleBinding extends Batman.DOM.AbstractAttributeBinding constructor: (args..., @parent) -> super(args...) dataChange: (value) -> @parent.setStyle(@attributeName, value) constructor: -> @oldStyles = {} super dataChange: (value) -> unless value @reapplyOldStyles() return @unbindCollection() if typeof value is 'string' @reapplyOldStyles() for style in value.split(';') # handle a case when css value contains colons itself (absolute URI) # split and rejoin because IE7/8 don't splice values of capturing regexes into split's return array [cssName, colonSplitCSSValues...] = style.split(":") @setStyle cssName, colonSplitCSSValues.join(":") return if value instanceof Batman.Hash if @bindCollection(value) value.forEach (key, value) => @setStyle key, value else if value instanceof Object @reapplyOldStyles() for own key, keyValue of value # Check whether the value is an existing keypath, and if so bind this attribute to it [keypathValue, keypathContext] = @renderContext.findKey(keyValue) if keypathValue @bindSingleAttribute key, keyValue @setStyle key, keypathValue else @setStyle key, keyValue handleItemsWereAdded: (newKey) => @setStyle newKey, @collection.get(newKey); return handleItemsWereRemoved: (oldKey) => @setStyle oldKey, ''; return bindSingleAttribute: (attr, keyPath) -> new @constructor.SingleStyleBinding(@node, attr, keyPath, @renderContext, @renderer, @only, @) setStyle: (key, value) => return unless key key = <KEY>(key.<KEY>) @oldStyles[key] = @node.style[key] @node.style[key] = if value then value.trim() else "" reapplyOldStyles: -> @setStyle(cssName, cssValue) for own cssName, cssValue of @oldStyles class Batman.DOM.RouteBinding extends Batman.DOM.AbstractBinding onATag: false @accessor 'dispatcher', -> @renderContext.get('dispatcher') || Batman.App.get('current.dispatcher') bind: -> if @node.nodeName.toUpperCase() is 'A' @onATag = true super Batman.DOM.events.click @node, => params = @pathFromValue(@get('filteredValue')) Batman.redirect params if params? dataChange: (value) -> if value? path = @pathFromValue(value) if @onATag if path? path = Batman.navigator.linkTo path else path = "#" @node.href = path pathFromValue: (value) -> if value.isNamedRouteQuery value.get('path') else @get('dispatcher')?.pathFromParams(value) class Batman.DOM.ViewBinding extends Batman.DOM.AbstractBinding constructor: -> super @renderer.prevent 'rendered' @node.removeAttribute 'data-view' dataChange: (viewClassOrInstance) -> return unless viewClassOrInstance? if viewClassOrInstance.isView @view = viewClassOrInstance @view.set 'node', @node @view.set 'context', @renderContext else @view = new viewClassOrInstance node: @node context: @renderContext parentView: @renderContext.findKey('isView')?[1] Batman.data @node, 'view', @view @view.on 'ready', => @view.awakeFromHTML? @node @view.fire 'beforeAppear', @node @renderer.allowAndFire 'rendered' @view.fire 'appear', @node @die() class Batman.DOM.FormBinding extends Batman.DOM.AbstractAttributeBinding @current: null errorClass: 'error' defaultErrorsListSelector: 'div.errors' @accessor 'errorsListSelector', -> @get('node').getAttribute('data-errors-list') || @defaultErrorsListSelector constructor: (node, contextName, keyPath, renderContext, renderer, only) -> super @contextName = contextName delete @attributeName Batman.DOM.events.submit @get('node'), (node, e) -> $preventDefault e Batman.DOM.on 'bindingAdded', @bindingWasAdded @setupErrorsList() bindingWasAdded: (binding) => if binding.isInputBinding && $isChildOf(@get('node'), binding.get('node')) if ~(index = binding.get('key').indexOf(@contextName)) # If the binding is to a key on the thing passed to formfor node = binding.get('node') field = binding.get('key').slice(index + @contextName.length + 1) # Slice off up until the context and the following dot new Batman.DOM.AddClassBinding(node, @errorClass, @get('keyPath') + " | get 'errors.#{field}.length'", @renderContext, @renderer) setupErrorsList: -> if @errorsListNode = @get('node').querySelector?(@get('errorsListSelector')) $setInnerHTML @errorsListNode, @errorsListHTML() unless @errorsListNode.getAttribute 'data-showif' @errorsListNode.setAttribute 'data-showif', "#{@contextName}.errors.length" errorsListHTML: -> """ <ul> <li data-foreach-error="#{@contextName}.errors" data-bind="error.attribute | append ' ' | append error.message"></li> </ul> """ die: -> Batman.DOM.forget 'bindingAdded', @bindingWasAdded super class Batman.DOM.IteratorBinding extends Batman.DOM.AbstractCollectionBinding deferEvery: 50 currentActionNumber: 0 queuedActionNumber: 0 bindImmediately: false constructor: (sourceNode, @iteratorName, @key, @context, @parentRenderer) -> @nodeMap = new Batman.SimpleHash @actionMap = new Batman.SimpleHash @rendererMap = new Batman.SimpleHash @actions = [] @prototypeNode = sourceNode.cloneNode(true) @prototypeNode.removeAttribute "data-foreach-#{@iteratorName}" @pNode = sourceNode.parentNode previousSiblingNode = sourceNode.nextSibling @siblingNode = document.createComment "end #{@iteratorName}" @siblingNode[Batman.expando] = sourceNode[Batman.expando] delete sourceNode[Batman.expando] if Batman.canDeleteExpando $insertBefore sourceNode.parentNode, @siblingNode, previousSiblingNode # Remove the original node once the parent has moved past it. @parentRenderer.on 'parsed', => # Move any Batman._data from the sourceNode to the sibling; we need to # retain the bindings, and we want to dispose of the node. $removeNode sourceNode # Attach observers. @bind() # Don't let the parent emit its rendered event until all the children have. # This `prevent`'s matching allow is run once the queue is empty in `processActionQueue`. @parentRenderer.prevent 'rendered' # Tie this binding to a node using the default behaviour in the AbstractBinding super(@siblingNode, @iteratorName, @key, @context, @parentRenderer) @fragment = document.createDocumentFragment() parentNode: -> @siblingNode.parentNode die: -> super @dead = true unbindCollection: -> if @collection @nodeMap.forEach (item) => @cancelExistingItem(item) super dataChange: (newCollection) -> if @collection != newCollection @removeAll() @bindCollection(newCollection) # Unbinds the old collection as well. if @collection if @collection.toArray @handleArrayChanged() else if @collection.forEach @collection.forEach (item) => @addOrInsertItem(item) else @addOrInsertItem(key) for own key, value of @collection else developer.warn "Warning! data-foreach-#{@iteratorName} called with an undefined binding. Key was: #{@key}." @processActionQueue() handleItemsWereAdded: (items...) => @addOrInsertItem(item, {fragment: false}) for item in items; return handleItemsWereRemoved: (items...) => @removeItem(item) for item in items; return handleArrayChanged: => newItemsInOrder = @collection.toArray() nodesToRemove = (new Batman.SimpleHash).merge(@nodeMap) for item in newItemsInOrder @addOrInsertItem(item, {fragment: false}) nodesToRemove.unset(item) nodesToRemove.forEach (item, node) => @removeItem(item) addOrInsertItem: (item, options = {}) -> existingNode = @nodeMap.get(item) if existingNode @insertItem(item, existingNode) else @addItem(item, options) addItem: (item, options = {fragment: true}) -> @parentRenderer.prevent 'rendered' # Remove any renderers in progress or actions lined up for an item, since we now know # this item belongs at the end of the queue. @cancelExistingItemActions(item) if @actionMap.get(item)? self = @ options.actionNumber = @queuedActionNumber++ # Render out the child in the custom context, and insert it once the render has completed the parse. childRenderer = new Batman.Renderer @_nodeForItem(item), (-> self.rendererMap.unset(item) self.insertItem(item, @node, options) ), @renderContext.descend(item, @iteratorName) @rendererMap.set(item, childRenderer) finish = => return if @dead @parentRenderer.allowAndFire 'rendered' childRenderer.on 'rendered', finish childRenderer.on 'stopped', => return if @dead @actions[options.actionNumber] = false finish() @processActionQueue() item removeItem: (item) -> return if @dead || !item? oldNode = @nodeMap.unset(item) @cancelExistingItem(item) if oldNode if hideFunction = Batman.data oldNode, 'hide' hideFunction.call(oldNode) else $removeNode(oldNode) removeAll: -> @nodeMap.forEach (item) => @removeItem(item) insertItem: (item, node, options = {}) -> return if @dead if !options.actionNumber? options.actionNumber = @queuedActionNumber++ existingActionNumber = @actionMap.get(item) if existingActionNumber > options.actionNumber # Another action for this item is scheduled for the future, do it then instead of now. Actions # added later enforce order, so we make this one a noop and let the later one have its proper effects. @actions[options.actionNumber] = -> else # Another action has been scheduled for this item. It hasn't been done yet because # its in the actionmap, but this insert is scheduled to happen after it. Skip it since its now defunct. if existingActionNumber @cancelExistingItemActions(item) # Update the action number map to now reflect this new action which will go on the end of the queue. @actionMap.set item, options.actionNumber @actions[options.actionNumber] = -> show = Batman.data node, 'show' if typeof show is 'function' show.call node, before: @siblingNode else if options.fragment @fragment.appendChild node else $insertBefore @parentNode(), node, @siblingNode if addItem = node.getAttribute 'data-additem' [_, context] = @renderer.context.findKey addItem context?[addItem]?(item, node) @actions[options.actionNumber].item = item @processActionQueue() cancelExistingItem: (item) -> @cancelExistingItemActions(item) @cancelExistingItemRender(item) cancelExistingItemActions: (item) -> oldActionNumber = @actionMap.get(item) # Only remove actions which haven't been completed yet. if oldActionNumber? && oldActionNumber >= @currentActionNumber @actions[oldActionNumber] = false @actionMap.unset item cancelExistingItemRender: (item) -> oldRenderer = @rendererMap.get(item) if oldRenderer oldRenderer.stop() $removeNode(oldRenderer.node) @rendererMap.unset item processActionQueue: -> return if @dead unless @actionQueueTimeout # Prevent the parent which will then be allowed when the timeout actually runs @actionQueueTimeout = $setImmediate => return if @dead delete @actionQueueTimeout startTime = new Date while (f = @actions[@currentActionNumber])? delete @actions[@currentActionNumber] @actionMap.unset f.item f.call(@) if f @currentActionNumber++ if @deferEvery && (new Date - startTime) > @deferEvery return @processActionQueue() if @fragment && @rendererMap.length is 0 && @fragment.hasChildNodes() $insertBefore @parentNode(), @fragment, @siblingNode @fragment = document.createDocumentFragment() if @currentActionNumber == @queuedActionNumber @parentRenderer.allowAndFire 'rendered' _nodeForItem: (item) -> newNode = @prototypeNode.cloneNode(true) @nodeMap.set(item, newNode) newNode # Filters # ------- # # `Batman.Filters` contains the simple, determininistic tranforms used in view bindings to # make life a little easier. buntUndefined = (f) -> (value) -> if typeof value is 'undefined' undefined else f.apply(@, arguments) filters = Batman.Filters = raw: buntUndefined (value, binding) -> binding.escapeValue = false value get: buntUndefined (value, key) -> if value.get? value.get(key) else value[key] equals: buntUndefined (lhs, rhs, binding) -> lhs is rhs not: (value, binding) -> ! !!value matches: buntUndefined (value, searchFor) -> value.indexOf(searchFor) isnt -1 truncate: buntUndefined (value, length, end = "...", binding) -> if !binding binding = end end = "..." if value.length > length value = value.substr(0, length-end.length) + end value default: (value, string, binding) -> value || string prepend: (value, string, binding) -> string + value append: (value, string, binding) -> value + string replace: buntUndefined (value, searchFor, replaceWith, flags, binding) -> if !binding binding = flags flags = undefined # Work around FF issue, "foo".replace("foo","bar",undefined) throws an error if flags is undefined value.replace searchFor, replaceWith else value.replace searchFor, replaceWith, flags downcase: buntUndefined (value) -> value.toLowerCase() upcase: buntUndefined (value) -> value.toUpperCase() pluralize: buntUndefined (string, count) -> helpers.pluralize(count, string) join: buntUndefined (value, withWhat = '', binding) -> if !binding binding = withWhat withWhat = '' value.join(withWhat) sort: buntUndefined (value) -> value.sort() map: buntUndefined (value, key) -> value.map((x) -> $get(x, key)) has: (set, item) -> return false unless set? Batman.contains(set, item) first: buntUndefined (value) -> value[0] meta: buntUndefined (value, keypath) -> developer.assert value.meta, "Error, value doesn't have a meta to filter on!" value.meta.get(keypath) interpolate: (string, interpolationKeypaths, binding) -> if not binding binding = interpolationKeypaths interpolationKeypaths = undefined return if not string values = {} for k, v of interpolationKeypaths values[k] = @findKey(v)[0] if !values[k]? Batman.developer.warn "Warning! Undefined interpolation key #{k} for interpolation", string values[k] = '' Batman.helpers.interpolate(string, values) # allows you to curry arguments to a function via a filter withArguments: (block, curryArgs..., binding) -> return if not block return (regularArgs...) -> block.call @, curryArgs..., regularArgs... routeToAction: buntUndefined (model, action) -> params = Batman.Dispatcher.paramsFromArgument(model) params.action = action params escape: buntUndefined($escapeHTML) for k in ['capitalize', 'singularize', 'underscore', 'camelize'] filters[k] = buntUndefined helpers[k] developer.addFilters() # Data # ---- $mixin Batman, cache: {} uuid: 0 expando: "batman" + Math.random().toString().replace(/\D/g, '') # Test to see if it's possible to delete an expando from an element # Fails in Internet Explorer canDeleteExpando: try div = document.createElement 'div' delete div.test catch e Batman.canDeleteExpando = false noData: # these throw exceptions if you attempt to add expandos to them "embed": true, # Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true hasData: (elem) -> elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando]) !!elem and !isEmptyDataObject(elem) data: (elem, name, data, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando getByName = typeof name == "string" cache = Batman.cache # Only defining an ID for JS objects if its cache already exists allows # the code to shortcut on the same path as a DOM node with no cache id = elem[Batman.expando] # Avoid doing any more work than we need to when trying to get data on an # object that has no data at all if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined return unless id # Also check that it's not a text node; IE can't set expandos on them if elem.nodeType isnt 3 elem[Batman.expando] = id = ++Batman.uuid else id = Batman.expando cache[id] = {} unless cache[id] # An object can be passed to Batman._data instead of a key/value pair; this gets # shallow copied over onto the existing cache if typeof name == "object" or typeof name == "function" if pvt cache[id][internalKey] = $mixin(cache[id][internalKey], name) else cache[id] = $mixin(cache[id], name) thisCache = cache[id] # Internal Batman data is stored in a separate object inside the object's data # cache in order to avoid key collisions between internal data and user-defined # data if pvt thisCache[internalKey] ||= {} thisCache = thisCache[internalKey] if data != undefined thisCache[name] = data # Check for both converted-to-camel and non-converted data property names # If a data property was specified if getByName # First try to find as-is property data ret = thisCache[name] else ret = thisCache return ret removeData: (elem, name, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando isNode = elem.nodeType # non DOM-nodes have their data attached directly cache = Batman.cache id = elem[Batman.expando] # If there is already no cache entry for this object, there is no # purpose in continuing return unless cache[id] if name thisCache = if pvt then cache[id][internalKey] else cache[id] if thisCache # Support interoperable removal of hyphenated or camelcased keys delete thisCache[name] # If there is no data left in the cache, we want to continue # and let the cache object itself get destroyed return unless isEmptyDataObject(thisCache) if pvt delete cache[id][internalKey] # Don't destroy the parent cache unless the internal data object # had been the only thing left in it return unless isEmptyDataObject(cache[id]) internalCache = cache[id][internalKey] # Browsers that fail expando deletion also refuse to delete expandos on # the window, but it will allow it on all other JS objects; other browsers # don't care # Ensure that `cache` is not a window object if Batman.canDeleteExpando or !cache.setInterval delete cache[id] else cache[id] = null # We destroyed the entire user cache at once because it's faster than # iterating through each key, but we need to continue to persist internal # data if it existed if internalCache cache[id] = {} cache[id][internalKey] = internalCache # Otherwise, we need to eliminate the expando on the node to avoid # false lookups in the cache for entries that no longer exist else if Batman.canDeleteExpando delete elem[Batman.expando] else if elem.removeAttribute elem.removeAttribute Batman.expando else elem[Batman.expando] = null # For internal use only _data: (elem, name, data) -> Batman.data elem, name, data, true # A method for determining if a DOM node can handle the data expando acceptData: (elem) -> if elem.nodeName match = Batman.noData[elem.nodeName.toLowerCase()] if match return !(match == true or elem.getAttribute("classid") != match) return true isEmptyDataObject = (obj) -> for name of obj return false return true # Mixins # ------ mixins = Batman.mixins = new Batman.Object() # Encoders # ------ Batman.Encoders = {} class Batman.Paginator extends Batman.Object class @Range constructor: (@offset, @limit) -> @reach = offset + limit coversOffsetAndLimit: (offset, limit) -> offset >= @offset and (offset + limit) <= @reach class @Cache extends @Range constructor: (@offset, @limit, @items) -> super @length = items.length itemsForOffsetAndLimit: (offset, limit) -> begin = offset-@offset end = begin + limit if begin < 0 padding = new Array(-begin) begin = 0 slice = @items.slice(begin, end) if padding padding.concat(slice) else slice offset: 0 limit: 10 totalCount: 0 markAsLoadingOffsetAndLimit: (offset, limit) -> @loadingRange = new Batman.Paginator.Range(offset, limit) markAsFinishedLoading: -> delete @loadingRange offsetFromPageAndLimit: (page, limit) -> Math.round((+page - 1) * limit) pageFromOffsetAndLimit: (offset, limit) -> offset / limit + 1 _load: (offset, limit) -> return if @loadingRange?.coversOffsetAndLimit(offset, limit) @markAsLoadingOffsetAndLimit(offset, limit) @loadItemsForOffsetAndLimit(offset, limit) toArray: -> cache = @get('cache') offset = @get('offset') limit = @get('limit') @_load(offset, limit) unless cache?.coversOffsetAndLimit(offset, limit) cache?.itemsForOffsetAndLimit(offset, limit) or [] page: -> @pageFromOffsetAndLimit(@get('offset'), @get('limit')) pageCount: -> Math.ceil(@get('totalCount') / @get('limit')) previousPage: -> @set('page', @get('page')-1) nextPage: -> @set('page', @get('page')+1) loadItemsForOffsetAndLimit: (offset, limit) -> # override on subclasses or instances updateCache: (offset, limit, items) -> cache = new Batman.Paginator.Cache(offset, limit, items) return if @loadingRange? and not cache.coversOffsetAndLimit(@loadingRange.offset, @loadingRange.limit) @markAsFinishedLoading() @set('cache', cache) @accessor 'toArray', @::toArray @accessor 'offset', 'limit', 'totalCount' get: Batman.Property.defaultAccessor.get set: (key, value) -> Batman.Property.defaultAccessor.set.call(this, key, +value) @accessor 'page', get: @::page set: (_,value) -> value = +value @set('offset', @offsetFromPageAndLimit(value, @get('limit'))) value @accessor 'pageCount', @::pageCount class Batman.ModelPaginator extends Batman.Paginator cachePadding: 0 paddedOffset: (offset) -> offset -= @cachePadding if offset < 0 then 0 else offset paddedLimit: (limit) -> limit + @cachePadding * 2 loadItemsForOffsetAndLimit: (offset, limit) -> params = @paramsForOffsetAndLimit(offset, limit) params[k] = v for k,v of @params @model.load params, (err, records) => if err? @markAsFinishedLoading() @fire('error', err) else @updateCache(@offsetFromParams(params), @limitFromParams(params), records) # override these to fetch records however you like: paramsForOffsetAndLimit: (offset, limit) -> offset: @paddedOffset(offset), limit: @paddedLimit(limit) offsetFromParams: (params) -> params.offset limitFromParams: (params) -> params.limit # Support AMD loaders if typeof define is 'function' define 'batman', [], -> Batman # Optionally export global sugar. Not sure what to do with this. Batman.exportHelpers = (onto) -> for k in ['mixin', 'unmixin', 'route', 'redirect', 'typeOf', 'redirect', 'setImmediate'] onto["$#{k}"] = Batman[k] onto Batman.exportGlobals = () -> Batman.exportHelpers(Batman.container)
true
# # batman.js # # Created by PI:NAME:<NAME>END_PI # Copyright 2011, Shopify # # The global namespace, the `Batman` function will also create also create a new # instance of Batman.Object and mixin all arguments to it. Batman = (mixins...) -> new Batman.Object mixins... Batman.version = '0.8.0' Batman.config = pathPrefix: '/' usePushState: no Batman.container = if exports? module.exports = Batman global else window.Batman = Batman window # Global Helpers # ------- # `$typeOf` returns a string that contains the built-in class of an object # like `String`, `Array`, or `Object`. Note that only `Object` will be returned for # the entire prototype chain. Batman.typeOf = $typeOf = (object) -> return "Undefined" if typeof object == 'undefined' _objectToString.call(object).slice(8, -1) # Cache this function to skip property lookups. _objectToString = Object.prototype.toString # `$mixin` applies every key from every argument after the first to the # first argument. If a mixin has an `initialize` method, it will be called in # the context of the `to` object, and it's key/values won't be applied. Batman.mixin = $mixin = (to, mixins...) -> hasSet = typeof to.set is 'function' for mixin in mixins continue if $typeOf(mixin) isnt 'Object' for own key, value of mixin continue if key in ['initialize', 'uninitialize', 'prototype'] if hasSet to.set(key, value) else if to.nodeName? Batman.data to, key, value else to[key] = value if typeof mixin.initialize is 'function' mixin.initialize.call to to # `$unmixin` removes every key/value from every argument after the first # from the first argument. If a mixin has a `deinitialize` method, it will be # called in the context of the `from` object and won't be removed. Batman.unmixin = $unmixin = (from, mixins...) -> for mixin in mixins for key of mixin continue if key in ['initialize', 'uninitialize'] delete from[key] if typeof mixin.uninitialize is 'function' mixin.uninitialize.call from from # `$functionName` returns the name of a given function, if any # Used to deal with functions not having the `name` property in IE Batman._functionName = $functionName = (f) -> return f.__name__ if f.__name__ return f.name if f.name f.toString().match(/\W*function\s+([\w\$]+)\(/)?[1] # `$preventDefault` checks for preventDefault, since it's not # always available across all browsers Batman._preventDefault = $preventDefault = (e) -> if typeof e.preventDefault is "function" then e.preventDefault() else e.returnValue = false Batman._isChildOf = $isChildOf = (parentNode, childNode) -> node = childNode.parentNode while node return true if node == parentNode node = node.parentNode false $setImmediate = $clearImmediate = null _implementImmediates = (container) -> canUsePostMessage = -> return false unless container.postMessage async = true oldMessage = container.onmessage container.onmessage = -> async = false container.postMessage("","*") container.onmessage = oldMessage async tasks = new Batman.SimpleHash count = 0 getHandle = -> "go#{++count}" if container.setImmediate $setImmediate = container.setImmediate $clearImmediate = container.clearImmediate else if container.msSetImmediate $setImmediate = msSetImmediate $clearImmediate = msClearImmediate else if canUsePostMessage() prefix = 'com.batman.' functions = new Batman.SimpleHash handler = (e) -> return unless ~e.data.search(prefix) handle = e.data.substring(prefix.length) tasks.unset(handle)?() if container.addEventListener container.addEventListener('message', handler, false) else container.attachEvent('onmessage', handler) $setImmediate = (f) -> tasks.set(handle = getHandle(), f) container.postMessage(prefix+handle, "*") handle $clearImmediate = (handle) -> tasks.unset(handle) else if typeof document isnt 'undefined' && "onreadystatechange" in document.createElement("script") $setImmediate = (f) -> handle = getHandle() script = document.createElement("script") script.onreadystatechange = -> tasks.get(handle)?() script.onreadystatechange = null script.parentNode.removeChild(script) script = null document.documentElement.appendChild(script) handle $clearImmediate = (handle) -> tasks.unset(handle) else $setImmediate = (f) -> setTimeout(f, 0) $clearImmediate = (handle) -> clearTimeout(handle) Batman.setImmediate = $setImmediate Batman.clearImmediate = $clearImmediate Batman.setImmediate = $setImmediate = -> _implementImmediates(Batman.container) Batman.setImmediate.apply(@, arguments) Batman.clearImmediate = $clearImmediate = -> _implementImmediates(Batman.container) Batman.clearImmediate.apply(@, arguments) Batman.forEach = $forEach = (container, iterator, ctx) -> if container.forEach container.forEach(iterator, ctx) else if container.indexOf iterator.call(ctx, e, i, container) for e,i in container else iterator.call(ctx, k, v, container) for k,v of container Batman.objectHasKey = $objectHasKey = (object, key) -> if typeof object.hasKey is 'function' object.hasKey(key) else key of object Batman.contains = $contains = (container, item) -> if container.indexOf item in container else if typeof container.has is 'function' container.has(item) else $objectHasKey(container, item) Batman.get = $get = (base, key) -> if typeof base.get is 'function' base.get(key) else Batman.Property.forBaseAndKey(base, key).getValue() Batman.escapeHTML = $escapeHTML = do -> replacements = "&": "&amp;" "<": "&lt;" ">": "&gt;" "\"": "&#34;" "'": "&#39;" return (s) -> (""+s).replace(/[&<>'"]/g, (c) -> replacements[c]) # `translate` is hook for the i18n extra to override and implemnent. All strings which might # be shown to the user pass through this method. `translate` is aliased to `t` internally. Batman.translate = (x, values = {}) -> helpers.interpolate($get(Batman.translate.messages, x), values) Batman.translate.messages = {} t = -> Batman.translate(arguments...) # Developer Tooling # ----------------- Batman.developer = suppressed: false DevelopmentError: (-> DevelopmentError = (@message) -> @name = "DevelopmentError" DevelopmentError:: = Error:: DevelopmentError )() _ie_console: (f, args) -> console?[f] "...#{f} of #{args.length} items..." unless args.length == 1 console?[f] arg for arg in args suppress: (f) -> developer.suppressed = true if f f() developer.suppressed = false unsuppress: -> developer.suppressed = false log: -> return if developer.suppressed or !(console?.log?) if console.log.apply then console.log(arguments...) else developer._ie_console "log", arguments warn: -> return if developer.suppressed or !(console?.warn?) if console.warn.apply then console.warn(arguments...) else developer._ie_console "warn", arguments error: (message) -> throw new developer.DevelopmentError(message) assert: (result, message) -> developer.error(message) unless result do: (f) -> f() unless developer.suppressed addFilters: -> $mixin Batman.Filters, log: (value, key) -> console?.log? arguments value logStack: (value) -> console?.log? developer.currentFilterStack value developer = Batman.developer developer.assert (->).bind, "Error! Batman needs Function.bind to work! Please shim it using something like es5-shim or augmentjs!" # Helpers # ------- # Just a few random Rails-style string helpers. You can add more # to the Batman.helpers object. class Batman.Inflector plural: [] singular: [] uncountable: [] @plural: (regex, replacement) -> @::plural.unshift [regex, replacement] @singular: (regex, replacement) -> @::singular.unshift [regex, replacement] @irregular: (singular, plural) -> if singular.charAt(0) == plural.charAt(0) @plural new RegExp("(#{singular.charAt(0)})#{singular.slice(1)}$", "i"), "$1" + plural.slice(1) @plural new RegExp("(#{singular.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + plural.slice(1) @singular new RegExp("(#{plural.charAt(0)})#{plural.slice(1)}$", "i"), "$1" + singular.slice(1) else @plural new RegExp("#{singular}$", 'i'), plural @plural new RegExp("#{plural}$", 'i'), plural @singular new RegExp("#{plural}$", 'i'), singular @uncountable: (strings...) -> @::uncountable = @::uncountable.concat(strings.map((x) -> new RegExp("#{x}$", 'i'))) @plural(/$/, 's') @plural(/s$/i, 's') @plural(/(ax|test)is$/i, '$1es') @plural(/(octop|vir)us$/i, '$1i') @plural(/(octop|vir)i$/i, '$1i') @plural(/(alias|status)$/i, '$1es') @plural(/(bu)s$/i, '$1ses') @plural(/(buffal|tomat)o$/i, '$1oes') @plural(/([ti])um$/i, '$1a') @plural(/([ti])a$/i, '$1a') @plural(/sis$/i, 'ses') @plural(/(?:([^f])fe|([lr])f)$/i, '$1$2ves') @plural(/(hive)$/i, '$1s') @plural(/([^aeiouy]|qu)y$/i, '$1ies') @plural(/(x|ch|ss|sh)$/i, '$1es') @plural(/(matr|vert|ind)(?:ix|ex)$/i, '$1ices') @plural(/([m|l])ouse$/i, '$1ice') @plural(/([m|l])ice$/i, '$1ice') @plural(/^(ox)$/i, '$1en') @plural(/^(oxen)$/i, '$1') @plural(/(quiz)$/i, '$1zes') @singular(/s$/i, '') @singular(/(n)ews$/i, '$1ews') @singular(/([ti])a$/i, '$1um') @singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '$1$2sis') @singular(/(^analy)ses$/i, '$1sis') @singular(/([^f])ves$/i, '$1fe') @singular(/(hive)s$/i, '$1') @singular(/(tive)s$/i, '$1') @singular(/([lr])ves$/i, '$1f') @singular(/([^aeiouy]|qu)ies$/i, '$1y') @singular(/(s)eries$/i, '$1eries') @singular(/(m)ovies$/i, '$1ovie') @singular(/(x|ch|ss|sh)es$/i, '$1') @singular(/([m|l])ice$/i, '$1ouse') @singular(/(bus)es$/i, '$1') @singular(/(o)es$/i, '$1') @singular(/(shoe)s$/i, '$1') @singular(/(cris|ax|test)es$/i, '$1is') @singular(/(octop|vir)i$/i, '$1us') @singular(/(alias|status)es$/i, '$1') @singular(/^(ox)en/i, '$1') @singular(/(vert|ind)ices$/i, '$1ex') @singular(/(matr)ices$/i, '$1ix') @singular(/(quiz)zes$/i, '$1') @singular(/(database)s$/i, '$1') @irregular('person', 'people') @irregular('man', 'men') @irregular('child', 'children') @irregular('sex', 'sexes') @irregular('move', 'moves') @irregular('cow', 'kine') @irregular('zombie', 'zombies') @uncountable('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans') ordinalize: (number) -> absNumber = Math.abs(parseInt(number)) if absNumber % 100 in [11..13] number + "th" else switch absNumber % 10 when 1 number + "st" when 2 number + "nd" when 3 number + "rd" else number + "th" pluralize: (word) -> for uncountableRegex in @uncountable return word if uncountableRegex.test(word) for [regex, replace_string] in @plural return word.replace(regex, replace_string) if regex.test(word) word singularize: (word) -> for uncountableRegex in @uncountable return word if uncountableRegex.test(word) for [regex, replace_string] in @singular return word.replace(regex, replace_string) if regex.test(word) word camelize_rx = /(?:^|_|\-)(.)/g capitalize_rx = /(^|\s)([a-z])/g underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g underscore_rx2 = /([a-z\d])([A-Z])/g helpers = Batman.helpers = inflector: new Batman.Inflector ordinalize: -> helpers.inflector.ordinalize.apply helpers.inflector, arguments singularize: -> helpers.inflector.singularize.apply helpers.inflector, arguments pluralize: (count, singular, plural) -> if arguments.length < 2 helpers.inflector.pluralize count else "#{count || 0} " + if +count is 1 then singular else (plural || helpers.inflector.pluralize(singular)) camelize: (string, firstLetterLower) -> string = string.replace camelize_rx, (str, p1) -> p1.toUpperCase() if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string underscore: (string) -> string.replace(underscore_rx1, '$1_$2') .replace(underscore_rx2, '$1_$2') .replace('-', '_').toLowerCase() capitalize: (string) -> string.replace capitalize_rx, (m,p1,p2) -> p1 + p2.toUpperCase() trim: (string) -> if string then string.trim() else "" interpolate: (stringOrObject, keys) -> if typeof stringOrObject is 'object' string = stringOrObject[keys.count] unless string string = stringOrObject['other'] else string = stringOrObject for key, value of keys string = string.replace(new RegExp("%\\{#{key}\\}", "g"), value) string class Batman.Event @forBaseAndKey: (base, key) -> if base.isEventEmitter base.event(key) else new Batman.Event(base, key) constructor: (@base, @key) -> @handlers = new Batman.SimpleSet @_preventCount = 0 isEvent: true isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key hashKey: -> @hashKey = -> key key = "<Batman.Event base: #{Batman.Hash::hashKeyFor(@base)}, key: \"#{Batman.Hash::PI:KEY:<KEY>END_PIKeyFor(@key)}\">" addHandler: (handler) -> @handlers.add(handler) @autofireHandler(handler) if @oneShot this removeHandler: (handler) -> @handlers.remove(handler) this eachHandler: (iterator) -> @handlers.forEach(iterator) if @base?.isEventEmitter key = @key @base._batman.ancestors (ancestor) -> if ancestor.isEventEmitter and ancestor.hasEvent(key) handlers = ancestor.event(key).handlers handlers.forEach(iterator) handlerContext: -> @base prevent: -> ++@_preventCount allow: -> --@_preventCount if @_preventCount @_preventCount isPrevented: -> @_preventCount > 0 autofireHandler: (handler) -> if @_oneShotFired and @_oneShotArgs? handler.apply(@handlerContext(), @_oneShotArgs) resetOneShot: -> @_oneShotFired = false @_oneShotArgs = null fire: -> return false if @isPrevented() or @_oneShotFired context = @handlerContext() args = arguments if @oneShot @_oneShotFired = true @_oneShotArgs = arguments @eachHandler (handler) -> handler.apply(context, args) allowAndFire: -> @allow() @fire(arguments...) Batman.EventEmitter = isEventEmitter: true hasEvent: (key) -> @_batman?.get?('events')?.hasKey(key) event: (key) -> Batman.initializeObject @ eventClass = @eventClass or Batman.Event events = @_batman.events ||= new Batman.SimpleHash if events.hasKey(key) existingEvent = events.get(key) else existingEvents = @_batman.get('events') newEvent = events.set(key, new eventClass(this, key)) newEvent.oneShot = existingEvents?.get(key)?.oneShot newEvent on: (key, handler) -> @event(key).addHandler(handler) registerAsMutableSource: -> Batman.Property.registerSource(@) mutation: (wrappedFunction) -> -> result = wrappedFunction.apply(this, arguments) @event('change').fire(this, this) result prevent: (key) -> @event(key).prevent() @ allow: (key) -> @event(key).allow() @ isPrevented: (key) -> @event(key).isPrevented() fire: (key, args...) -> @event(key).fire(args...) allowAndFire: (key, args...) -> @event(key).allowAndFire(args...) class Batman.PropertyEvent extends Batman.Event eachHandler: (iterator) -> @base.eachObserver(iterator) handlerContext: -> @base.base class Batman.Property $mixin @prototype, Batman.EventEmitter @_sourceTrackerStack: [] @sourceTracker: -> (stack = @_sourceTrackerStack)[stack.length - 1] @defaultAccessor: get: (key) -> @[key] set: (key, val) -> @[key] = val unset: (key) -> x = @[key]; delete @[key]; x cachable: no @forBaseAndKey: (base, key) -> if base.isObservable base.property(key) else new Batman.Keypath(base, key) @withoutTracking: (block) -> @pushDummySourceTracker() try block() finally @popSourceTracker() @registerSource: (obj) -> return unless obj.isEventEmitter @sourceTracker()?.add(obj) @pushSourceTracker: -> Batman.Property._sourceTrackerStack.push(new Batman.SimpleSet) @pushDummySourceTracker: -> Batman.Property._sourceTrackerStack.push(null) @popSourceTracker: -> Batman.Property._sourceTrackerStack.pop() constructor: (@base, @key) -> developer.do => keyType = $typeOf(@key) if keyType in ['Array', 'Object'] developer.log "Accessing a property with an #{keyType} key. This is okay, but could be a source of memory leaks if you aren't careful." _isolationCount: 0 cached: no value: null sources: null isProperty: true isDead: false eventClass: Batman.PropertyEvent isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key hashKey: -> @hashKey = -> key key = "<PI:KEY:<KEY>END_PI.Property base: #{BPI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI(@base)}, key: \"PI:KEY:<KEY>END_PI changeEvent: -> event = @event('change') @changeEvent = -> event event accessor: -> keyAccessors = @base._batman?.get('keyAccessors') accessor = if keyAccessors && (val = keyAccessors.get(@key)) val else @base._batman?.getFirst('defaultAccessor') or Batman.Property.defaultAccessor @accessor = -> accessor accessor eachObserver: (iterator) -> key = @key @changeEvent().handlers.forEach(iterator) if @base.isObservable @base._batman.ancestors (ancestor) -> if ancestor.isObservable and ancestor.hasProperty(key) property = ancestor.property(key) handlers = property.changeEvent().handlers handlers.forEach(iterator) observers: -> results = [] @eachObserver (observer) -> results.push(observer) results hasObservers: -> @observers().length > 0 updateSourcesFromTracker: -> newSources = @constructor.popSourceTracker() handler = @sourceChangeHandler() @_eachSourceChangeEvent (e) -> e.removeHandler(handler) @sources = newSources @_eachSourceChangeEvent (e) -> e.addHandler(handler) _eachSourceChangeEvent: (iterator) -> return unless @sources? @sources.forEach (source) -> iterator(source.event('change')) getValue: -> @registerAsMutableSource() unless @isCached() @constructor.pushSourceTracker() try @value = @valueFromAccessor() @cached = yes finally @updateSourcesFromTracker() @value isCachable: -> return true if @isFinal() cachable = @accessor().cachable if cachable? then !!cachable else true isCached: -> @isCachable() and @cached isFinal: -> !!@accessor()['final'] refresh: -> @cached = no previousValue = @value value = @getValue() if value isnt previousValue and not @isIsolated() @fire(value, previousValue) @lockValue() if @value isnt undefined and @isFinal() sourceChangeHandler: -> handler = => @_handleSourceChange() @sourceChangeHandler = -> handler handler _handleSourceChange: -> if @isIsolated() @_needsRefresh = yes else if not @isFinal() && not @hasObservers() @cached = no else @refresh() valueFromAccessor: -> @accessor().get?.call(@base, @key) setValue: (val) -> return unless set = @accessor().set @_changeValue -> set.call(@base, @key, val) unsetValue: -> return unless unset = @accessor().unset @_changeValue -> unset.call(@base, @key) _changeValue: (block) -> @cached = no @constructor.pushDummySourceTracker() try result = block.apply(this) @refresh() finally @constructor.popSourceTracker() @die() unless @isCached() or @hasObservers() result forget: (handler) -> if handler? @changeEvent().removeHandler(handler) else @changeEvent().handlers.clear() observeAndFire: (handler) -> @observe(handler) handler.call(@base, @value, @value) observe: (handler) -> @changeEvent().addHandler(handler) @getValue() unless @sources? this _removeHandlers: -> handler = @sourceChangeHandler() @_eachSourceChangeEvent (e) -> e.removeHandler(handler) delete @sources @changeEvent().handlers.clear() lockValue: -> @_removeHandlers() @getValue = -> @value @setValue = @unsetValue = @refresh = @observe = -> die: -> @_removeHandlers() @base._batman?.properties?.unset(@key) @isDead = true fire: -> @changeEvent().fire(arguments...) isolate: -> if @_isolationCount is 0 @_preIsolationValue = @getValue() @_isolationCount++ expose: -> if @_isolationCount is 1 @_isolationCount-- if @_needsRefresh @value = @_preIsolationValue @refresh() else if @value isnt @_preIsolationValue @fire(@value, @_preIsolationValue) @_preIsolationValue = null else if @_isolationCount > 0 @_isolationCount-- isIsolated: -> @_isolationCount > 0 # Keypaths # -------- class Batman.Keypath extends Batman.Property constructor: (base, key) -> if $typeOf(key) is 'String' @segments = key.split('.') @depth = @segments.length else @segments = [key] @depth = 1 super slice: (begin, end=@depth) -> base = @base for segment in @segments.slice(0, begin) return unless base? and base = $get(base, segment) propertyClass = base.propertyClass or Batman.Keypath remainingSegments = @segments.slice(begin, end) remainingPath = remainingSegments.join('.') if propertyClass is Batman.Keypath or remainingSegments.length is 1 Batman.Keypath.forBaseAndKey(base, remainingPath) else new Batman.Keypath(base, remainingPath) terminalProperty: -> @slice -1 valueFromAccessor: -> if @depth is 1 then super else @terminalProperty()?.getValue() setValue: (val) -> if @depth is 1 then super else @terminalProperty()?.setValue(val) unsetValue: -> if @depth is 1 then super else @terminalProperty()?.unsetValue() # Observable # ---------- # Batman.Observable is a generic mixin that can be applied to any object to allow it to be bound to. # It is applied by default to every instance of `Batman.Object` and subclasses. Batman.Observable = isObservable: true hasProperty: (key) -> @_batman?.properties?.hasKey?(key) property: (key) -> Batman.initializeObject @ propertyClass = @propertyClass or Batman.Keypath properties = @_batman.properties ||= new Batman.SimpleHash properties.get(key) or properties.set(key, new propertyClass(this, key)) get: (key) -> @property(key).getValue() set: (key, val) -> @property(key).setValue(val) unset: (key) -> @property(key).unsetValue() getOrSet: (key, valueFunction) -> currentValue = @get(key) unless currentValue currentValue = valueFunction() @set(key, currentValue) currentValue # `forget` removes an observer from an object. If the callback is passed in, # its removed. If no callback but a key is passed in, all the observers on # that key are removed. If no key is passed in, all observers are removed. forget: (key, observer) -> if key @property(key).forget(observer) else @_batman.properties?.forEach (key, property) -> property.forget() @ # `fire` tells any observers attached to a key to fire, manually. # `prevent` stops of a given binding from firing. `prevent` calls can be repeated such that # the same number of calls to allow are needed before observers can be fired. # `allow` unblocks a property for firing observers. Every call to prevent # must have a matching call to allow later if observers are to be fired. # `observe` takes a key and a callback. Whenever the value for that key changes, your # callback will be called in the context of the original object. observe: (key, args...) -> @property(key).observe(args...) @ observeAndFire: (key, args...) -> @property(key).observeAndFire(args...) @ # Objects # ------- # `Batman.initializeObject` is called by all the methods in Batman.Object to ensure that the # object's `_batman` property is initialized and it's own. Classes extending Batman.Object inherit # methods like `get`, `set`, and `observe` by default on the class and prototype levels, such that # both instances and the class respond to them and can be bound to. However, CoffeeScript's static # class inheritance copies over all class level properties indiscriminately, so a parent class' # `_batman` object will get copied to its subclasses, transferring all the information stored there and # allowing subclasses to mutate parent state. This method prevents this undesirable behaviour by tracking # which object the `_batman_` object was initialized upon, and reinitializing if that has changed since # initialization. Batman.initializeObject = (object) -> if object._batman? object._batman.check(object) else object._batman = new _Batman(object) # _Batman provides a convienient, parent class and prototype aware place to store hidden # object state. Things like observers, accessors, and states belong in the `_batman` object # attached to every Batman.Object subclass and subclass instance. Batman._Batman = class _Batman constructor: (@object, mixins...) -> $mixin(@, mixins...) if mixins.length > 0 # Used by `Batman.initializeObject` to ensure that this `_batman` was created referencing # the object it is pointing to. check: (object) -> if object != @object object._batman = new _Batman(object) return false return true # `get` is a prototype and class aware property access method. `get` will traverse the prototype chain, asking # for the passed key at each step, and then attempting to merge the results into one object. # It can only do this if at each level an `Array`, `Hash`, or `Set` is found, so try to use # those if you need `_batman` inhertiance. get: (key) -> # Get all the keys from the ancestor chain results = @getAll(key) switch results.length when 0 undefined when 1 results[0] else # And then try to merge them if there is more than one. Use `concat` on arrays, and `merge` on # sets and hashes. if results[0].concat? results = results.reduceRight (a, b) -> a.concat(b) else if results[0].merge? results = results.reduceRight (a, b) -> a.merge(b) results # `getFirst` is a prototype and class aware property access method. `getFirst` traverses the prototype chain, # and returns the value of the first `_batman` object which defines the passed key. Useful for # times when the merged value doesn't make sense or the value is a primitive. getFirst: (key) -> results = @getAll(key) results[0] # `getAll` is a prototype and class chain iterator. When passed a key or function, it applies it to each # parent class or parent prototype, and returns the undefined values, closest ancestor first. getAll: (keyOrGetter) -> # Get a function which pulls out the key from the ancestor's `_batman` or use the passed function. if typeof keyOrGetter is 'function' getter = keyOrGetter else getter = (ancestor) -> ancestor._batman?[keyOrGetter] # Apply it to all the ancestors, and then this `_batman`'s object. results = @ancestors(getter) if val = getter(@object) results.unshift val results # `ancestors` traverses the prototype or class chain and returns the application of a function to each # object in the chain. `ancestors` does this _only_ to the `@object`'s ancestors, and not the `@object` # itsself. ancestors: (getter = (x) -> x) -> results = [] # Decide if the object is a class or not, and pull out the first ancestor isClass = !!@object.prototype parent = if isClass @object.__super__?.constructor else if (proto = Object.getPrototypeOf(@object)) == @object @object.constructor.__super__ else proto if parent? parent._batman?.check(parent) # Apply the function and store the result if it isn't undefined. val = getter(parent) results.push(val) if val? # Use a recursive call to `_batman.ancestors` on the ancestor, which will take the next step up the chain. if parent._batman? results = results.concat(parent._batman.ancestors(getter)) results set: (key, value) -> @[key] = value # `Batman.Object` is the base class for all other Batman objects. It is not abstract. class BatmanObject extends Object Batman.initializeObject(this) Batman.initializeObject(@prototype) # Setting `isGlobal` to true will cause the class name to be defined on the # global object. For example, Batman.Model will be aliased to window.Model. # This should be used sparingly; it's mostly useful for debugging. @global: (isGlobal) -> return if isGlobal is false Batman.container[$functionName(@)] = @ # Apply mixins to this class. @classMixin: -> $mixin @, arguments... # Apply mixins to instances of this class. @mixin: -> @classMixin.apply @prototype, arguments mixin: @classMixin counter = 0 _objectID: -> @_objectID = -> c c = counter++ hashKey: -> return if typeof @isEqual is 'function' @hashKey = -> key key = "<Batman.Object #{@_objectID()}>" toJSON: -> obj = {} for own key, value of @ when key not in ["_batman", "hashKey", "_objectID"] obj[key] = if value?.toJSON then value.toJSON() else value obj # Accessor implementation. Accessors are used to create properties on a class or prototype which can be fetched # with get, but are computed instead of just stored. This is a batman and old browser friendly version of # `defineProperty` without as much goodness. # # Accessors track which other properties they rely on for computation, and when those other properties change, # an accessor will recalculate its value and notifiy its observers. This way, when a source value is changed, # any dependent accessors will automatically update any bindings to them with a new value. Accessors accomplish # this feat by tracking `get` calls, do be sure to use `get` to retrieve properties inside accessors. # # `@accessor` or `@classAccessor` can be called with zero, one, or many keys to attach the accessor to. This # has the following effects: # # * zero: create a `defaultAccessor`, which will be called when no other properties or accessors on an object # match a keypath. This is similar to `method_missing` in Ruby or `#doesNotUnderstand` in Smalltalk. # * one: create a `keyAccessor` at the given key, which will only be called when that key is `get`ed. # * many: create `keyAccessors` for each given key, which will then be called whenever each key is `get`ed. # # Note: This function gets called in all sorts of different contexts by various # other pointers to it, but it acts the same way on `this` in all cases. getAccessorObject = (accessor) -> accessor = {get: accessor} if !accessor.get && !accessor.set && !accessor.unset accessor @classAccessor: (keys..., accessor) -> Batman.initializeObject @ # Create a default accessor if no keys have been given. if keys.length is 0 # The `accessor` argument is wrapped in `getAccessorObject` which allows functions to be passed in # as a shortcut to {get: function} @_batman.defaultAccessor = getAccessorObject(accessor) else # Otherwise, add key accessors for each key given. @_batman.keyAccessors ||= new Batman.SimpleHash @_batman.keyAccessors.set(key, getAccessorObject(accessor)) for key in keys # Support adding accessors to the prototype from within class defintions or after the class has been created # with `KlassExtendingBatmanObject.accessor(keys..., accessorObject)` @accessor: -> @classAccessor.apply @prototype, arguments # Support adding accessors to instances after creation accessor: @classAccessor constructor: (mixins...) -> @_batman = new _Batman(@) @mixin mixins... # Make every subclass and their instances observable. @classMixin Batman.EventEmitter, Batman.Observable @mixin Batman.EventEmitter, Batman.Observable # Observe this property on every instance of this class. @observeAll: -> @::observe.apply @prototype, arguments @singleton: (singletonMethodName="sharedInstance") -> @classAccessor singletonMethodName, get: -> @["_#{singletonMethodName}"] ||= new @ Batman.Object = BatmanObject class Batman.Accessible extends Batman.Object constructor: -> @accessor.apply(@, arguments) class Batman.TerminalAccessible extends Batman.Accessible propertyClass: Batman.Property # Collections Batman.Enumerable = isEnumerable: true map: (f, ctx = Batman.container) -> r = []; @forEach(-> r.push f.apply(ctx, arguments)); r mapToProperty: (key) -> r = []; @forEach((item) -> r.push item.get(key)); r every: (f, ctx = Batman.container) -> r = true; @forEach(-> r = r && f.apply(ctx, arguments)); r some: (f, ctx = Batman.container) -> r = false; @forEach(-> r = r || f.apply(ctx, arguments)); r reduce: (f, r) -> count = 0 self = @ @forEach -> if r? then r = f(r, arguments..., count, self) else r = arguments[0] r filter: (f) -> r = new @constructor if r.add wrap = (r, e) -> r.add(e) if f(e); r else if r.set wrap = (r, k, v) -> r.set(k, v) if f(k, v); r else r = [] unless r.push wrap = (r, e) -> r.push(e) if f(e); r @reduce wrap, r # Provide this simple mixin ability so that during bootstrapping we don't have to use `$mixin`. `$mixin` # will correctly attempt to use `set` on the mixinee, which ends up requiring the definition of # `SimpleSet` to be complete during its definition. $extendsEnumerable = (onto) -> onto[k] = v for k,v of Batman.Enumerable class Batman.SimpleHash constructor: (obj) -> @_storage = {} @length = 0 @update(obj) if obj? $extendsEnumerable(@::) propertyClass: Batman.Property hasKey: (key) -> if pairs = @_storage[@hashKeyFor(key)] for pair in pairs return true if @equality(pair[0], key) return false get: (key) -> if pairs = @_storage[@hashKeyFor(key)] for pair in pairs return pair[1] if @equality(pair[0], key) set: (key, val) -> pairs = @_storage[@hashKeyFor(key)] ||= [] for pair in pairs if @equality(pair[0], key) return pair[1] = val @length++ pairs.push([key, val]) val unset: (key) -> hashKey = @hashKeyFor(key) if pairs = @_storage[hashKey] for [obj,value], index in pairs if @equality(obj, key) pair = pairs.splice(index,1) delete @_storage[hashKey] unless pairs.length @length-- return pair[0][1] getOrSet: Batman.Observable.getOrSet hashKeyFor: (obj) -> obj?.hashKey?() or obj equality: (lhs, rhs) -> return true if lhs is rhs return true if lhs isnt lhs and rhs isnt rhs # when both are NaN return true if lhs?.isEqual?(rhs) and rhs?.isEqual?(lhs) return false forEach: (iterator, ctx) -> for key, values of @_storage iterator.call(ctx, obj, value, this) for [obj, value] in values.slice() keys: -> result = [] # Explicitly reference this foreach so that if it's overriden in subclasses the new implementation isn't used. Batman.SimpleHash::forEach.call @, (key) -> result.push key result clear: -> @_storage = {} @length = 0 isEmpty: -> @length is 0 merge: (others...) -> merged = new @constructor others.unshift(@) for hash in others hash.forEach (obj, value) -> merged.set obj, value merged update: (object) -> @set(k,v) for k,v of object replace: (object) -> @forEach (key, value) => @unset(key) unless key of object @update(object) toObject: -> obj = {} for key, pair of @_storage obj[key] = pair[0][1] # the first value for this key obj toJSON: @::toObject class Batman.Hash extends Batman.Object class @Metadata extends Batman.Object constructor: (@hash) -> @accessor 'length', -> @hash.registerAsMutableSource() @hash.length @accessor 'isEmpty', -> @hash.isEmpty() @accessor 'keys', -> @hash.keys() constructor: -> @meta = new @constructor.Metadata(this) Batman.SimpleHash.apply(@, arguments) super $extendsEnumerable(@::) propertyClass: Batman.Property @accessor get: Batman.SimpleHash::get set: @mutation (key, value) -> result = Batman.SimpleHash::set.call(@, key, value) @fire 'itemsWereAdded', key result unset: @mutation (key) -> result = Batman.SimpleHash::unset.call(@, key) @fire 'itemsWereRemoved', key if result? result cachable: false _preventMutationEvents: (block) -> @prevent 'change' @prevent 'itemsWereAdded' @prevent 'itemsWereRemoved' try block.call(this) finally @allow 'change' @allow 'itemsWereAdded' @allow 'itemsWereRemoved' clear: @mutation -> keys = @keys() @_preventMutationEvents -> @forEach (k) => @unset(k) result = Batman.SimpleHash::clear.call(@) @fire 'itemsWereRemoved', keys... result update: @mutation (object) -> addedKeys = [] @_preventMutationEvents -> Batman.forEach object, (k,v) => addedKeys.push(k) unless @hasKey(k) @set(k,v) @fire('itemsWereAdded', addedKeys...) if addedKeys.length > 0 replace: @mutation (object) -> addedKeys = [] removedKeys = [] @_preventMutationEvents -> @forEach (k, _) => unless Batman.objectHasKey(object, k) @unset(k) removedKeys.push(k) Batman.forEach object, (k,v) => addedKeys.push(k) unless @hasKey(k) @set(k,v) @fire('itemsWereAdded', addedKeys...) if addedKeys.length > 0 @fire('itemsWereRemoved', removedKeys...) if removedKeys.length > 0 equality: Batman.SimpleHash::equality hashKeyFor: Batman.SimpleHash::hashKeyFor for k in ['hasKey', 'forEach', 'isEmpty', 'keys', 'merge', 'toJSON', 'toObject'] proto = @prototype do (k) -> proto[k] = -> @registerAsMutableSource() Batman.SimpleHash::[k].apply(@, arguments) class Batman.SimpleSet constructor: -> @_storage = new Batman.SimpleHash @_indexes = new Batman.SimpleHash @_uniqueIndexes = new Batman.SimpleHash @_sorts = new Batman.SimpleHash @length = 0 @add.apply @, arguments if arguments.length > 0 $extendsEnumerable(@::) has: (item) -> @_storage.hasKey item add: (items...) -> addedItems = [] for item in items when !@_storage.hasKey(item) @_storage.set item, true addedItems.push item @length++ if @fire and addedItems.length isnt 0 @fire('change', this, this) @fire('itemsWereAdded', addedItems...) addedItems remove: (items...) -> removedItems = [] for item in items when @_storage.hasKey(item) @_storage.unset item removedItems.push item @length-- if @fire and removedItems.length isnt 0 @fire('change', this, this) @fire('itemsWereRemoved', removedItems...) removedItems find: (f) -> ret = undefined @forEach (item) -> if ret is undefined && f(item) is true ret = item ret forEach: (iterator, ctx) -> container = this @_storage.forEach (key) -> iterator.call(ctx, key, null, container) isEmpty: -> @length is 0 clear: -> items = @toArray() @_storage = new Batman.SimpleHash @length = 0 if @fire and items.length isnt 0 @fire('change', this, this) @fire('itemsWereRemoved', items...) items replace: (other) -> try @prevent?('change') @clear() @add(other.toArray()...) finally @allowAndFire?('change', this, this) toArray: -> @_storage.keys() merge: (others...) -> merged = new @constructor others.unshift(@) for set in others set.forEach (v) -> merged.add v merged indexedBy: (key) -> @_indexes.get(key) or @_indexes.set(key, new Batman.SetIndex(@, key)) indexedByUnique: (key) -> @_uniqueIndexes.get(key) or @_uniqueIndexes.set(key, new Batman.UniqueSetIndex(@, key)) sortedBy: (key, order="asc") -> order = if order.toLowerCase() is "desc" then "desc" else "asc" sortsForKey = @_sorts.get(key) or @_sorts.set(key, new Batman.Object) sortsForKey.get(order) or sortsForKey.set(order, new Batman.SetSort(@, key, order)) class Batman.Set extends Batman.Object constructor: -> Batman.SimpleSet.apply @, arguments $extendsEnumerable(@::) for k in ['add', 'remove', 'find', 'clear', 'replace', 'indexedBy', 'indexedByUnique', 'sortedBy'] @::[k] = Batman.SimpleSet::[k] for k in ['merge', 'forEach', 'toArray', 'isEmpty', 'has'] proto = @prototype do (k) -> proto[k] = -> @registerAsMutableSource() Batman.SimpleSet::[k].apply(@, arguments) toJSON: @::toArray applySetAccessors = (klass) -> klass.accessor 'first', -> @toArray()[0] klass.accessor 'last', -> @toArray()[@length - 1] klass.accessor 'indexedBy', -> new Batman.TerminalAccessible (key) => @indexedBy(key) klass.accessor 'indexedByUnique', -> new Batman.TerminalAccessible (key) => @indexedByUnique(key) klass.accessor 'sortedBy', -> new Batman.TerminalAccessible (key) => @sortedBy(key) klass.accessor 'sortedByDescending', -> new Batman.TerminalAccessible (key) => @sortedBy(key, 'desc') klass.accessor 'isEmpty', -> @isEmpty() klass.accessor 'toArray', -> @toArray() klass.accessor 'length', -> @registerAsMutableSource() @length applySetAccessors(Batman.Set) class Batman.SetObserver extends Batman.Object constructor: (@base) -> @_itemObservers = new Batman.SimpleHash @_setObservers = new Batman.SimpleHash @_setObservers.set "itemsWereAdded", => @fire('itemsWereAdded', arguments...) @_setObservers.set "itemsWereRemoved", => @fire('itemsWereRemoved', arguments...) @on 'itemsWereAdded', @startObservingItems.bind(@) @on 'itemsWereRemoved', @stopObservingItems.bind(@) observedItemKeys: [] observerForItemAndKey: (item, key) -> _getOrSetObserverForItemAndKey: (item, key) -> @_itemObservers.getOrSet item, => observersByKey = new Batman.SimpleHash observersByKey.getOrSet key, => @observerForItemAndKey(item, key) startObserving: -> @_manageItemObservers("observe") @_manageSetObservers("addHandler") stopObserving: -> @_manageItemObservers("forget") @_manageSetObservers("removeHandler") startObservingItems: (items...) -> @_manageObserversForItem(item, "observe") for item in items stopObservingItems: (items...) -> @_manageObserversForItem(item, "forget") for item in items _manageObserversForItem: (item, method) -> return unless item.isObservable for key in @observedItemKeys item[method] key, @_getOrSetObserverForItemAndKey(item, key) @_itemObservers.unset(item) if method is "forget" _manageItemObservers: (method) -> @base.forEach (item) => @_manageObserversForItem(item, method) _manageSetObservers: (method) -> return unless @base.isObservable @_setObservers.forEach (key, observer) => @base.event(key)[method](observer) class Batman.SetProxy extends Batman.Object constructor: () -> super() @length = 0 @base.on 'itemsWereAdded', (items...) => @fire('itemsWereAdded', items...) @base.on 'itemsWereRemoved', (items...) => @fire('itemsWereRemoved', items...) $extendsEnumerable(@::) filter: (f) -> r = new Batman.Set() @reduce(((r, e) -> r.add(e) if f(e); r), r) for k in ['add', 'remove', 'find', 'clear', 'replace'] do (k) => @::[k] = -> results = @base[k](arguments...) @length = @set('length', @base.get 'length') results for k in ['has', 'merge', 'toArray', 'isEmpty', 'indexedBy', 'indexedByUnique', 'sortedBy'] do (k) => @::[k] = -> @base[k](arguments...) applySetAccessors(@) @accessor 'length', get: -> @registerAsMutableSource() @length set: (_, v) -> @length = v class Batman.SetSort extends Batman.SetProxy constructor: (@base, @key, order="asc") -> super() @descending = order.toLowerCase() is "desc" if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] boundReIndex = @_reIndex.bind(@) @_setObserver.observerForItemAndKey = -> boundReIndex @_setObserver.on 'itemsWereAdded', boundReIndex @_setObserver.on 'itemsWereRemoved', boundReIndex @startObserving() @_reIndex() startObserving: -> @_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() toArray: -> @get('_storage') forEach: (iterator, ctx) -> iterator.call(ctx,e,i,this) for e,i in @get('_storage') compare: (a,b) -> return 0 if a is b return 1 if a is undefined return -1 if b is undefined return 1 if a is null return -1 if b is null return 1 if a is false return -1 if b is false return 1 if a is true return -1 if b is true if a isnt a if b isnt b return 0 # both are NaN else return 1 # a is NaN return -1 if b isnt b # b is NaN return 1 if a > b return -1 if a < b return 0 _reIndex: -> newOrder = @base.toArray().sort (a,b) => valueA = $get(a, @key) valueA = valueA.valueOf() if valueA? valueB = $get(b, @key) valueB = valueB.valueOf() if valueB? multiple = if @descending then -1 else 1 @compare.call(@, valueA, valueB) * multiple @_setObserver?.startObservingItems(newOrder...) @set('_storage', newOrder) class Batman.SetIndex extends Batman.Object propertyClass: Batman.Property constructor: (@base, @key) -> super() @_storage = new Batman.SimpleHash if @base.isEventEmitter @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] @_setObserver.observerForItemAndKey = @observerForItemAndKey.bind(@) @_setObserver.on 'itemsWereAdded', (items...) => @_addItem(item) for item in items @_setObserver.on 'itemsWereRemoved', (items...) => @_removeItem(item) for item in items @base.forEach @_addItem.bind(@) @startObserving() @accessor (key) -> @_resultSetForKey(key) startObserving: ->@_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() observerForItemAndKey: (item, key) -> (newValue, oldValue) => @_removeItemFromKey(item, oldValue) @_addItemToKey(item, newValue) _addItem: (item) -> @_addItemToKey(item, @_keyForItem(item)) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item _removeItem: (item) -> @_removeItemFromKey(item, @_keyForItem(item)) _removeItemFromKey: (item, key) -> @_resultSetForKey(key).remove(item) _resultSetForKey: (key) -> @_storage.getOrSet(key, -> new Batman.Set) _keyForItem: (item) -> Batman.Keypath.forBaseAndKey(item, @key).getValue() class Batman.UniqueSetIndex extends Batman.SetIndex constructor: -> @_uniqueIndex = new Batman.Hash super @accessor (key) -> @_uniqueIndex.get(key) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item unless @_uniqueIndex.hasKey(key) @_uniqueIndex.set(key, item) _removeItemFromKey: (item, key) -> resultSet = @_resultSetForKey(key) super if resultSet.isEmpty() @_uniqueIndex.unset(key) else @_uniqueIndex.set(key, resultSet.toArray()[0]) class Batman.BinarySetOperation extends Batman.Set constructor: (@left, @right) -> super() @_setup @left, @right @_setup @right, @left _setup: (set, opposite) => set.on 'itemsWereAdded', (items...) => @_itemsWereAddedToSource(set, opposite, items...) set.on 'itemsWereRemoved', (items...) => @_itemsWereRemovedFromSource(set, opposite, items...) @_itemsWereAddedToSource set, opposite, set.toArray()... merge: (others...) -> merged = new Batman.Set others.unshift(@) for set in others set.forEach (v) -> merged.add v merged filter: Batman.SetProxy::filter class Batman.SetUnion extends Batman.BinarySetOperation _itemsWereAddedToSource: (source, opposite, items...) -> @add items... _itemsWereRemovedFromSource: (source, opposite, items...) -> itemsToRemove = (item for item in items when !opposite.has(item)) @remove itemsToRemove... class Batman.SetIntersection extends Batman.BinarySetOperation _itemsWereAddedToSource: (source, opposite, items...) -> itemsToAdd = (item for item in items when opposite.has(item)) @add itemsToAdd... _itemsWereRemovedFromSource: (source, opposite, items...) -> @remove items... # State Machines # -------------- Batman.StateMachine = { initialize: -> Batman.initializeObject @ if not @_batman.states @_batman.states = new Batman.SimpleHash state: (name, callback) -> Batman.StateMachine.initialize.call @ return @_batman.getFirst 'state' unless name developer.assert @isEventEmitter, "StateMachine requires EventEmitter" @[name] ||= (callback) -> _stateMachine_setState.call(@, name) @on(name, callback) if typeof callback is 'function' transition: (from, to, callback) -> Batman.StateMachine.initialize.call @ @state from @state to @on("#{from}->#{to}", callback) if callback } # A special method to alias state machine methods to class methods Batman.Object.actsAsStateMachine = (includeInstanceMethods=true) -> Batman.StateMachine.initialize.call @ Batman.StateMachine.initialize.call @prototype @classState = -> Batman.StateMachine.state.apply @, arguments @state = -> @classState.apply @prototype, arguments @::state = @classState if includeInstanceMethods @classTransition = -> Batman.StateMachine.transition.apply @, arguments @transition = -> @classTransition.apply @prototype, arguments @::transition = @classTransition if includeInstanceMethods # This is cached here so it doesn't need to be recompiled for every setter _stateMachine_setState = (newState) -> Batman.StateMachine.initialize.call @ if @_batman.isTransitioning (@_batman.nextState ||= []).push(newState) return false @_batman.isTransitioning = yes oldState = @state() @_batman.state = newState if newState and oldState @fire("#{oldState}->#{newState}", newState, oldState) if newState @fire(newState, newState, oldState) @_batman.isTransitioning = no @[@_batman.nextState.shift()]() if @_batman.nextState?.length newState # App, Requests, and Routing # -------------------------- # `Batman.Request` is a normalizer for XHR requests in the Batman world. class Batman.Request extends Batman.Object @objectToFormData: (data) -> pairForList = (key, object, first = false) -> list = switch Batman.typeOf(object) when 'Object' list = for k, v of object pairForList((if first then k else "#{key}[#{k}]"), v) list.reduce((acc, list) -> acc.concat list , []) when 'Array' object.reduce((acc, element) -> acc.concat pairForList("#{key}[]", element) , []) else [[key, object]] formData = new Batman.container.FormData() for [key, val] in pairForList("", data, true) formData.append(key, val) formData url: '' data: '' method: 'GET' formData: false response: null status: null headers: {} @accessor 'method', $mixin {}, Batman.Property.defaultAccessor, set: (k,val) -> @[k] = val?.toUpperCase?() # Set the content type explicitly for PUT and POST requests. contentType: 'application/x-www-form-urlencoded' constructor: (options) -> handlers = {} for k, handler of options when k in ['success', 'error', 'loading', 'loaded'] handlers[k] = handler delete options[k] super(options) @on k, handler for k, handler of handlers # After the URL gets set, we'll try to automatically send # your request after a short period. If this behavior is # not desired, use @cancel() after setting the URL. @observeAll 'url', (url) -> @_autosendTimeout = $setImmediate => @send() # `send` is implmented in the platform layer files. One of those must be required for # `Batman.Request` to be useful. send: -> developer.error "Please source a dependency file for a request implementation" cancel: -> $clearImmediate(@_autosendTimeout) if @_autosendTimeout ## Routes class Batman.Route extends Batman.Object # Route regexes courtesy of Backbone @regexps = namedParam: /:([\w\d]+)/g splatParam: /\*([\w\d]+)/g queryParam: '(?:\\?.+)?' namedOrSplat: /[:|\*]([\w\d]+)/g namePrefix: '[:|\*]' escapeRegExp: /[-[\]{}()+?.,\\^$|#\s]/g optionKeys: ['member', 'collection'] testKeys: ['controller', 'action'] isRoute: true constructor: (templatePath, baseParams) -> regexps = @constructor.regexps templatePath = "/#{templatePath}" if templatePath.indexOf('/') isnt 0 pattern = templatePath.replace(regexps.escapeRegExp, '\\$&') regexp = /// ^ #{pattern .replace(regexps.namedParam, '([^\/]+)') .replace(regexps.splatParam, '(.*?)') } #{regexps.queryParam} $ /// namedArguments = (matches[1] while matches = regexps.namedOrSplat.exec(pattern)) properties = {templatePath, pattern, regexp, namedArguments, baseParams} for k in @optionKeys properties[k] = baseParams[k] delete baseParams[k] super(properties) paramsFromPath: (path) -> [path, query] = path.split '?' namedArguments = @get('namedArguments') params = $mixin {path}, @get('baseParams') matches = @get('regexp').exec(path).slice(1) for match, index in matches name = namedArguments[index] params[name] = match if query for pair in query.split('&') [key, value] = pair.split '=' params[key] = value params pathFromParams: (argumentParams) -> params = $mixin {}, argumentParams path = @get('templatePath') # Replace the names in the template with their values from params for name in @get('namedArguments') regexp = ///#{@constructor.regexps.namePrefix}#{name}/// newPath = path.replace regexp, (if params[name]? then params[name] else '') if newPath != path delete params[name] path = newPath for key in @testKeys delete params[key] # Append the rest of the params as a query string queryParams = ("#{key}=#{value}" for key, value of params) if queryParams.length > 0 path += "?" + queryParams.join("&") path test: (pathOrParams) -> if typeof pathOrParams is 'string' path = pathOrParams else if pathOrParams.path? path = pathOrParams.path else path = @pathFromParams(pathOrParams) for key in @testKeys if (value = @get(key))? return false unless pathOrParams[key] == value @get('regexp').test(path) dispatch: (pathOrParams) -> return false unless @test(pathOrParams) if typeof pathOrParams is 'string' params = @paramsFromPath(pathOrParams) path = pathOrParams else params = pathOrParams path = @pathFromParams(pathOrParams) @get('callback')(params) return path callback: -> throw new Batman.DevelopmentError "Override callback in a Route subclass" class Batman.CallbackActionRoute extends Batman.Route optionKeys: ['member', 'collection', 'callback', 'app'] controller: false action: false class Batman.ControllerActionRoute extends Batman.Route optionKeys: ['member', 'collection', 'app', 'controller', 'action'] constructor: (templatePath, options) -> if options.signature [controller, action] = options.signature.split('#') action ||= 'index' options.controller = controller options.action = action delete options.signature super(templatePath, options) callback: (params) => controller = @get("app.dispatcher.controllers.#{@get('controller')}") controller.dispatch(@get('action'), params) class Batman.Dispatcher extends Batman.Object @canInferRoute: (argument) -> argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy || argument.prototype instanceof Batman.Model @paramsFromArgument: (argument) -> resourceNameFromModel = (model) -> helpers.underscore(helpers.pluralize($functionName(model))) return argument unless @canInferRoute(argument) if argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy argument = argument.get('target') if argument.isProxy if argument? { controller: resourceNameFromModel(argument.constructor) action: 'show' id: argument.get('id') } else {} else if argument.prototype instanceof Batman.Model { controller: resourceNameFromModel(argument) action: 'index' } else argument class ControllerDirectory extends Batman.Object @accessor '__app', Batman.Property.defaultAccessor @accessor (key) -> @get("__app.#{helpers.capitalize(key)}Controller.sharedController") @accessor 'controllers', -> new ControllerDirectory(__app: @get('app')) constructor: (app, routeMap) -> super({app, routeMap}) routeForParams: (params) -> params = @constructor.paramsFromArgument(params) @get('routeMap').routeForParams(params) pathFromParams: (params) -> return params if typeof params is 'string' params = @constructor.paramsFromArgument(params) @routeForParams(params)?.pathFromParams(params) dispatch: (params) -> inferredParams = @constructor.paramsFromArgument(params) route = @routeForParams(inferredParams) if route path = route.dispatch(inferredParams) else # No route matching the parameters was found, but an object which might be for # use with the params replacer has been passed. If its an object like a model # or a record we could have inferred a route for it (but didn't), so we make # sure that it isn't by running it through canInferRoute. if $typeOf(params) is 'Object' && !@constructor.canInferRoute(params) return @get('app.currentParams').replace(params) else @get('app.currentParams').clear() return Batman.redirect('/404') unless path is '/404' or params is '/404' @set 'app.currentURL', path @set 'app.currentRoute', route path class Batman.RouteMap memberRoute: null collectionRoute: null constructor: -> @childrenByOrder = [] @childrenByName = {} routeForParams: (params) -> for route in @childrenByOrder return route if route.test(params) return undefined addRoute: (name, route) -> @childrenByOrder.push(route) if name.length > 0 && (names = name.split('.')).length > 0 base = names.shift() unless @childrenByName[base] @childrenByName[base] = new Batman.RouteMap @childrenByName[base].addRoute(names.join('.'), route) else if route.get('member') developer.do => Batman.developer.error("Member route with name #{name} already exists!") if @memberRoute @memberRoute = route else developer.do => Batman.developer.error("Collection route with name #{name} already exists!") if @collectionRoute @collectionRoute = route true class Batman.NamedRouteQuery extends Batman.Object isNamedRouteQuery: true developer.do => class NonWarningProperty extends Batman.Keypath constructor: -> developer.suppress() super developer.unsuppress() @::propertyClass = NonWarningProperty constructor: (routeMap, args = []) -> super({routeMap, args}) @accessor 'route', -> {memberRoute, collectionRoute} = @get('routeMap') for route in [memberRoute, collectionRoute] when route? return route if route.namedArguments.length == @get('args').length return collectionRoute || memberRoute @accessor 'path', -> params = {} namedArguments = @get('route.namedArguments') for argumentName, index in namedArguments if (argumentValue = @get('args')[index])? params[argumentName] = @_toParam(argumentValue) @get('route').pathFromParams(params) @accessor 'routeMap', 'args', 'cardinality', Batman.Property.defaultAccessor @accessor get: (key) -> return if !key? if typeof key is 'string' @nextQueryForName(key) else @nextQueryWithArgument(key) set: -> cacheable: false nextQueryForName: (key) -> if map = @get('routeMap').childrenByName[key] return new Batman.NamedRouteQuery(map, @args) else Batman.developer.error "Couldn't find a route for the name #{key}!" nextQueryWithArgument: (arg) -> args = @args.slice(0) args.push arg @clone(args) _toParam: (arg) -> if arg instanceof Batman.AssociationProxy arg = arg.get('target') if arg.toParam isnt 'undefined' then arg.toParam() else arg _paramName: (arg) -> string = helpers.singularize($functionName(arg)) + "Id" string.charAt(0).toLowerCase() + string.slice(1) clone: (args = @args) -> new Batman.NamedRouteQuery(@routeMap, args) class Batman.RouteMapBuilder @BUILDER_FUNCTIONS = ['resources', 'member', 'collection', 'route', 'root'] @ROUTES = index: cardinality: 'collection' path: (resource) -> resource name: (resource) -> resource new: cardinality: 'collection' path: (resource) -> "#{resource}/new" name: (resource) -> "#{resource}.new" show: cardinality: 'member' path: (resource) -> "#{resource}/:id" name: (resource) -> resource edit: cardinality: 'member' path: (resource) -> "#{resource}/:id/edit" name: (resource) -> "#{resource}.edit" collection: cardinality: 'collection' path: (resource, name) -> "#{resource}/#{name}" name: (resource, name) -> "#{resource}.#{name}" member: cardinality: 'member' path: (resource, name) -> "#{resource}/:id/#{name}" name: (resource, name) -> "#{resource}.#{name}" constructor: (@app, @routeMap, @parent, @baseOptions = {}) -> if @parent @rootPath = @parent._nestingPath() @rootName = @parent._nestingName() else @rootPath = '' @rootName = '' resources: (args...) -> resourceNames = (arg for arg in args when typeof arg is 'string') callback = args.pop() if typeof args[args.length - 1] is 'function' if typeof args[args.length - 1] is 'object' options = args.pop() else options = {} actions = {index: true, new: true, show: true, edit: true} if options.except actions[k] = false for k in options.except delete options.except else if options.only actions[k] = false for k, v of actions actions[k] = true for k in options.only delete options.only for resourceName in resourceNames controller = resourceRoot = helpers.pluralize(resourceName) childBuilder = @_childBuilder({controller}) # Call the callback so that routes defined within it are matched # before the standard routes defined by `resources`. callback?.call(childBuilder) for action, included of actions when included route = @constructor.ROUTES[action] as = route.name(resourceRoot) path = route.path(resourceRoot) routeOptions = $mixin {controller, action, path, as}, options childBuilder[route.cardinality](action, routeOptions) true member: -> @_addRoutesWithCardinality('member', arguments...) collection: -> @_addRoutesWithCardinality('collection', arguments...) root: (signature, options) -> @route '/', signature, options route: (path, signature, options, callback) -> if !callback if typeof options is 'function' callback = options options = undefined else if typeof signature is 'function' callback = signature signature = undefined if !options if typeof signature is 'string' options = {signature} else options = signature options ||= {} else options.signature = signature if signature options.callback = callback if callback options.as ||= @_nameFromPath(path) options.path = path @_addRoute(options) _addRoutesWithCardinality: (cardinality, names..., options) -> if typeof options is 'string' names.push options options = {} options = $mixin {}, @baseOptions, options options[cardinality] = true route = @constructor.ROUTES[cardinality] resourceRoot = options.controller for name in names routeOptions = $mixin {action: name}, options unless routeOptions.path? routeOptions.path = route.path(resourceRoot, name) unless routeOptions.as? routeOptions.as = route.name(resourceRoot, name) @_addRoute(routeOptions) true _addRoute: (options = {}) -> path = @rootPath + options.path name = @rootName + options.as delete options.as delete options.path klass = if options.callback then Batman.CallbackActionRoute else Batman.ControllerActionRoute options.app = @app route = new klass(path, options) @routeMap.addRoute(name, route) _nameFromPath: (path) -> underscored = path .replace(Batman.Route.regexps.namedOrSplat, '') .replace(/\/+/g, '_') .replace(/(^_)|(_$)/g, '') name = helpers.camelize(underscored) name.charAt(0).toLowerCase() + name.slice(1) _nestingPath: -> unless @parent "" else nestingParam = ":" + helpers.singularize(@baseOptions.controller) + "Id" "#{@parent._nestingPath()}/#{@baseOptions.controller}/#{nestingParam}/" _nestingName: -> unless @parent "" else @baseOptions.controller + "." _childBuilder: (baseOptions = {}) -> new Batman.RouteMapBuilder(@app, @routeMap, @, baseOptions) class Batman.Navigator @defaultClass: -> if Batman.config.usePushState and Batman.PushStateNavigator.isSupported() Batman.PushStateNavigator else Batman.HashbangNavigator @forApp: (app) -> new (@defaultClass())(app) constructor: (@app) -> start: -> return if typeof window is 'undefined' return if @started @started = yes @startWatching() Batman.currentApp.prevent 'ready' $setImmediate => if @started && Batman.currentApp @handleCurrentLocation() Batman.currentApp.allowAndFire 'ready' stop: -> @stopWatching() @started = no handleLocation: (location) -> path = @pathFromLocation(location) return if path is @cachedPath @dispatch(path) handleCurrentLocation: => @handleLocation(window.location) dispatch: (params) -> @cachedPath = @app.get('dispatcher').dispatch(params) push: (params) -> path = @dispatch(params) @pushState(null, '', path) path replace: (params) -> path = @dispatch(params) @replaceState(null, '', path) path redirect: @::push normalizePath: (segments...) -> segments = for seg, i in segments "#{seg}".replace(/^(?!\/)/, '/').replace(/\/+$/,'') segments.join('') or '/' @normalizePath: @::normalizePath class Batman.PushStateNavigator extends Batman.Navigator @isSupported: -> window?.history?.pushState? startWatching: -> $addEventListener window, 'popstate', @handleCurrentLocation stopWatching: -> $removeEventListener window, 'popstate', @handleCurrentLocation pushState: (stateObject, title, path) -> window.history.pushState(stateObject, title, @linkTo(path)) replaceState: (stateObject, title, path) -> window.history.replaceState(stateObject, title, @linkTo(path)) linkTo: (url) -> @normalizePath(Batman.config.pathPrefix, url) pathFromLocation: (location) -> fullPath = "#{location.pathname or ''}#{location.search or ''}" prefixPattern = new RegExp("^#{@normalizePath(Batman.config.pathPrefix)}") @normalizePath(fullPath.replace(prefixPattern, '')) handleLocation: (location) -> path = @pathFromLocation(location) if path is '/' and (hashbangPath = Batman.HashbangNavigator::pathFromLocation(location)) isnt '/' @replace(hashbangPath) else super class Batman.HashbangNavigator extends Batman.Navigator HASH_PREFIX: '#!' if window? and 'onhashchange' of window @::startWatching = -> $addEventListener window, 'hashchange', @handleCurrentLocation @::stopWatching = -> $removeEventListener window, 'hashchange', @handleCurrentLocation else @::startWatching = -> @interval = setInterval @handleCurrentLocation, 100 @::stopWatching = -> @interval = clearInterval @interval pushState: (stateObject, title, path) -> window.location.hash = @linkTo(path) replaceState: (stateObject, title, path) -> loc = window.location loc.replace("#{loc.pathname}#{loc.search}#{@linkTo(path)}") linkTo: (url) -> @HASH_PREFIX + url pathFromLocation: (location) -> hash = location.hash if hash?.substr(0,2) is @HASH_PREFIX @normalizePath(hash.substr(2)) else '/' handleLocation: (location) -> return super unless Batman.config.usePushState realPath = Batman.PushStateNavigator::pathFromLocation(location) if realPath is '/' super else location.replace(@normalizePath("#{Batman.config.pathPrefix}#{@linkTo(realPath)}")) Batman.redirect = $redirect = (url) -> Batman.navigator?.redirect url class Batman.ParamsReplacer extends Batman.Object constructor: (@navigator, @params) -> redirect: -> @navigator.replace(@toObject()) replace: (params) -> @params.replace(params) @redirect() update: (params) -> @params.update(params) @redirect() clear: () -> @params.clear() @redirect() toObject: -> @params.toObject() @accessor get: (k) -> @params.get(k) set: (k,v) -> oldValue = @params.get(k) result = @params.set(k,v) @redirect() if oldValue isnt v result unset: (k) -> hadKey = @params.hasKey(k) result = @params.unset(k) @redirect() if hadKey result class Batman.ParamsPusher extends Batman.ParamsReplacer redirect: -> @navigator.push(@toObject()) # `Batman.App` manages requiring files and acts as a namespace for all code subclassing # Batman objects. class Batman.App extends Batman.Object @classAccessor 'currentParams', get: -> new Batman.Hash 'final': true @classAccessor 'paramsManager', get: -> return unless nav = @get('navigator') params = @get('currentParams') params.replacer = new Batman.ParamsReplacer(nav, params) 'final': true @classAccessor 'paramsPusher', get: -> return unless nav = @get('navigator') params = @get('currentParams') params.pusher = new Batman.ParamsPusher(nav, params) 'final': true @classAccessor 'routes', -> new Batman.NamedRouteQuery(@get('routeMap')) @classAccessor 'routeMap', -> new Batman.RouteMap @classAccessor 'routeMapBuilder', -> new Batman.RouteMapBuilder(@, @get('routeMap')) @classAccessor 'dispatcher', -> new Batman.Dispatcher(@, @get('routeMap')) @classAccessor 'controllers', -> @get('dispatcher.controllers') @classAccessor '_renderContext', -> Batman.RenderContext.base.descend(@) # Require path tells the require methods which base directory to look in. @requirePath: '' # The require class methods (`controller`, `model`, `view`) simply tells # your app where to look for coffeescript source files. This # implementation may change in the future. developer.do => App.require = (path, names...) -> base = @requirePath + path for name in names @prevent 'run' path = base + '/' + name + '.coffee' new Batman.Request url: path type: 'html' success: (response) => CoffeeScript.eval response @allow 'run' if not @isPrevented 'run' @fire 'loaded' @run() if @wantsToRun @ @controller = (names...) -> names = names.map (n) -> n + '_controller' @require 'controllers', names... @model = -> @require 'models', arguments... @view = -> @require 'views', arguments... # Layout is the base view that other views can be yielded into. The # default behavior is that when `app.run()` is called, a new view will # be created for the layout using the `document` node as its content. # Use `MyApp.layout = null` to turn off the default behavior. @layout: undefined # Routes for the app are built using a RouteMapBuilder, so delegate the # functions used to build routes to it. for name in Batman.RouteMapBuilder.BUILDER_FUNCTIONS do (name) => @[name] = -> @get('routeMapBuilder')[name](arguments...) # Call `MyApp.run()` to start up an app. Batman level initializers will # be run to bootstrap the application. @event('ready').oneShot = true @event('run').oneShot = true @run: -> if Batman.currentApp return if Batman.currentApp is @ Batman.currentApp.stop() return false if @hasRun if @isPrevented 'run' @wantsToRun = true return false else delete @wantsToRun Batman.currentApp = @ Batman.App.set('current', @) unless @get('dispatcher')? @set 'dispatcher', new Batman.Dispatcher(@, @get('routeMap')) @set 'controllers', @get('dispatcher.controllers') unless @get('navigator')? @set('navigator', Batman.Navigator.forApp(@)) @on 'run', => Batman.navigator = @get('navigator') Batman.navigator.start() if Object.keys(@get('dispatcher').routeMap).length > 0 @observe 'layout', (layout) => layout?.on 'ready', => @fire 'ready' if typeof @layout is 'undefined' @set 'layout', new Batman.View context: @ node: document else if typeof @layout is 'string' @set 'layout', new @[helpers.camelize(@layout) + 'View'] @hasRun = yes @fire('run') @ @event('ready').oneShot = true @event('stop').oneShot = true @stop: -> @navigator?.stop() Batman.navigator = null @hasRun = no @fire('stop') @ # Controllers # ----------- class Batman.Controller extends Batman.Object @singleton 'sharedController' @accessor 'controllerName', -> @_controllerName ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) @accessor '_renderContext', -> Batman.RenderContext.root().descend(@) @beforeFilter: (options, nameOrFunction) -> if not nameOrFunction nameOrFunction = options options = {} else options.only = [options.only] if options.only and $typeOf(options.only) isnt 'Array' options.except = [options.except] if options.except and $typeOf(options.except) isnt 'Array' Batman.initializeObject @ options.block = nameOrFunction filters = @_batman.beforeFilters ||= new Batman.Hash filters.set(nameOrFunction, options) @afterFilter: (options, nameOrFunction) -> if not nameOrFunction nameOrFunction = options options = {} else options.only = [options.only] if options.only and $typeOf(options.only) isnt 'Array' options.except = [options.except] if options.except and $typeOf(options.except) isnt 'Array' Batman.initializeObject @ options.block = nameOrFunction filters = @_batman.afterFilters ||= new Batman.Hash filters.set(nameOrFunction, options) runFilters: (params, filters) -> action = params.action if filters = @constructor._batman?.get(filters) filters.forEach (_, options) => return if options.only and action not in options.only return if options.except and action in options.except block = options.block if typeof block is 'function' then block.call(@, params) else @[block]?(params) # You shouldn't call this method directly. It will be called by the dispatcher when a route is called. # If you need to call a route manually, use `$redirect()`. dispatch: (action, params = {}) -> params.controller ||= @get 'controllerName' params.action ||= action params.target ||= @ oldRedirect = Batman.navigator?.redirect Batman.navigator?.redirect = @redirect @_inAction = yes @_actedDuringAction = no @set 'action', action @set 'params', params @runFilters params, 'beforeFilters' developer.assert @[action], "Error! Controller action #{@get 'controllerName'}.#{action} couldn't be found!" @[action](params) if not @_actedDuringAction @render() @runFilters params, 'afterFilters' delete @_actedDuringAction delete @_inAction Batman.navigator?.redirect = oldRedirect redirectTo = @_afterFilterRedirect delete @_afterFilterRedirect $redirect(redirectTo) if redirectTo redirect: (url) => if @_actedDuringAction && @_inAction developer.warn "Warning! Trying to redirect but an action has already be taken during #{@get('controllerName')}.#{@get('action')}}" if @_inAction @_actedDuringAction = yes @_afterFilterRedirect = url else if $typeOf(url) is 'Object' url.controller = @ if not url.controller $redirect url render: (options = {}) -> if @_actedDuringAction && @_inAction developer.warn "Warning! Trying to render but an action has already be taken during #{@get('controllerName')}.#{@get('action')}" @_actedDuringAction = yes return if options is false if not options.view options.context ||= @get('_renderContext') options.source ||= helpers.underscore(@get('controllerName') + '/' + @get('action')) options.view = new (Batman.currentApp?[helpers.camelize("#{@get('controllerName')}_#{@get('action')}_view")] || Batman.View)(options) if view = options.view Batman.currentApp?.prevent 'ready' view.on 'ready', => Batman.DOM.replace options.into || 'main', view.get('node'), view.hasContainer Batman.currentApp?.allowAndFire 'ready' view.ready?(@params) view # Models # ------ class Batman.Model extends Batman.Object # ## Model API # Override this property if your model is indexed by a key other than `id` @primaryKey: 'id' # Override this property to define the key which storage adapters will use to store instances of this model under. # - For RestStorage, this ends up being part of the url built to store this model # - For LocalStorage, this ends up being the namespace in localStorage in which JSON is stored @storageKey: null # Pick one or many mechanisms with which this model should be persisted. The mechanisms # can be already instantiated or just the class defining them. @persist: (mechanisms...) -> Batman.initializeObject @prototype storage = @::_batman.storage ||= [] results = for mechanism in mechanisms mechanism = if mechanism.isStorageAdapter then mechanism else new mechanism(@) storage.push mechanism mechanism if results.length > 1 results else results[0] # Encoders are the tiny bits of logic which manage marshalling Batman models to and from their # storage representations. Encoders do things like stringifying dates and parsing them back out again, # pulling out nested model collections and instantiating them (and JSON.stringifying them back again), # and marshalling otherwise un-storable object. @encode: (keys..., encoderOrLastKey) -> Batman.initializeObject @prototype @::_batman.encoders ||= new Batman.SimpleHash @::_batman.decoders ||= new Batman.SimpleHash encoder = {} switch $typeOf(encoderOrLastKey) when 'String' keys.push encoderOrLastKey when 'Function' encoder.encode = encoderOrLastKey else encoder.encode = encoderOrLastKey.encode encoder.decode = encoderOrLastKey.decode encoder = $mixin {}, @defaultEncoder, encoder for operation in ['encode', 'decode'] for key in keys hash = @::_batman["#{operation}rs"] if encoder[operation] hash.set(key, encoder[operation]) else hash.unset(key) #true # Set up the unit functions as the default for both @defaultEncoder: encode: (x) -> x decode: (x) -> x # Attach encoders and decoders for the primary key, and update them if the primary key changes. @observeAndFire 'primaryKey', (newPrimaryKey) -> @encode newPrimaryKey, {encode: false, decode: @defaultEncoder.decode} # Validations allow a model to be marked as 'valid' or 'invalid' based on a set of programmatic rules. # By validating our data before it gets to the server we can provide immediate feedback to the user about # what they have entered and forgo waiting on a round trip to the server. # `validate` allows the attachment of validations to the model on particular keys, where the validation is # either a built in one (by use of options to pass to them) or a custom one (by use of a custom function as # the second argument). Custom validators should have the signature `(errors, record, key, callback)`. They # should add strings to the `errors` set based on the record (maybe depending on the `key` they were attached # to) and then always call the callback. Again: the callback must always be called. @validate: (keys..., optionsOrFunction) -> Batman.initializeObject @prototype validators = @::_batman.validators ||= [] if typeof optionsOrFunction is 'function' # Given a function, use that as the actual validator, expecting it to conform to the API # the built in validators do. validators.push keys: keys callback: optionsOrFunction else # Given options, find the validations which match the given options, and add them to the validators # array. options = optionsOrFunction for validator in Validators if (matches = validator.matches(options)) delete options[match] for match in matches validators.push keys: keys validator: new validator(matches) @urlNestsUnder: (key) -> parent = Batman.helpers.pluralize(key) children = Batman.helpers.pluralize(Batman._functionName(@).toLowerCase()) @url = (options) -> parentID = options.data[key + '_id'] delete options.data[key + '_id'] "#{parent}/#{parentID}/#{children}" @::url = -> url = "#{parent}/#{@get(key + '_id')}/#{children}" if id = @get('id') url += '/' + id url # ### Query methods @classAccessor 'all', get: -> @load() if @::hasStorage() and @classState() not in ['loaded', 'loading'] @get('loaded') set: (k, v) -> @set('loaded', v) @classAccessor 'loaded', get: -> @_loaded ||= new Batman.Set set: (k, v) -> @_loaded = v @classAccessor 'first', -> @get('all').toArray()[0] @classAccessor 'last', -> x = @get('all').toArray(); x[x.length - 1] @clear: -> Batman.initializeObject(@) result = @get('loaded').clear() @_batman.get('associations')?.reset() result @find: (id, callback) -> developer.assert callback, "Must call find with a callback!" record = new @() record.set 'id', id newRecord = @_mapIdentity(record) newRecord.load callback return newRecord # `load` fetches records from all sources possible @load: (options, callback) -> if typeof options in ['function', 'undefined'] callback = options options = {} developer.assert @::_batman.getAll('storage').length, "Can't load model #{$functionName(@)} without any storage adapters!" @loading() @::_doStorageOperation 'readAll', options, (err, records) => if err? callback?(err, []) else mappedRecords = (@_mapIdentity(record) for record in records) @loaded() callback?(err, mappedRecords) # `create` takes an attributes hash, creates a record from it, and saves it given the callback. @create: (attrs, callback) -> if !callback [attrs, callback] = [{}, attrs] obj = new this(attrs) obj.save(callback) obj # `findOrCreate` takes an attributes hash, optionally containing a primary key, and returns to you a saved record # representing those attributes, either from the server or from the identity map. @findOrCreate: (attrs, callback) -> record = new this(attrs) if record.isNew() record.save(callback) else foundRecord = @_mapIdentity(record) foundRecord.updateAttributes(attrs) callback(undefined, foundRecord) @_mapIdentity: (record) -> if typeof (id = record.get('id')) == 'undefined' || id == '' return record else existing = @get("loaded.indexedBy.id").get(id)?.toArray()[0] if existing existing.updateAttributes(record._batman.attributes || {}) return existing else @get('loaded').add(record) return record associationProxy: (association) -> Batman.initializeObject(@) proxies = @_batman.associationProxies ||= new Batman.SimpleHash proxies.get(association.label) or proxies.set(association.label, new association.proxyClass(association, @)) # ### Record API # Add a universally accessible accessor for retrieving the primrary key, regardless of which key its stored under. @accessor 'id', get: -> pk = @constructor.primaryKey if pk == 'id' @id else @get(pk) set: (k, v) -> # naively coerce string ids into integers if typeof v is "string" and v.match(/[^0-9]/) is null v = parseInt(v, 10) pk = @constructor.primaryKey if pk == 'id' @id = v else @set(pk, v) # Add normal accessors for the dirty keys and errors attributes of a record, so these accesses don't fall to the # default accessor. @accessor 'dirtyKeys', 'errors', Batman.Property.defaultAccessor # Add an accessor for the internal batman state under `batmanState`, so that the `state` key can be a valid # attribute. @accessor 'batmanState' get: -> @state() set: (k, v) -> @state(v) # Add a default accessor to make models store their attributes under a namespace by default. @accessor Model.defaultAccessor = get: (k) -> attribute = (@_batman.attributes ||= {})[k] if typeof attribute isnt 'undefined' attribute else @[k] set: (k, v) -> (@_batman.attributes ||= {})[k] = v unset: (k) -> x = (@_batman.attributes ||={})[k] delete @_batman.attributes[k] x # New records can be constructed by passing either an ID or a hash of attributes (potentially # containing an ID) to the Model constructor. By not passing an ID, the model is marked as new. constructor: (idOrAttributes = {}) -> developer.assert @ instanceof Batman.Object, "constructors must be called with new" # We have to do this ahead of super, because mixins will call set which calls things on dirtyKeys. @dirtyKeys = new Batman.Hash @errors = new Batman.ErrorsSet # Find the ID from either the first argument or the attributes. if $typeOf(idOrAttributes) is 'Object' super(idOrAttributes) else super() @set('id', idOrAttributes) @empty() if not @state() # Override the `Batman.Observable` implementation of `set` to implement dirty tracking. set: (key, value) -> # Optimize setting where the value is the same as what's already been set. oldValue = @get(key) return if oldValue is value # Actually set the value and note what the old value was in the tracking array. result = super @dirtyKeys.set(key, oldValue) # Mark the model as dirty if isn't already. @dirty() unless @state() in ['dirty', 'loading', 'creating'] result updateAttributes: (attrs) -> @mixin(attrs) @ toString: -> "#{$functionName(@constructor)}: #{@get('id')}" # `toJSON` uses the various encoders for each key to grab a storable representation of the record. toJSON: -> obj = {} # Encode each key into a new object encoders = @_batman.get('encoders') unless !encoders or encoders.isEmpty() encoders.forEach (key, encoder) => val = @get key if typeof val isnt 'undefined' encodedVal = encoder(val, key, obj, @) if typeof encodedVal isnt 'undefined' obj[key] = encodedVal if @constructor.primaryKey isnt 'id' obj[@constructor.primaryKey] = @get('id') delete obj.id obj # `fromJSON` uses the various decoders for each key to generate a record instance from the JSON # stored in whichever storage mechanism. fromJSON: (data) -> obj = {} decoders = @_batman.get('decoders') # If no decoders were specified, do the best we can to interpret the given JSON by camelizing # each key and just setting the values. if !decoders or decoders.isEmpty() for key, value of data obj[key] = value else # If we do have decoders, use them to get the data. decoders.forEach (key, decoder) => obj[key] = decoder(data[key], key, data, obj, @) unless typeof data[key] is 'undefined' if @constructor.primaryKey isnt 'id' obj.id = data[@constructor.primaryKey] developer.do => if (!decoders) || decoders.length <= 1 developer.warn "Warning: Model #{$functionName(@constructor)} has suspiciously few decoders!" # Mixin the buffer object to use optimized and event-preventing sets used by `mixin`. @mixin obj toParam: -> @get('id') # Each model instance (each record) can be in one of many states throughout its lifetime. Since various # operations on the model are asynchronous, these states are used to indicate exactly what point the # record is at in it's lifetime, which can often be during a save or load operation. @actsAsStateMachine yes # Add the various states to the model. for k in ['empty', 'dirty', 'loading', 'loaded', 'saving', 'saved', 'creating', 'created', 'validating', 'validated', 'destroying', 'destroyed'] @state k for k in ['loading', 'loaded'] @classState k _doStorageOperation: (operation, options, callback) -> developer.assert @hasStorage(), "Can't #{operation} model #{$functionName(@constructor)} without any storage adapters!" adapters = @_batman.get('storage') for adapter in adapters adapter.perform operation, @, {data: options}, callback true hasStorage: -> (@_batman.get('storage') || []).length > 0 # `load` fetches the record from all sources possible load: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't load a destroyed record!")) return @loading() @_doStorageOperation 'read', {}, (err, record) => unless err @loaded() record = @constructor._mapIdentity(record) callback?(err, record) # `save` persists a record to all the storage mechanisms added using `@persist`. `save` will only save # a model if it is valid. save: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't save a destroyed record!")) return @validate (isValid, errors) => if !isValid callback?(errors) return creating = @isNew() do @saving do @creating if creating associations = @constructor._batman.get('associations') # Save belongsTo models immediately since we don't need this model's id associations?.getByType('belongsTo')?.forEach (association, label) => association.apply(@) @_doStorageOperation (if creating then 'create' else 'update'), {}, (err, record) => unless err if creating do @created do @saved @dirtyKeys.clear() associations?.getByType('hasOne')?.forEach (association) -> association.apply(err, record) associations?.getByType('hasMany')?.forEach (association) -> association.apply(err, record) record = @constructor._mapIdentity(record) callback?(err, record) # `destroy` destroys a record in all the stores. destroy: (callback) => do @destroying @_doStorageOperation 'destroy', {}, (err, record) => unless err @constructor.get('all').remove(@) do @destroyed callback?(err) # `validate` performs the record level validations determining the record's validity. These may be asynchronous, # in which case `validate` has no useful return value. Results from asynchronous validations can be received by # listening to the `afterValidation` lifecycle callback. validate: (callback) -> oldState = @state() @errors.clear() do @validating finish = () => do @validated @[oldState]() callback?(@errors.length == 0, @errors) validators = @_batman.get('validators') || [] unless validators.length > 0 finish() else count = validators.length validationCallback = => if --count == 0 finish() for validator in validators v = validator.validator # Run the validator `v` or the custom callback on each key it validates by instantiating a new promise # and passing it to the appropriate function along with the key and the value to be validated. for key in validator.keys if v v.validateEach @errors, @, key, validationCallback else validator.callback @errors, @, key, validationCallback return isNew: -> typeof @get('id') is 'undefined' # ## Associations class Batman.AssociationProxy extends Batman.Object isProxy: true constructor: (@association, @model) -> loaded: false toJSON: -> target = @get('target') @get('target').toJSON() if target? load: (callback) -> @fetch (err, proxiedRecord) => unless err @set 'loaded', true @set 'target', proxiedRecord callback?(err, proxiedRecord) @get('target') fetch: (callback) -> unless (@get('foreignValue') || @get('primaryValue'))? return callback(undefined, undefined) record = @fetchFromLocal() if record return callback(undefined, record) else @fetchFromRemote(callback) @accessor 'loaded', Batman.Property.defaultAccessor @accessor 'target', get: -> @fetchFromLocal() set: (_, v) -> v # This just needs to bust the cache @accessor get: (k) -> @get('target')?.get(k) set: (k, v) -> @get('target')?.set(k, v) class Batman.BelongsToProxy extends Batman.AssociationProxy @accessor 'foreignValue', -> @model.get(@association.foreignKey) fetchFromLocal: -> @association.setIndex().get(@get('foreignValue')) fetchFromRemote: (callback) -> @association.getRelatedModel().find @get('foreignValue'), (error, loadedRecord) => throw error if error callback undefined, loadedRecord class Batman.HasOneProxy extends Batman.AssociationProxy @accessor 'primaryValue', -> @model.get(@association.primaryKey) fetchFromLocal: -> @association.setIndex().get(@get('primaryValue')) fetchFromRemote: (callback) -> loadOptions = {} loadOptions[@association.foreignKey] = @get('primaryValue') @association.getRelatedModel().load loadOptions, (error, loadedRecords) => throw error if error if !loadedRecords or loadedRecords.length <= 0 callback new Error("Couldn't find related record!"), undefined else callback undefined, loadedRecords[0] class Batman.AssociationSet extends Batman.SetSort constructor: (@value, @association) -> base = new Batman.Set super(base, 'hashKey') loaded: false load: (callback) -> return callback(undefined, @) unless @value? loadOptions = {} loadOptions[@association.foreignKey] = @value @association.getRelatedModel().load loadOptions, (err, records) => @loaded = true unless err @fire 'loaded' callback(err, @) class Batman.UniqueAssociationSetIndex extends Batman.UniqueSetIndex constructor: (@association, key) -> super @association.getRelatedModel().get('loaded'), key class Batman.AssociationSetIndex extends Batman.SetIndex constructor: (@association, key) -> super @association.getRelatedModel().get('loaded'), key _resultSetForKey: (key) -> @_storage.getOrSet key, => new Batman.AssociationSet(key, @association) _setResultSet: (key, set) -> @_storage.set key, set class Batman.AssociationCurator extends Batman.SimpleHash @availableAssociations: ['belongsTo', 'hasOne', 'hasMany'] constructor: (@model) -> super() # Contains (association, label) pairs mapped by association type # ie. @storage = {<Association.associationType>: [<Association>, <Association>]} @_byTypeStorage = new Batman.SimpleHash add: (association) -> @set association.label, association unless associationTypeSet = @_byTypeStorage.get(association.associationType) associationTypeSet = new Batman.SimpleSet @_byTypeStorage.set association.associationType, associationTypeSet associationTypeSet.add association getByType: (type) -> @_byTypeStorage.get(type) getByLabel: (label) -> @get(label) reset: -> @forEach (label, association) -> association.reset() true merge: (others...) -> result = super result._byTypeStorage = @_byTypeStorage.merge(others.map (other) -> other._byTypeStorage) result class Batman.Association associationType: '' defaultOptions: saveInline: true autoload: true constructor: (@model, @label, options = {}) -> defaultOptions = namespace: Batman.currentApp name: helpers.camelize(helpers.singularize(@label)) @options = $mixin defaultOptions, @defaultOptions, options # Setup encoders and accessors for this association. The accessor needs reference to this # association object, so curry the association info into the getAccessor, which has the # model applied as the context @model.encode label, @encoder() self = @ getAccessor = -> return self.getAccessor.call(@, self, @model, @label) @model.accessor @label, get: getAccessor set: model.defaultAccessor.set unset: model.defaultAccessor.unset if @url @model.url ||= (recordOptions) -> return self.url(recordOptions) getRelatedModel: -> scope = @options.namespace or Batman.currentApp modelName = @options.name relatedModel = scope?[modelName] developer.do -> if Batman.currentApp? and not relatedModel developer.warn "Related model #{modelName} hasn't loaded yet." relatedModel getFromAttributes: (record) -> record.constructor.defaultAccessor.get.call(record, @label) setIntoAttributes: (record, value) -> record.constructor.defaultAccessor.set.call(record, @label, value) encoder: -> developer.error "You must override encoder in Batman.Association subclasses." setIndex: -> developer.error "You must override setIndex in Batman.Association subclasses." inverse: -> if relatedAssocs = @getRelatedModel()._batman.get('associations') if @options.inverseOf return relatedAssocs.getByLabel(@options.inverseOf) inverse = null relatedAssocs.forEach (label, assoc) => if assoc.getRelatedModel() is @model inverse = assoc inverse reset: -> delete @index true class Batman.SingularAssociation extends Batman.Association isSingular: true getAccessor: (self, model, label) -> # Check whether the relation has already been set on this model if recordInAttributes = self.getFromAttributes(@) return recordInAttributes # Make sure the related model has been loaded if self.getRelatedModel() proxy = @associationProxy(self) Batman.Property.withoutTracking -> if not proxy.get('loaded') and self.options.autoload proxy.load() proxy setIndex: -> @index ||= new Batman.UniqueAssociationSetIndex(@, @[@indexRelatedModelOn]) @index class Batman.PluralAssociation extends Batman.Association isSingular: false setForRecord: (record) -> Batman.Property.withoutTracking => if id = record.get(@primaryKey) @setIndex().get(id) else new Batman.AssociationSet(undefined, @) getAccessor: (self, model, label) -> return unless self.getRelatedModel() # Check whether the relation has already been set on this model if setInAttributes = self.getFromAttributes(@) setInAttributes else relatedRecords = self.setForRecord(@) self.setIntoAttributes(@, relatedRecords) Batman.Property.withoutTracking => if self.options.autoload and not @isNew() and not relatedRecords.loaded relatedRecords.load (error, records) -> throw error if error relatedRecords setIndex: -> @index ||= new Batman.AssociationSetIndex(@, @[@indexRelatedModelOn]) @index class Batman.BelongsToAssociation extends Batman.SingularAssociation associationType: 'belongsTo' proxyClass: Batman.BelongsToProxy indexRelatedModelOn: 'primaryKey' defaultOptions: saveInline: false autoload: true constructor: -> super @foreignKey = @options.foreignKey or "#{@label}_id" @primaryKey = @options.primaryKey or "id" @model.encode @foreignKey url: (recordOptions) -> if inverse = @inverse() root = Batman.helpers.pluralize(@label) id = recordOptions.data?["#{@label}_id"] helper = if inverse.isSingular then "singularize" else "pluralize" ending = Batman.helpers[helper](inverse.label) return "/#{root}/#{id}/#{ending}" encoder: -> association = @ encoder = encode: false decode: (data, _, __, ___, childRecord) -> relatedModel = association.getRelatedModel() record = new relatedModel() record.fromJSON(data) record = relatedModel._mapIdentity(record) if association.options.inverseOf if inverse = association.inverse() if inverse instanceof Batman.HasManyAssociation # Rely on the parent's set index to get this out. childRecord.set(association.foreignKey, record.get(association.primaryKey)) else record.set(inverse.label, childRecord) childRecord.set(association.label, record) record if @options.saveInline encoder.encode = (val) -> val.toJSON() encoder apply: (base) -> if model = base.get(@label) foreignValue = model.get(@primaryKey) if foreignValue isnt undefined base.set @foreignKey, foreignValue class Batman.HasOneAssociation extends Batman.SingularAssociation associationType: 'hasOne' proxyClass: Batman.HasOneProxy indexRelatedModelOn: 'foreignKey' constructor: -> super @primaryKey = @options.primaryKey or "id" @foreignKey = @options.foreignKey or "#{helpers.underscore($functionName(@model))}_id" apply: (baseSaveError, base) -> if relation = @getFromAttributes(base) relation.set @foreignKey, base.get(@primaryKey) encoder: -> association = @ return { encode: (val, key, object, record) -> return unless association.options.saveInline if json = val.toJSON() json[association.foreignKey] = record.get(association.primaryKey) json decode: (data, _, __, ___, parentRecord) -> relatedModel = association.getRelatedModel() record = new (relatedModel)() record.fromJSON(data) if association.options.inverseOf record.set association.options.inverseOf, parentRecord record = relatedModel._mapIdentity(record) record } class Batman.HasManyAssociation extends Batman.PluralAssociation associationType: 'hasMany' indexRelatedModelOn: 'foreignKey' constructor: -> super @primaryKey = @options.primaryKey or "PI:KEY:<KEY>END_PI" @foreignKey = @options.foreignKey or "#{helpers.underscore($functionName(@model))}_PI:KEY:<KEY>END_PI" apply: (baseSaveError, base) -> unless baseSaveError if relations = @getFromAttributes(base) relations.forEach (model) => model.set @foreignKey, base.get(@primaryKey) base.set @label, @setForRecord(base) encoder: -> association = @ return { encode: (relationSet, _, __, record) -> return if association._beingEncoded association._beingEncoded = true return unless association.options.saveInline if relationSet? jsonArray = [] relationSet.forEach (relation) -> relationJSON = relation.toJSON() relationJSON[association.foreignKey] = record.get(association.primaryKey) jsonArray.push relationJSON delete association._beingEncoded jsonArray decode: (data, key, _, __, parentRecord) -> if relatedModel = association.getRelatedModel() existingRelations = association.getFromAttributes(parentRecord) || association.setForRecord(parentRecord) existingArray = existingRelations?.toArray() for jsonObject, i in data record = if existingArray && existingArray[i] existing = true existingArray[i] else existing = false new relatedModel() record.fromJSON jsonObject if association.options.inverseOf record.set association.options.inverseOf, parentRecord record = relatedModel._mapIdentity(record) existingRelations.add record else developer.error "Can't decode model #{association.options.name} because it hasn't been loaded yet!" existingRelations } # ### Model Associations API for k in Batman.AssociationCurator.availableAssociations do (k) => Batman.Model[k] = (label, scope) -> Batman.initializeObject(@) collection = @_batman.associations ||= new Batman.AssociationCurator(@) collection.add new Batman["#{helpers.capitalize(k)}Association"](@, label, scope) class Batman.ValidationError extends Batman.Object constructor: (attribute, message) -> super({attribute, message}) # `ErrorSet` is a simple subclass of `Set` which makes it a bit easier to # manage the errors on a model. class Batman.ErrorsSet extends Batman.Set # Define a default accessor to get the set of errors on a key @accessor (key) -> @indexedBy('attribute').get(key) # Define a shorthand method for adding errors to a key. add: (key, error) -> super(new Batman.ValidationError(key, error)) class Batman.Validator extends Batman.Object constructor: (@options, mixins...) -> super mixins... validate: (record) -> developer.error "You must override validate in Batman.Validator subclasses." format: (key, messageKey, interpolations) -> t('errors.format', {attribute: key, message: t("errors.messages.#{messageKey}", interpolations)}) @options: (options...) -> Batman.initializeObject @ if @_batman.options then @_batman.options.concat(options) else @_batman.options = options @matches: (options) -> results = {} shouldReturn = no for key, value of options if ~@_batman?.options?.indexOf(key) results[key] = value shouldReturn = yes return results if shouldReturn Validators = Batman.Validators = [ class Batman.LengthValidator extends Batman.Validator @options 'minLength', 'maxLength', 'length', 'lengthWithin', 'lengthIn' constructor: (options) -> if range = (options.lengthIn or options.lengthWithin) options.minLength = range[0] options.maxLength = range[1] || -1 delete options.lengthWithin delete options.lengthIn super validateEach: (errors, record, key, callback) -> options = @options value = record.get(key) ? [] if options.minLength and value.length < options.minLength errors.add key, @format(key, 'too_short', {count: options.minLength}) if options.maxLength and value.length > options.maxLength errors.add key, @format(key, 'too_long', {count: options.maxLength}) if options.length and value.length isnt options.length errors.add key, @format(key, 'wrong_length', {count: options.length}) callback() class Batman.PresenceValidator extends Batman.Validator @options 'presence' validateEach: (errors, record, key, callback) -> value = record.get(key) if @options.presence && (!value? || value is '') errors.add key, @format(key, 'blank') callback() ] $mixin Batman.translate.messages, errors: format: "%{attribute} %{message}" messages: too_short: "must be at least %{count} characters" too_long: "must be less than %{count} characters" wrong_length: "must be %{count} characters" blank: "can't be blank" class Batman.StorageAdapter extends Batman.Object class @StorageError extends Error name: "StorageError" constructor: (message) -> super @message = message class @RecordExistsError extends @StorageError name: 'RecordExistsError' constructor: (message) -> super(message || "Can't create this record because it already exists in the store!") class @NotFoundError extends @StorageError name: 'NotFoundError' constructor: (message) -> super(message || "Record couldn't be found in storage!") constructor: (model) -> super(model: model) isStorageAdapter: true storageKey: (record) -> model = record?.constructor || @model model.get('storageKey') || helpers.pluralize(helpers.underscore($functionName(model))) getRecordFromData: (attributes, constructor = @model) -> record = new constructor() record.fromJSON(attributes) record @skipIfError: (f) -> return (env, next) -> if env.error? next() else f.call(@, env, next) before: -> @_addFilter('before', arguments...) after: -> @_addFilter('after', arguments...) _inheritFilters: -> if !@_batman.check(@) || !@_batman.filters oldFilters = @_batman.getFirst('filters') @_batman.filters = {before: {}, after: {}} if oldFilters? for position, filtersByKey of oldFilters for key, filtersList of filtersByKey @_batman.filters[position][key] = filtersList.slice(0) _addFilter: (position, keys..., filter) -> @_inheritFilters() for key in keys @_batman.filters[position][key] ||= [] @_batman.filters[position][key].push filter true runFilter: (position, action, env, callback) -> @_inheritFilters() allFilters = @_batman.filters[position].all || [] actionFilters = @_batman.filters[position][action] || [] env.action = action # Action specific filters execute first, and then the `all` filters. filters = actionFilters.concat(allFilters) next = (newEnv) => env = newEnv if newEnv? if (nextFilter = filters.shift())? nextFilter.call @, env, next else callback.call @, env next() runBeforeFilter: -> @runFilter 'before', arguments... runAfterFilter: (action, env, callback) -> @runFilter 'after', action, env, @exportResult(callback) exportResult: (callback) -> (env) -> callback(env.error, env.result, env) _jsonToAttributes: (json) -> JSON.parse(json) perform: (key, recordOrProto, options, callback) -> options ||= {} env = {options} if key == 'PI:KEY:<KEY>END_PI' env.proto = recordOrProto else env.record = recordOrProto next = (newEnv) => env = newEnv if newEnv? @runAfterFilter key, env, callback @runBeforeFilter key, env, (env) -> @[key](env, next) class Batman.LocalStorage extends Batman.StorageAdapter constructor: -> return null if typeof window.localStorage is 'undefined' super @storage = localStorage storageRegExpForRecord: (record) -> new RegExp("^#{@storageKey(record)}(\\d+)$") nextIdForRecord: (record) -> re = @storageRegExpForRecord(record) nextId = 1 @_forAllStorageEntries (k, v) -> if matches = re.exec(k) nextId = Math.max(nextId, parseInt(matches[1], 10) + 1) nextId _forAllStorageEntries: (iterator) -> for i in [0...@storage.length] key = @storage.key(i) iterator.call(@, key, @storage.getItem(key)) true _storageEntriesMatching: (proto, options) -> re = @storageRegExpForRecord(proto) records = [] @_forAllStorageEntries (storageKey, storageString) -> if keyMatches = re.exec(storageKey) data = @_jsonToAttributes(storageString) data[proto.constructor.primaryKey] = keyMatches[1] records.push data if @_dataMatches(options, data) records _dataMatches: (conditions, data) -> match = true for k, v of conditions if data[k] != v match = false break match @::before 'read', 'create', 'update', 'destroy', @skipIfError (env, next) -> if env.action == 'create' env.id = env.record.get('id') || env.record.set('id', @nextIdForRecord(env.record)) else env.id = env.record.get('id') unless env.id? env.error = new @constructor.StorageError("Couldn't get/set record primary key on #{env.action}!") else env.key = @storageKey(env.record) + env.id next() @::before 'create', 'update', @skipIfError (env, next) -> env.recordAttributes = JSON.stringify(env.record) next() @::after 'read', @skipIfError (env, next) -> if typeof env.recordAttributes is 'string' try env.recordAttributes = @_jsonToAttributes(env.recordAttributes) catch error env.error = error return next() env.record.fromJSON env.recordAttributes next() @::after 'read', 'create', 'update', 'destroy', @skipIfError (env, next) -> env.result = env.record next() @::after 'readAll', @skipIfError (env, next) -> env.result = env.records = for recordAttributes in env.recordsAttributes @getRecordFromData(recordAttributes, env.proto.constructor) next() read: @skipIfError (env, next) -> env.recordAttributes = @storage.getItem(env.key) if !env.recordAttributes env.error = new @constructor.NotFoundError() next() create: @skipIfError ({key, recordAttributes}, next) -> if @storage.getItem(key) arguments[0].error = new @constructor.RecordExistsError else @storage.setItem(key, recordAttributes) next() update: @skipIfError ({key, recordAttributes}, next) -> @storage.setItem(key, recordAttributes) next() destroy: @skipIfError ({key}, next) -> @storage.removeItem(key) next() readAll: @skipIfError ({proto, options}, next) -> try arguments[0].recordsAttributes = @_storageEntriesMatching(proto, options.data) catch error arguments[0].error = error next() class Batman.SessionStorage extends Batman.LocalStorage constructor: -> if typeof window.sessionStorage is 'undefined' return null super @storage = sessionStorage class Batman.RestStorage extends Batman.StorageAdapter @JSONContentType: 'application/json' @PostBodyContentType: 'application/x-www-form-urlencoded' defaultRequestOptions: type: 'json' serializeAsForm: true constructor: -> super @defaultRequestOptions = $mixin {}, @defaultRequestOptions recordJsonNamespace: (record) -> helpers.singularize(@storageKey(record)) collectionJsonNamespace: (proto) -> helpers.pluralize(@storageKey(proto)) _execWithOptions: (object, key, options) -> if typeof object[key] is 'function' then object[key](options) else object[key] _defaultCollectionUrl: (record) -> "/#{@storageKey(record)}" urlForRecord: (record, env) -> if record.url url = @_execWithOptions(record, 'url', env.options) else url = if record.constructor.url @_execWithOptions(record.constructor, 'url', env.options) else @_defaultCollectionUrl(record) if env.action != 'create' if (id = record.get('id'))? url = url + "/" + id else throw new @constructor.StorageError("Couldn't get/set record primary key on #{env.action}!") @urlPrefix(record, env) + url + @urlSuffix(record, env) urlForCollection: (model, env) -> url = if model.url @_execWithOptions(model, 'url', env.options) else @_defaultCollectionUrl(model::, env.options) @urlPrefix(model, env) + url + @urlSuffix(model, env) urlPrefix: (object, env) -> @_execWithOptions(object, 'urlPrefix', env.options) || '' urlSuffix: (object, env) -> @_execWithOptions(object, 'urlSuffix', env.options) || '' request: (env, next) -> options = $mixin env.options, success: (data) -> env.data = data error: (error) -> env.error = error loaded: -> env.response = req.get('response') next() req = new Batman.Request(options) perform: (key, record, options, callback) -> $mixin (options ||= {}), @defaultRequestOptions super @::before 'create', 'read', 'update', 'destroy', @skipIfError (env, next) -> try env.options.url = @urlForRecord(env.record, env) catch error env.error = error next() @::before 'readAll', @skipIfError (env, next) -> try env.options.url = @urlForCollection(env.proto.constructor, env) catch error env.error = error next() @::before 'create', 'update', @skipIfError (env, next) -> json = env.record.toJSON() if namespace = @recordJsonNamespace(env.record) data = {} data[namespace] = json else data = json if @serializeAsForm # Leave the POJO in the data for the request adapter to serialize to a body env.options.contentType = @constructor.PostBodyContentType else data = JSON.stringify(data) env.options.contentType = @constructor.JSONContentType env.options.data = data next() @::after 'create', 'read', 'update', @skipIfError (env, next) -> if typeof env.data is 'string' try json = @_jsonToAttributes(env.data) catch error env.error = error return next() else json = env.data namespace = @recordJsonNamespace(env.record) json = json[namespace] if namespace && json[namespace]? env.record.fromJSON(json) env.result = env.record next() @::after 'readAll', @skipIfError (env, next) -> if typeof env.data is 'string' try env.data = JSON.parse(env.env) catch jsonError env.error = jsonError return next() namespace = @collectionJsonNamespace(env.proto) env.recordsAttributes = if namespace && env.data[namespace]? env.data[namespace] else env.data env.result = env.records = for jsonRecordAttributes in env.recordsAttributes @getRecordFromData(jsonRecordAttributes, env.proto.constructor) next() @HTTPMethods = create: 'POST' update: 'PUT' read: 'GET' readAll: 'GET' destroy: 'DELETE' for key in ['create', 'read', 'update', 'destroy', 'readAll'] do (key) => @::[key] = @skipIfError (env, next) -> env.options.method = @constructor.HTTPMethods[key] @request(env, next) # Views # ----------- class Batman.ViewStore extends Batman.Object @prefix: 'views' constructor: -> super @_viewContents = {} @_requestedPaths = new Batman.SimpleSet propertyClass: Batman.Property fetchView: (path) -> developer.do -> unless typeof Batman.View::prefix is 'undefined' developer.warn "Batman.View.prototype.prefix has been removed, please use Batman.ViewStore.prefix instead." new Batman.Request url: Batman.Navigator.normalizePath(@constructor.prefix, "#{path}.html") type: 'html' success: (response) => @set(path, response) error: (response) -> throw new Error("Could not load view from #{path}") @accessor 'final': true get: (path) -> return @get("/#{path}") unless path[0] is '/' return @_viewContents[path] if @_viewContents[path] return if @_requestedPaths.has(path) @fetchView(path) return set: (path, content) -> return @set("/#{path}", content) unless path[0] is '/' @_requestedPaths.add(path) @_viewContents[path] = content prefetch: (path) -> @get(path) true # A `Batman.View` can function two ways: a mechanism to load and/or parse html files # or a root of a subclass hierarchy to create rich UI classes, like in Cocoa. class Batman.View extends Batman.Object isView: true constructor: (options = {}) -> context = options.context if context unless context instanceof Batman.RenderContext context = Batman.RenderContext.root().descend(context) else context = Batman.RenderContext.root() options.context = context.descend(@) super(options) # Start the rendering by asking for the node Batman.Property.withoutTracking => if node = @get('node') @render node else @observe 'node', (node) => @render(node) @store: new Batman.ViewStore() # Set the source attribute to an html file to have that file loaded. source: '' # Set the html to a string of html to have that html parsed. html: '' # Set an existing DOM node to parse immediately. node: null # Fires once a node is parsed. @::event('ready').oneShot = true @accessor 'html', get: -> return @html if @html && @html.length > 0 return unless source = @get 'source' source = Batman.Navigator.normalizePath(source) @html = @constructor.store.get(source) set: (_, html) -> @html = html @accessor 'node' get: -> unless @node html = @get('html') return unless html && html.length > 0 @hasContainer = true @node = document.createElement 'div' $setInnerHTML(@node, html) if @node.children.length > 0 Batman.data(@node.children[0], 'view', @) return @node set: (_, node) -> @node = node Batman.data(@node, 'view', @) updateHTML = (html) => if html? $setInnerHTML(@get('node'), html) @forget('html', updateHTML) @observeAndFire 'html', updateHTML render: (node) -> @event('ready').resetOneShot() @_renderer?.forgetAll() # We use a renderer with the continuation style rendering engine to not # block user interaction for too long during the render. if node @_renderer = new Batman.Renderer(node, null, @context, @) @_renderer.on 'rendered', => @fire('ready', node) @::on 'appear', -> @viewDidAppear? arguments... @::on 'disappear', -> @viewDidDisappear? arguments... @::on 'beforeAppear', -> @viewWillAppear? arguments... @::on 'beforeDisappear', -> @viewWillDisappear? arguments... # DOM Helpers # ----------- # `Batman.Renderer` will take a node and parse all recognized data attributes out of it and its children. # It is a continuation style parser, designed not to block for longer than 50ms at a time if the document # fragment is particularly long. class Batman.Renderer extends Batman.Object deferEvery: 50 constructor: (@node, callback, @context, view) -> super() @on('parsed', callback) if callback? developer.error "Must pass a RenderContext to a renderer for rendering" unless @context instanceof Batman.RenderContext @immediate = $setImmediate @start start: => @startTime = new Date @parseNode @node resume: => @startTime = new Date @parseNode @resumeNode finish: -> @startTime = null @prevent 'stopped' @fire 'parsed' @fire 'rendered' stop: -> $clearImmediate @immediate @fire 'stopped' forgetAll: -> for k in ['parsed', 'rendered', 'stopped'] @::event(k).oneShot = true bindingRegexp = /^data\-(.*)/ bindingSortOrder = ["renderif", "foreach", "formfor", "context", "bind", "source", "target"] bindingSortPositions = {} bindingSortPositions[name] = pos for name, pos in bindingSortOrder _sortBindings: (a,b) -> aindex = bindingSortPositions[a[0]] bindex = bindingSortPositions[b[0]] aindex ?= bindingSortOrder.length # put unspecified bindings last bindex ?= bindingSortOrder.length if aindex > bindex 1 else if bindex > aindex -1 else if a[0] > b[0] 1 else if b[0] > a[0] -1 else 0 parseNode: (node) -> if @deferEvery && (new Date - @startTime) > @deferEvery @resumeNode = node @timeout = $setImmediate @resume return if node.getAttribute and node.attributes bindings = for attr in node.attributes name = attr.nodeName.match(bindingRegexp)?[1] continue if not name if ~(varIndex = name.indexOf('-')) [name.substr(0, varIndex), name.substr(varIndex + 1), attr.value] else [name, attr.value] for readerArgs in bindings.sort(@_sortBindings) key = readerArgs[1] result = if readerArgs.length == 2 Batman.DOM.readers[readerArgs[0]]?(node, key, @context, @) else Batman.DOM.attrReaders[readerArgs[0]]?(node, key, readerArgs[2], @context, @) if result is false skipChildren = true break else if result instanceof Batman.RenderContext oldContext = @context @context = result $onParseExit(node, => @context = oldContext) if (nextNode = @nextNode(node, skipChildren)) then @parseNode(nextNode) else @finish() nextNode: (node, skipChildren) -> if not skipChildren children = node.childNodes return children[0] if children?.length sibling = node.nextSibling # Grab the reference before onParseExit may remove the node $onParseExit(node).forEach (callback) -> callback() $forgetParseExit(node) return if @node == node return sibling if sibling nextParent = node while nextParent = nextParent.parentNode $onParseExit(nextParent).forEach (callback) -> callback() $forgetParseExit(nextParent) return if @node == nextParent parentSibling = nextParent.nextSibling return parentSibling if parentSibling return # The RenderContext class manages the stack of contexts accessible to a view during rendering. class Batman.RenderContext @deProxy: (object) -> if object? && object.isContextProxy then object.get('proxiedObject') else object @root: -> if Batman.currentApp? Batman.currentApp.get('_renderContext') else @base constructor: (@object, @parent) -> findKey: (key) -> base = key.split('.')[0].split('|')[0].trim() currentNode = @ while currentNode # We define the behaviour of the context stack as latching a get when the first key exists, # so we need to check only if the basekey exists, not if all intermediary keys do as well. val = $get(currentNode.object, base) if typeof val isnt 'undefined' val = $get(currentNode.object, key) return [val, currentNode.object].map(@constructor.deProxy) currentNode = currentNode.parent @windowWrapper ||= window: Batman.container [$get(@windowWrapper, key), @windowWrapper] get: (key) -> @findKey(key)[0] # Below are the three primitives that all the `Batman.DOM` helpers are composed of. # `descend` takes an `object`, and optionally a `scopedKey`. It creates a new `RenderContext` leaf node # in the tree with either the object available on the stack or the object available at the `scopedKey` # on the stack. descend: (object, scopedKey) -> if scopedKey oldObject = object object = new Batman.Object() object[scopedKey] = oldObject return new @constructor(object, @) # `descendWithKey` takes a `key` and optionally a `scopedKey`. It creates a new `RenderContext` leaf node # with the runtime value of the `key` available on the stack or under the `scopedKey` if given. This # differs from a normal `descend` in that it looks up the `key` at runtime (in the parent `RenderContext`) # and will correctly reflect changes if the value at the `key` changes. A normal `descend` takes a concrete # reference to an object which never changes. descendWithKey: (key, scopedKey) -> proxy = new ContextProxy(@, key) return @descend(proxy, scopedKey) # `chain` flattens a `RenderContext`'s path to the root. chain: -> x = [] parent = this while parent x.push parent.object parent = parent.parent x # `ContextProxy` is a simple class which assists in pushing dynamic contexts onto the `RenderContext` tree. # This happens when a `data-context` is descended into, for each iteration in a `data-foreach`, # and in other specific HTML bindings like `data-formfor`. `ContextProxy`s use accessors so that if the # value of the object they proxy changes, the changes will be propagated to any thing observing the `ContextProxy`. # This is good because it allows `data-context` to take keys which will change, filtered keys, and even filters # which take keypath arguments. It will calculate the context to descend into when any of those keys change # because it preserves the property of a binding, and importantly it exposes a friendly `Batman.Object` # interface for the rest of the `Binding` code to work with. @ContextProxy = class ContextProxy extends Batman.Object isContextProxy: true # Reveal the binding's final value. @accessor 'proxiedObject', -> @binding.get('filteredValue') # Proxy all gets to the proxied object. @accessor get: (key) -> @get("proxiedObject.#{key}") set: (key, value) -> @set("proxiedObject.#{key}", value) unset: (key) -> @unset("proxiedObject.#{key}") constructor: (@renderContext, @keyPath, @localKey) -> @binding = new Batman.DOM.AbstractBinding(undefined, @keyPath, @renderContext) Batman.RenderContext.base = new Batman.RenderContext(window: Batman.container) Batman.DOM = { # `Batman.DOM.readers` contains the functions used for binding a node's value or innerHTML, showing/hiding nodes, # and any other `data-#{name}=""` style DOM directives. readers: { target: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'nodeChange') true source: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'dataChange') true bind: (node, key, context, renderer, only) -> bindingClass = false switch node.nodeName.toLowerCase() when 'input' switch node.getAttribute('type') when 'checkbox' Batman.DOM.attrReaders.bind(node, 'checked', key, context, renderer, only) return true when 'radio' bindingClass = Batman.DOM.RadioBinding when 'file' bindingClass = Batman.DOM.FileBinding when 'select' bindingClass = Batman.DOM.SelectBinding bindingClass ||= Batman.DOM.Binding new bindingClass(arguments...) true context: (node, key, context, renderer) -> return context.descendWithKey(key) mixin: (node, key, context, renderer) -> new Batman.DOM.MixinBinding(node, key, context.descend(Batman.mixins), renderer) true showif: (node, key, context, parentRenderer, invert) -> new Batman.DOM.ShowHideBinding(node, key, context, parentRenderer, false, invert) true hideif: -> Batman.DOM.readers.showif(arguments..., yes) route: -> new Batman.DOM.RouteBinding(arguments...) true view: -> new Batman.DOM.ViewBinding arguments... false partial: (node, path, context, renderer) -> Batman.DOM.partial node, path, context, renderer true defineview: (node, name, context, renderer) -> $onParseExit(node, -> $removeNode(node)) Batman.View.store.set(Batman.Navigator.normalizePath(name), node.innerHTML) false renderif: (node, key, context, renderer) -> new Batman.DOM.DeferredRenderingBinding(node, key, context, renderer) false yield: (node, key) -> $setImmediate -> Batman.DOM.yield key, node true contentfor: (node, key) -> $setImmediate -> Batman.DOM.contentFor key, node true replace: (node, key) -> $setImmediate -> Batman.DOM.replace key, node true } _yielders: {} # name/fn pairs of yielding functions _yields: {} # name/container pairs of yielding nodes # `Batman.DOM.attrReaders` contains all the DOM directives which take an argument in their name, in the # `data-dosomething-argument="keypath"` style. This means things like foreach, binding attributes like # disabled or anything arbitrary, descending into a context, binding specific classes, or binding to events. attrReaders: { _parseAttribute: (value) -> if value is 'false' then value = false if value is 'true' then value = true value source: (node, attr, key, context, renderer) -> Batman.DOM.attrReaders.bind node, attr, key, context, renderer, 'dataChange' bind: (node, attr, key, context, renderer, only) -> bindingClass = switch attr when 'checked', 'disabled', 'selected' Batman.DOM.CheckedBinding when 'value', 'href', 'src', 'size' Batman.DOM.NodeAttributeBinding when 'class' Batman.DOM.ClassBinding when 'style' Batman.DOM.StyleBinding else Batman.DOM.AttributeBinding new bindingClass(arguments...) true context: (node, contextName, key, context) -> return context.descendWithKey(key, contextName) event: (node, eventName, key, context) -> new Batman.DOM.EventBinding(arguments...) true addclass: (node, className, key, context, parentRenderer, invert) -> new Batman.DOM.AddClassBinding(node, className, key, context, parentRenderer, false, invert) true removeclass: (node, className, key, context, parentRenderer) -> Batman.DOM.attrReaders.addclass node, className, key, context, parentRenderer, yes foreach: (node, iteratorName, key, context, parentRenderer) -> new Batman.DOM.IteratorBinding(arguments...) false # Return false so the Renderer doesn't descend into this node's children. formfor: (node, localName, key, context) -> new Batman.DOM.FormBinding(arguments...) context.descendWithKey(key, localName) view: (node, bindKey, contextKey, context) -> [_, parent] = context.findKey contextKey view = null parent.observeAndFire contextKey, (newValue) -> view ||= Batman.data node, 'view' view?.set bindKey, newValue } # `Batman.DOM.events` contains the helpers used for binding to events. These aren't called by # DOM directives, but are used to handle specific events by the `data-event-#{name}` helper. events: { click: (node, callback, context, eventName = 'click') -> $addEventListener node, eventName, (args...) -> callback node, args..., context $preventDefault args[0] if node.nodeName.toUpperCase() is 'A' and not node.href node.href = '#' node doubleclick: (node, callback, context) -> # The actual DOM event is called `dblclick` Batman.DOM.events.click node, callback, context, 'dblclick' change: (node, callback, context) -> eventNames = switch node.nodeName.toUpperCase() when 'TEXTAREA' then ['keyup', 'change'] when 'INPUT' if node.type.toLowerCase() in Batman.DOM.textInputTypes oldCallback = callback callback = (e) -> return if e.type == 'keyup' && 13 <= e.keyCode <= 14 oldCallback(arguments...) ['keyup', 'change'] else ['change'] else ['change'] for eventName in eventNames $addEventListener node, eventName, (args...) -> callback node, args..., context isEnter: (ev) -> ev.keyCode is 13 || ev.which is 13 || ev.keyIdentifier is 'Enter' || ev.key is 'Enter' submit: (node, callback, context) -> if Batman.DOM.nodeIsEditable(node) $addEventListener node, 'keydown', (args...) -> if Batman.DOM.events.isEnter(args[0]) Batman.DOM._keyCapturingNode = node $addEventListener node, 'keyup', (args...) -> if Batman.DOM.events.isEnter(args[0]) if Batman.DOM._keyCapturingNode is node $preventDefault args[0] callback node, args..., context Batman.DOM._keyCapturingNode = null else $addEventListener node, 'submit', (args...) -> $preventDefault args[0] callback node, args..., context node other: (node, eventName, callback, context) -> $addEventListener node, eventName, (args...) -> callback node, args..., context } # List of input type="types" for which we can use keyup events to track textInputTypes: ['text', 'search', 'tel', 'url', 'email', 'password'] # `yield` and `contentFor` are used to declare partial views and then pull them in elsewhere. # `replace` is used to replace yielded content. # This can be used for abstraction as well as repetition. yield: (name, node) -> Batman.DOM._yields[name] = node # render any content for this yield if yielders = Batman.DOM._yielders[name] fn(node) for fn in yielders contentFor: (name, node, _replaceContent, _yieldChildren) -> yieldingNode = Batman.DOM._yields[name] # Clone the node if it's a child in case the parent gets cleared during the yield if yieldingNode and $isChildOf(yieldingNode, node) node = $cloneNode node yieldFn = (yieldingNode) -> if _replaceContent || !Batman._data(yieldingNode, 'yielded') $setInnerHTML yieldingNode, '', true Batman.DOM.didRemoveNode(child) for child in yieldingNode.children if _yieldChildren while node.childNodes.length > 0 child = node.childNodes[0] view = Batman.data(child, 'view') view?.fire 'beforeAppear', child $appendChild yieldingNode, node.childNodes[0], true view?.fire 'appear', child else view = Batman.data(node, 'view') view?.fire 'beforeAppear', child $appendChild yieldingNode, node, true view?.fire 'appear', child Batman._data node, 'yielded', true Batman._data yieldingNode, 'yielded', true delete Batman.DOM._yielders[name] if contents = Batman.DOM._yielders[name] contents.push yieldFn else Batman.DOM._yielders[name] = [yieldFn] if yieldingNode Batman.DOM.yield name, yieldingNode replace: (name, node, _yieldChildren) -> Batman.DOM.contentFor name, node, true, _yieldChildren partial: (container, path, context, renderer) -> renderer.prevent 'rendered' view = new Batman.View source: path context: context view.on 'ready', -> $setInnerHTML container, '' # Render the partial content into the data-partial node # Text nodes move when they are appended, so copy childNodes children = (node for node in view.get('node').childNodes) $appendChild(container, child) for child in children renderer.allowAndFire 'rendered' # Adds a binding or binding-like object to the `bindings` set in a node's # data, so that upon node removal we can unset the binding and any other objects # it retains. trackBinding: $trackBinding = (binding, node) -> if bindings = Batman._data node, 'bindings' bindings.add binding else Batman._data node, 'bindings', new Batman.SimpleSet(binding) Batman.DOM.fire('bindingAdded', binding) true # Removes listeners and bindings tied to `node`, allowing it to be cleared # or removed without leaking memory unbindNode: $unbindNode = (node) -> # break down all bindings if bindings = Batman._data node, 'bindings' bindings.forEach (binding) -> binding.die() # remove all event listeners if listeners = Batman._data node, 'listeners' for eventName, eventListeners of listeners eventListeners.forEach (listener) -> $removeEventListener node, eventName, listener # remove all bindings and other data associated with this node Batman.removeData node # external data (Batman.data) Batman.removeData node, undefined, true # internal data (Batman._data) # Unbinds the tree rooted at `node`. # When set to `false`, `unbindRoot` skips the `node` before unbinding all of its children. unbindTree: $unbindTree = (node, unbindRoot = true) -> $unbindNode node if unbindRoot $unbindTree(child) for child in node.childNodes # Copy the event handlers from src node to dst node copyNodeEventListeners: $copyNodeEventListeners = (dst, src) -> if listeners = Batman._data src, 'listeners' for eventName, eventListeners of listeners eventListeners.forEach (listener) -> $addEventListener dst, eventName, listener # Copy all event handlers from the src tree to the dst tree. Note that the # trees must have identical structures. copyTreeEventListeners: $copyTreeEventListeners = (dst, src) -> $copyNodeEventListeners dst, src for i in [0...src.childNodes.length] $copyTreeEventListeners dst.childNodes[i], src.childNodes[i] # Enhance the base cloneNode method to copy event handlers over to the new # instance cloneNode: $cloneNode = (node, deep=true) -> newNode = node.cloneNode(deep) if deep $copyTreeEventListeners newNode, node else $copyNodeEventListeners newNode, node newNode # Memory-safe setting of a node's innerHTML property setInnerHTML: $setInnerHTML = (node, html, args...) -> hide.apply(child, args) for child in node.childNodes when hide = Batman.data(child, 'hide') $unbindTree node, false node?.innerHTML = html setStyleProperty: $setStyleProperty = (node, property, value, importance) -> if node.style.setAttribute node.style.setAttribute(property, value, importance) else node.style.setProperty(property, value, importance) # Memory-safe removal of a node from the DOM removeNode: $removeNode = (node) -> node.parentNode?.removeChild node Batman.DOM.didRemoveNode(node) appendChild: $appendChild = (parent, child, args...) -> view = Batman.data(child, 'view') view?.fire 'beforeAppear', child Batman.data(child, 'show')?.apply(child, args) parent.appendChild(child) view?.fire 'appear', child insertBefore: $insertBefore = (parentNode, newNode, referenceNode = null) -> if !referenceNode or parentNode.childNodes.length <= 0 $appendChild parentNode, newNode else parentNode.insertBefore newNode, referenceNode valueForNode: (node, value = '', escapeValue = true) -> isSetting = arguments.length > 1 switch node.nodeName.toUpperCase() when 'INPUT', 'TEXTAREA' if isSetting then (node.value = value) else node.value when 'SELECT' if isSetting then node.value = value else if isSetting $setInnerHTML node, if escapeValue then $escapeHTML(value) else value else node.innerHTML nodeIsEditable: (node) -> node.nodeName.toUpperCase() in ['INPUT', 'TEXTAREA', 'SELECT'] # `$addEventListener uses attachEvent when necessary addEventListener: $addEventListener = (node, eventName, callback) -> # store the listener in Batman.data unless listeners = Batman._data node, 'listeners' listeners = Batman._data node, 'listeners', {} unless listeners[eventName] listeners[eventName] = new Batman.Set listeners[eventName].add callback if $hasAddEventListener node.addEventListener eventName, callback, false else node.attachEvent "on#{eventName}", callback # `$removeEventListener` uses detachEvent when necessary removeEventListener: $removeEventListener = (node, eventName, callback) -> # remove the listener from Batman.data if listeners = Batman._data node, 'listeners' if eventListeners = listeners[eventName] eventListeners.remove callback if $hasAddEventListener node.removeEventListener eventName, callback, false else node.detachEvent 'on'+eventName, callback hasAddEventListener: $hasAddEventListener = !!window?.addEventListener didRemoveNode: (node) -> view = Batman.data node, 'view' view?.fire 'beforeDisappear', node $unbindTree node view?.fire 'disappear', node onParseExit: $onParseExit = (node, callback) -> set = Batman._data(node, 'onParseExit') || Batman._data(node, 'onParseExit', new Batman.SimpleSet) set.add callback if callback? set forgetParseExit: $forgetParseExit = (node, callback) -> Batman.removeData(node, 'onParseExit', true) } $mixin Batman.DOM, Batman.EventEmitter, Batman.Observable Batman.DOM.event('bindingAdded') # Bindings are shortlived objects which manage the observation of any keypaths a `data` attribute depends on. # Bindings parse any keypaths which are filtered and use an accessor to apply the filters, and thus enjoy # the automatic trigger and dependency system that Batman.Objects use. Every, and I really mean every method # which uses filters has to be defined in terms of a new binding. This is so that the proper order of # objects is traversed and any observers are properly attached. class Batman.DOM.AbstractBinding extends Batman.Object # A beastly regular expression for pulling keypaths out of the JSON arguments to a filter. # It makes the following matches: # # + `foo` and `baz.qux` in `foo, "bar", baz.qux` # + `foo.bar.baz` in `true, false, "true", "false", foo.bar.baz` # + `true.bar` in `2, true.bar` # + `truesay` in truesay # + no matches in `"bar", 2, {"x":"y", "Z": foo.bar.baz}, "baz"` keypath_rx = /// (^|,) # Match either the start of an arguments list or the start of a space inbetween commas. \s* # Be insensitive to whitespace between the comma and the actual arguments. (?! # Use a lookahead to ensure we aren't matching true or false: (?:true|false) # Match either true or false ... \s* # and make sure that there's nothing else that comes after the true or false ... (?:$|,) # before the end of this argument in the list. ) ( [a-zA-Z][\w\.]* # Now that true and false can't be matched, match a dot delimited list of keys. [\?\!]? # Allow ? and ! at the end of a keypath to support Ruby's methods ) \s* # Be insensitive to whitespace before the next comma or end of the filter arguments list. (?=$|,) # Match either the next comma or the end of the filter arguments list. ///g # A less beastly pair of regular expressions for pulling out the [] syntax `get`s in a binding string, and # dotted names that follow them. get_dot_rx = /(?:\]\.)(.+?)(?=[\[\.]|\s*\||$)/ get_rx = /(?!^\s*)\[(.*?)\]/g # The `filteredValue` which calculates the final result by reducing the initial value through all the filters. @accessor 'filteredValue' get: -> unfilteredValue = @get('unfilteredValue') self = @ renderContext = @get('renderContext') if @filterFunctions.length > 0 developer.currentFilterStack = renderContext result = @filterFunctions.reduce((value, fn, i) -> # Get any argument keypaths from the context stored at parse time. args = self.filterArguments[i].map (argument) -> if argument._keypath self.renderContext.get(argument._keypath) else argument # Apply the filter. args.unshift value args.push self fn.apply(renderContext, args) , unfilteredValue) developer.currentFilterStack = null result else unfilteredValue # We ignore any filters for setting, because they often aren't reversible. set: (_, newValue) -> @set('unfilteredValue', newValue) # The `unfilteredValue` is whats evaluated each time any dependents change. @accessor 'unfilteredValue' get: -> # If we're working with an `@key` and not an `@value`, find the context the key belongs to so we can # hold a reference to it for passing to the `dataChange` and `nodeChange` observers. if k = @get('key') Batman.RenderContext.deProxy(@get("keyContext.#{k}")) else @get('value') set: (_, value) -> if k = @get('key') keyContext = @get('keyContext') # Supress sets on the window if keyContext != Batman.container @set("keyContext.#{k}", value) else @set('value', value) # The `keyContext` accessor is @accessor 'keyContext', -> @renderContext.findKey(@key)[1] bindImmediately: true shouldSet: true isInputBinding: false escapeValue: true constructor: (@node, @keyPath, @renderContext, @renderer, @only = false) -> # Pull out the `@key` and filter from the `@keyPath`. @parseFilter() # Observe the node and the data. @bind() if @bindImmediately isTwoWay: -> @key? && @filterFunctions.length is 0 bind: -> # Attach the observers. if @node? && @only in [false, 'nodeChange'] and Batman.DOM.nodeIsEditable(@node) Batman.DOM.events.change @node, @_fireNodeChange, @renderContext # Usually, we let the HTML value get updated upon binding by `observeAndFire`ing the dataChange # function below. When dataChange isn't attached, we update the JS land value such that the # sync between DOM and JS is maintained. if @only is 'nodeChange' @_fireNodeChange() # Observe the value of this binding's `filteredValue` and fire it immediately to update the node. if @only in [false, 'dataChange'] @observeAndFire 'filteredValue', @_fireDataChange Batman.DOM.trackBinding(@, @node) if @node? _fireNodeChange: => @shouldSet = false @nodeChange?(@node, @value || @get('keyContext')) @shouldSet = true _fireDataChange: (value) => if @shouldSet @dataChange?(value, @node) die: -> @forget() @_batman.properties?.forEach (key, property) -> property.die() parseFilter: -> # Store the function which does the filtering and the arguments (all except the actual value to apply the # filter to) in these arrays. @filterFunctions = [] @filterArguments = [] # Rewrite [] style gets, replace quotes to be JSON friendly, and split the string by pipes to see if there are any filters. keyPath = @keyPath keyPath = keyPath.replace(get_dot_rx, "]['$1']") while get_dot_rx.test(keyPath) # Stupid lack of lookbehind assertions... filters = keyPath.replace(get_rx, " | get $1 ").replace(/'/g, '"').split(/(?!")\s+\|\s+(?!")/) # The key will is always the first token before the pipe. try key = @parseSegment(orig = filters.shift())[0] catch e developer.warn e developer.error "Error! Couldn't parse keypath in \"#{orig}\". Parsing error above." if key and key._keypath @key = key._keypath else @value = key if filters.length while filterString = filters.shift() # For each filter, get the name and the arguments by splitting on the first space. split = filterString.indexOf(' ') if ~split filterName = filterString.substr(0, split) args = filterString.substr(split) else filterName = filterString # If the filter exists, grab it. if filter = Batman.Filters[filterName] @filterFunctions.push filter # Get the arguments for the filter by parsing the args as JSON, or # just pushing an placeholder array if args try @filterArguments.push @parseSegment(args) catch e developer.error "Bad filter arguments \"#{args}\"!" else @filterArguments.push [] else developer.error "Unrecognized filter '#{filterName}' in key \"#{@keyPath}\"!" true # Turn a piece of a `data` keypath into a usable javascript object. # + replacing keypaths using the above regular expression # + wrapping the `,` delimited list in square brackets # + and `JSON.parse`ing them as an array. parseSegment: (segment) -> JSON.parse( "[" + segment.replace(keypath_rx, "$1{\"_keypath\": \"$2\"}") + "]" ) class Batman.DOM.AbstractAttributeBinding extends Batman.DOM.AbstractBinding constructor: (node, @attributeName, args...) -> super(node, args...) class Batman.DOM.AbstractCollectionBinding extends Batman.DOM.AbstractAttributeBinding bindCollection: (newCollection) -> unless newCollection == @collection @unbindCollection() @collection = newCollection if @collection if @collection.isObservable && @collection.toArray @collection.observe 'toArray', @handleArrayChanged else if @collection.isEventEmitter @collection.on 'itemsWereAdded', @handleItemsWereAdded @collection.on 'itemsWereRemoved', @handleItemsWereRemoved else return false return true return false unbindCollection: -> if @collection if @collection.isObservable && @collection.toArray @collection.forget('toArray', @handleArrayChanged) else if @collection.isEventEmitter @collection.event('itemsWereAdded').removeHandler(@handleItemsWereAdded) @collection.event('itemsWereRemoved').removeHandler(@handleItemsWereRemoved) handleItemsWereAdded: -> handleItemsWereRemoved: -> handleArrayChanged: -> die: -> @unbindCollection() super class Batman.DOM.Binding extends Batman.DOM.AbstractBinding constructor: (node) -> @isInputBinding = node.nodeName.toLowerCase() in ['input', 'textarea'] super nodeChange: (node, context) -> if @isTwoWay() @set 'filteredValue', @node.value dataChange: (value, node) -> Batman.DOM.valueForNode @node, value, @escapeValue class Batman.DOM.AttributeBinding extends Batman.DOM.AbstractAttributeBinding dataChange: (value) -> @node.setAttribute(@attributeName, value) nodeChange: (node) -> if @isTwoWay() @set 'filteredValue', Batman.DOM.attrReaders._parseAttribute(node.getAttribute(@attributeName)) class Batman.DOM.NodeAttributeBinding extends Batman.DOM.AbstractAttributeBinding dataChange: (value = "") -> @node[@attributeName] = value nodeChange: (node) -> if @isTwoWay() @set 'filteredValue', Batman.DOM.attrReaders._parseAttribute(node[@attributeName]) class Batman.DOM.ShowHideBinding extends Batman.DOM.AbstractBinding constructor: (node, className, key, context, parentRenderer, @invert = false) -> display = node.style.display display = '' if not display or display is 'none' @originalDisplay = display super dataChange: (value) -> view = Batman.data @node, 'view' if !!value is not @invert view?.fire 'beforeAppear', @node Batman.data(@node, 'show')?.call(@node) @node.style.display = @originalDisplay view?.fire 'appear', @node else view?.fire 'beforeDisappear', @node if typeof (hide = Batman.data(@node, 'hide')) is 'function' hide.call @node else $setStyleProperty(@node, 'display', 'none', 'important') view?.fire 'disappear', @node class Batman.DOM.CheckedBinding extends Batman.DOM.NodeAttributeBinding isInputBinding: true dataChange: (value) -> @node[@attributeName] = !!value # Update the parent's binding if necessary if @node.parentNode Batman._data(@node.parentNode, 'updateBinding')?() constructor: -> super # Attach this binding to the node under the attribute name so that parent # bindings can query this binding and modify its state. This is useful # for <options> within a select or radio buttons. Batman._data @node, @attributeName, @ class Batman.DOM.ClassBinding extends Batman.DOM.AbstractCollectionBinding dataChange: (value) -> if value? @unbindCollection() if typeof value is 'string' @node.className = value else @bindCollection(value) @updateFromCollection() updateFromCollection: -> if @collection array = if @collection.map @collection.map((x) -> x) else (k for own k,v of @collection) array = array.toArray() if array.toArray? @node.className = array.join ' ' handleArrayChanged: => @updateFromCollection() handleItemsWereRemoved: => @updateFromCollection() handleItemsWereAdded: => @updateFromCollection() class Batman.DOM.DeferredRenderingBinding extends Batman.DOM.AbstractBinding rendered: false constructor: -> super @node.removeAttribute "data-renderif" nodeChange: -> dataChange: (value) -> if value && !@rendered @render() render: -> new Batman.Renderer(@node, null, @renderContext) @rendered = true class Batman.DOM.AddClassBinding extends Batman.DOM.AbstractAttributeBinding constructor: (node, className, keyPath, renderContext, renderer, only, @invert = false) -> names = className.split('|') @classes = for name in names { name: name pattern: new RegExp("(?:^|\\s)#{name}(?:$|\\s)", 'i') } super delete @attributeName dataChange: (value) -> currentName = @node.className for {name, pattern} in @classes includesClassName = pattern.test(currentName) if !!value is !@invert @node.className = "#{currentName} #{name}" if !includesClassName else @node.className = currentName.replace(pattern, '') if includesClassName true class Batman.DOM.EventBinding extends Batman.DOM.AbstractAttributeBinding bindImmediately: false constructor: (node, eventName, key, context) -> super confirmText = @node.getAttribute('data-confirm') callback = => return if confirmText and not confirm(confirmText) @get('filteredValue')?.apply @get('callbackContext'), arguments if attacher = Batman.DOM.events[@attributeName] attacher @node, callback, context else Batman.DOM.events.other @node, @attributeName, callback, context @accessor 'callbackContext', -> contextKeySegments = @key.split('.') contextKeySegments.pop() if contextKeySegments.length > 0 @get('keyContext').get(contextKeySegments.join('.')) else @get('keyContext') class Batman.DOM.RadioBinding extends Batman.DOM.AbstractBinding isInputBinding: true dataChange: (value) -> # don't overwrite `checked` attributes in the HTML unless a bound # value is defined in the context. if no bound value is found, bind # to the key if the node is checked. if (boundValue = @get('filteredValue'))? @node.checked = boundValue == @node.value else if @node.checked @set 'filteredValue', @node.value nodeChange: (node) -> if @isTwoWay() @set('filteredValue', Batman.DOM.attrReaders._parseAttribute(node.value)) class Batman.DOM.FileBinding extends Batman.DOM.AbstractBinding isInputBinding: true nodeChange: (node, subContext) -> return if !@isTwoWay() segments = @key.split('.') if segments.length > 1 keyContext = subContext.get(segments.slice(0, -1).join('.')) else keyContext = subContext actualObject = Batman.RenderContext.deProxy(keyContext) if actualObject.hasStorage && actualObject.hasStorage() for adapter in actualObject._batman.get('storage') when adapter instanceof Batman.RestStorage adapter.defaultRequestOptions.formData = true if node.hasAttribute('multiple') @set 'filteredValue', Array::slice.call(node.files) else @set 'filteredValue', node.files[0] class Batman.DOM.MixinBinding extends Batman.DOM.AbstractBinding dataChange: (value) -> $mixin @node, value if value? class Batman.DOM.SelectBinding extends Batman.DOM.AbstractBinding isInputBinding: true bindImmediately: false firstBind: true constructor: -> super # wait for the select to render before binding to it @renderer.on 'rendered', => if @node? Batman._data @node, 'updateBinding', @updateSelectBinding @bind() dataChange: (newValue) => # For multi-select boxes, the `value` property only holds the first # selection, so go through the child options and update as necessary. if newValue instanceof Array # Use a hash to map values to their nodes to avoid O(n^2). valueToChild = {} for child in @node.children # Clear all options. child.selected = false # Avoid collisions among options with same values. matches = valueToChild[child.value] if matches then matches.push child else matches = [child] valueToChild[child.value] = matches # Select options corresponding to the new values for value in newValue for match in valueToChild[value] match.selected = yes # For a regular select box, update the value. else if typeof newValue is 'undefined' && @firstBind @firstBind = false @set('unfilteredValue', @node.value) else Batman.DOM.valueForNode(@node, newValue, @escapeValue) # Finally, update the options' `selected` bindings @updateOptionBindings() nodeChange: => if @isTwoWay() @updateSelectBinding() @updateOptionBindings() updateSelectBinding: => # Gather the selected options and update the binding selections = if @node.multiple then (c.value for c in @node.children when c.selected) else @node.value selections = selections[0] if typeof selections is Array && selections.length == 1 @set 'unfilteredValue', selections true updateOptionBindings: => # Go through the option nodes and update their bindings using the # context and key attached to the node via Batman.data for child in @node.children if selectedBinding = Batman._data(child, 'selected') selectedBinding.nodeChange(selectedBinding.node) true class Batman.DOM.StyleBinding extends Batman.DOM.AbstractCollectionBinding class @SingleStyleBinding extends Batman.DOM.AbstractAttributeBinding constructor: (args..., @parent) -> super(args...) dataChange: (value) -> @parent.setStyle(@attributeName, value) constructor: -> @oldStyles = {} super dataChange: (value) -> unless value @reapplyOldStyles() return @unbindCollection() if typeof value is 'string' @reapplyOldStyles() for style in value.split(';') # handle a case when css value contains colons itself (absolute URI) # split and rejoin because IE7/8 don't splice values of capturing regexes into split's return array [cssName, colonSplitCSSValues...] = style.split(":") @setStyle cssName, colonSplitCSSValues.join(":") return if value instanceof Batman.Hash if @bindCollection(value) value.forEach (key, value) => @setStyle key, value else if value instanceof Object @reapplyOldStyles() for own key, keyValue of value # Check whether the value is an existing keypath, and if so bind this attribute to it [keypathValue, keypathContext] = @renderContext.findKey(keyValue) if keypathValue @bindSingleAttribute key, keyValue @setStyle key, keypathValue else @setStyle key, keyValue handleItemsWereAdded: (newKey) => @setStyle newKey, @collection.get(newKey); return handleItemsWereRemoved: (oldKey) => @setStyle oldKey, ''; return bindSingleAttribute: (attr, keyPath) -> new @constructor.SingleStyleBinding(@node, attr, keyPath, @renderContext, @renderer, @only, @) setStyle: (key, value) => return unless key key = PI:KEY:<KEY>END_PI(key.PI:KEY:<KEY>END_PI) @oldStyles[key] = @node.style[key] @node.style[key] = if value then value.trim() else "" reapplyOldStyles: -> @setStyle(cssName, cssValue) for own cssName, cssValue of @oldStyles class Batman.DOM.RouteBinding extends Batman.DOM.AbstractBinding onATag: false @accessor 'dispatcher', -> @renderContext.get('dispatcher') || Batman.App.get('current.dispatcher') bind: -> if @node.nodeName.toUpperCase() is 'A' @onATag = true super Batman.DOM.events.click @node, => params = @pathFromValue(@get('filteredValue')) Batman.redirect params if params? dataChange: (value) -> if value? path = @pathFromValue(value) if @onATag if path? path = Batman.navigator.linkTo path else path = "#" @node.href = path pathFromValue: (value) -> if value.isNamedRouteQuery value.get('path') else @get('dispatcher')?.pathFromParams(value) class Batman.DOM.ViewBinding extends Batman.DOM.AbstractBinding constructor: -> super @renderer.prevent 'rendered' @node.removeAttribute 'data-view' dataChange: (viewClassOrInstance) -> return unless viewClassOrInstance? if viewClassOrInstance.isView @view = viewClassOrInstance @view.set 'node', @node @view.set 'context', @renderContext else @view = new viewClassOrInstance node: @node context: @renderContext parentView: @renderContext.findKey('isView')?[1] Batman.data @node, 'view', @view @view.on 'ready', => @view.awakeFromHTML? @node @view.fire 'beforeAppear', @node @renderer.allowAndFire 'rendered' @view.fire 'appear', @node @die() class Batman.DOM.FormBinding extends Batman.DOM.AbstractAttributeBinding @current: null errorClass: 'error' defaultErrorsListSelector: 'div.errors' @accessor 'errorsListSelector', -> @get('node').getAttribute('data-errors-list') || @defaultErrorsListSelector constructor: (node, contextName, keyPath, renderContext, renderer, only) -> super @contextName = contextName delete @attributeName Batman.DOM.events.submit @get('node'), (node, e) -> $preventDefault e Batman.DOM.on 'bindingAdded', @bindingWasAdded @setupErrorsList() bindingWasAdded: (binding) => if binding.isInputBinding && $isChildOf(@get('node'), binding.get('node')) if ~(index = binding.get('key').indexOf(@contextName)) # If the binding is to a key on the thing passed to formfor node = binding.get('node') field = binding.get('key').slice(index + @contextName.length + 1) # Slice off up until the context and the following dot new Batman.DOM.AddClassBinding(node, @errorClass, @get('keyPath') + " | get 'errors.#{field}.length'", @renderContext, @renderer) setupErrorsList: -> if @errorsListNode = @get('node').querySelector?(@get('errorsListSelector')) $setInnerHTML @errorsListNode, @errorsListHTML() unless @errorsListNode.getAttribute 'data-showif' @errorsListNode.setAttribute 'data-showif', "#{@contextName}.errors.length" errorsListHTML: -> """ <ul> <li data-foreach-error="#{@contextName}.errors" data-bind="error.attribute | append ' ' | append error.message"></li> </ul> """ die: -> Batman.DOM.forget 'bindingAdded', @bindingWasAdded super class Batman.DOM.IteratorBinding extends Batman.DOM.AbstractCollectionBinding deferEvery: 50 currentActionNumber: 0 queuedActionNumber: 0 bindImmediately: false constructor: (sourceNode, @iteratorName, @key, @context, @parentRenderer) -> @nodeMap = new Batman.SimpleHash @actionMap = new Batman.SimpleHash @rendererMap = new Batman.SimpleHash @actions = [] @prototypeNode = sourceNode.cloneNode(true) @prototypeNode.removeAttribute "data-foreach-#{@iteratorName}" @pNode = sourceNode.parentNode previousSiblingNode = sourceNode.nextSibling @siblingNode = document.createComment "end #{@iteratorName}" @siblingNode[Batman.expando] = sourceNode[Batman.expando] delete sourceNode[Batman.expando] if Batman.canDeleteExpando $insertBefore sourceNode.parentNode, @siblingNode, previousSiblingNode # Remove the original node once the parent has moved past it. @parentRenderer.on 'parsed', => # Move any Batman._data from the sourceNode to the sibling; we need to # retain the bindings, and we want to dispose of the node. $removeNode sourceNode # Attach observers. @bind() # Don't let the parent emit its rendered event until all the children have. # This `prevent`'s matching allow is run once the queue is empty in `processActionQueue`. @parentRenderer.prevent 'rendered' # Tie this binding to a node using the default behaviour in the AbstractBinding super(@siblingNode, @iteratorName, @key, @context, @parentRenderer) @fragment = document.createDocumentFragment() parentNode: -> @siblingNode.parentNode die: -> super @dead = true unbindCollection: -> if @collection @nodeMap.forEach (item) => @cancelExistingItem(item) super dataChange: (newCollection) -> if @collection != newCollection @removeAll() @bindCollection(newCollection) # Unbinds the old collection as well. if @collection if @collection.toArray @handleArrayChanged() else if @collection.forEach @collection.forEach (item) => @addOrInsertItem(item) else @addOrInsertItem(key) for own key, value of @collection else developer.warn "Warning! data-foreach-#{@iteratorName} called with an undefined binding. Key was: #{@key}." @processActionQueue() handleItemsWereAdded: (items...) => @addOrInsertItem(item, {fragment: false}) for item in items; return handleItemsWereRemoved: (items...) => @removeItem(item) for item in items; return handleArrayChanged: => newItemsInOrder = @collection.toArray() nodesToRemove = (new Batman.SimpleHash).merge(@nodeMap) for item in newItemsInOrder @addOrInsertItem(item, {fragment: false}) nodesToRemove.unset(item) nodesToRemove.forEach (item, node) => @removeItem(item) addOrInsertItem: (item, options = {}) -> existingNode = @nodeMap.get(item) if existingNode @insertItem(item, existingNode) else @addItem(item, options) addItem: (item, options = {fragment: true}) -> @parentRenderer.prevent 'rendered' # Remove any renderers in progress or actions lined up for an item, since we now know # this item belongs at the end of the queue. @cancelExistingItemActions(item) if @actionMap.get(item)? self = @ options.actionNumber = @queuedActionNumber++ # Render out the child in the custom context, and insert it once the render has completed the parse. childRenderer = new Batman.Renderer @_nodeForItem(item), (-> self.rendererMap.unset(item) self.insertItem(item, @node, options) ), @renderContext.descend(item, @iteratorName) @rendererMap.set(item, childRenderer) finish = => return if @dead @parentRenderer.allowAndFire 'rendered' childRenderer.on 'rendered', finish childRenderer.on 'stopped', => return if @dead @actions[options.actionNumber] = false finish() @processActionQueue() item removeItem: (item) -> return if @dead || !item? oldNode = @nodeMap.unset(item) @cancelExistingItem(item) if oldNode if hideFunction = Batman.data oldNode, 'hide' hideFunction.call(oldNode) else $removeNode(oldNode) removeAll: -> @nodeMap.forEach (item) => @removeItem(item) insertItem: (item, node, options = {}) -> return if @dead if !options.actionNumber? options.actionNumber = @queuedActionNumber++ existingActionNumber = @actionMap.get(item) if existingActionNumber > options.actionNumber # Another action for this item is scheduled for the future, do it then instead of now. Actions # added later enforce order, so we make this one a noop and let the later one have its proper effects. @actions[options.actionNumber] = -> else # Another action has been scheduled for this item. It hasn't been done yet because # its in the actionmap, but this insert is scheduled to happen after it. Skip it since its now defunct. if existingActionNumber @cancelExistingItemActions(item) # Update the action number map to now reflect this new action which will go on the end of the queue. @actionMap.set item, options.actionNumber @actions[options.actionNumber] = -> show = Batman.data node, 'show' if typeof show is 'function' show.call node, before: @siblingNode else if options.fragment @fragment.appendChild node else $insertBefore @parentNode(), node, @siblingNode if addItem = node.getAttribute 'data-additem' [_, context] = @renderer.context.findKey addItem context?[addItem]?(item, node) @actions[options.actionNumber].item = item @processActionQueue() cancelExistingItem: (item) -> @cancelExistingItemActions(item) @cancelExistingItemRender(item) cancelExistingItemActions: (item) -> oldActionNumber = @actionMap.get(item) # Only remove actions which haven't been completed yet. if oldActionNumber? && oldActionNumber >= @currentActionNumber @actions[oldActionNumber] = false @actionMap.unset item cancelExistingItemRender: (item) -> oldRenderer = @rendererMap.get(item) if oldRenderer oldRenderer.stop() $removeNode(oldRenderer.node) @rendererMap.unset item processActionQueue: -> return if @dead unless @actionQueueTimeout # Prevent the parent which will then be allowed when the timeout actually runs @actionQueueTimeout = $setImmediate => return if @dead delete @actionQueueTimeout startTime = new Date while (f = @actions[@currentActionNumber])? delete @actions[@currentActionNumber] @actionMap.unset f.item f.call(@) if f @currentActionNumber++ if @deferEvery && (new Date - startTime) > @deferEvery return @processActionQueue() if @fragment && @rendererMap.length is 0 && @fragment.hasChildNodes() $insertBefore @parentNode(), @fragment, @siblingNode @fragment = document.createDocumentFragment() if @currentActionNumber == @queuedActionNumber @parentRenderer.allowAndFire 'rendered' _nodeForItem: (item) -> newNode = @prototypeNode.cloneNode(true) @nodeMap.set(item, newNode) newNode # Filters # ------- # # `Batman.Filters` contains the simple, determininistic tranforms used in view bindings to # make life a little easier. buntUndefined = (f) -> (value) -> if typeof value is 'undefined' undefined else f.apply(@, arguments) filters = Batman.Filters = raw: buntUndefined (value, binding) -> binding.escapeValue = false value get: buntUndefined (value, key) -> if value.get? value.get(key) else value[key] equals: buntUndefined (lhs, rhs, binding) -> lhs is rhs not: (value, binding) -> ! !!value matches: buntUndefined (value, searchFor) -> value.indexOf(searchFor) isnt -1 truncate: buntUndefined (value, length, end = "...", binding) -> if !binding binding = end end = "..." if value.length > length value = value.substr(0, length-end.length) + end value default: (value, string, binding) -> value || string prepend: (value, string, binding) -> string + value append: (value, string, binding) -> value + string replace: buntUndefined (value, searchFor, replaceWith, flags, binding) -> if !binding binding = flags flags = undefined # Work around FF issue, "foo".replace("foo","bar",undefined) throws an error if flags is undefined value.replace searchFor, replaceWith else value.replace searchFor, replaceWith, flags downcase: buntUndefined (value) -> value.toLowerCase() upcase: buntUndefined (value) -> value.toUpperCase() pluralize: buntUndefined (string, count) -> helpers.pluralize(count, string) join: buntUndefined (value, withWhat = '', binding) -> if !binding binding = withWhat withWhat = '' value.join(withWhat) sort: buntUndefined (value) -> value.sort() map: buntUndefined (value, key) -> value.map((x) -> $get(x, key)) has: (set, item) -> return false unless set? Batman.contains(set, item) first: buntUndefined (value) -> value[0] meta: buntUndefined (value, keypath) -> developer.assert value.meta, "Error, value doesn't have a meta to filter on!" value.meta.get(keypath) interpolate: (string, interpolationKeypaths, binding) -> if not binding binding = interpolationKeypaths interpolationKeypaths = undefined return if not string values = {} for k, v of interpolationKeypaths values[k] = @findKey(v)[0] if !values[k]? Batman.developer.warn "Warning! Undefined interpolation key #{k} for interpolation", string values[k] = '' Batman.helpers.interpolate(string, values) # allows you to curry arguments to a function via a filter withArguments: (block, curryArgs..., binding) -> return if not block return (regularArgs...) -> block.call @, curryArgs..., regularArgs... routeToAction: buntUndefined (model, action) -> params = Batman.Dispatcher.paramsFromArgument(model) params.action = action params escape: buntUndefined($escapeHTML) for k in ['capitalize', 'singularize', 'underscore', 'camelize'] filters[k] = buntUndefined helpers[k] developer.addFilters() # Data # ---- $mixin Batman, cache: {} uuid: 0 expando: "batman" + Math.random().toString().replace(/\D/g, '') # Test to see if it's possible to delete an expando from an element # Fails in Internet Explorer canDeleteExpando: try div = document.createElement 'div' delete div.test catch e Batman.canDeleteExpando = false noData: # these throw exceptions if you attempt to add expandos to them "embed": true, # Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true hasData: (elem) -> elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando]) !!elem and !isEmptyDataObject(elem) data: (elem, name, data, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando getByName = typeof name == "string" cache = Batman.cache # Only defining an ID for JS objects if its cache already exists allows # the code to shortcut on the same path as a DOM node with no cache id = elem[Batman.expando] # Avoid doing any more work than we need to when trying to get data on an # object that has no data at all if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined return unless id # Also check that it's not a text node; IE can't set expandos on them if elem.nodeType isnt 3 elem[Batman.expando] = id = ++Batman.uuid else id = Batman.expando cache[id] = {} unless cache[id] # An object can be passed to Batman._data instead of a key/value pair; this gets # shallow copied over onto the existing cache if typeof name == "object" or typeof name == "function" if pvt cache[id][internalKey] = $mixin(cache[id][internalKey], name) else cache[id] = $mixin(cache[id], name) thisCache = cache[id] # Internal Batman data is stored in a separate object inside the object's data # cache in order to avoid key collisions between internal data and user-defined # data if pvt thisCache[internalKey] ||= {} thisCache = thisCache[internalKey] if data != undefined thisCache[name] = data # Check for both converted-to-camel and non-converted data property names # If a data property was specified if getByName # First try to find as-is property data ret = thisCache[name] else ret = thisCache return ret removeData: (elem, name, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando isNode = elem.nodeType # non DOM-nodes have their data attached directly cache = Batman.cache id = elem[Batman.expando] # If there is already no cache entry for this object, there is no # purpose in continuing return unless cache[id] if name thisCache = if pvt then cache[id][internalKey] else cache[id] if thisCache # Support interoperable removal of hyphenated or camelcased keys delete thisCache[name] # If there is no data left in the cache, we want to continue # and let the cache object itself get destroyed return unless isEmptyDataObject(thisCache) if pvt delete cache[id][internalKey] # Don't destroy the parent cache unless the internal data object # had been the only thing left in it return unless isEmptyDataObject(cache[id]) internalCache = cache[id][internalKey] # Browsers that fail expando deletion also refuse to delete expandos on # the window, but it will allow it on all other JS objects; other browsers # don't care # Ensure that `cache` is not a window object if Batman.canDeleteExpando or !cache.setInterval delete cache[id] else cache[id] = null # We destroyed the entire user cache at once because it's faster than # iterating through each key, but we need to continue to persist internal # data if it existed if internalCache cache[id] = {} cache[id][internalKey] = internalCache # Otherwise, we need to eliminate the expando on the node to avoid # false lookups in the cache for entries that no longer exist else if Batman.canDeleteExpando delete elem[Batman.expando] else if elem.removeAttribute elem.removeAttribute Batman.expando else elem[Batman.expando] = null # For internal use only _data: (elem, name, data) -> Batman.data elem, name, data, true # A method for determining if a DOM node can handle the data expando acceptData: (elem) -> if elem.nodeName match = Batman.noData[elem.nodeName.toLowerCase()] if match return !(match == true or elem.getAttribute("classid") != match) return true isEmptyDataObject = (obj) -> for name of obj return false return true # Mixins # ------ mixins = Batman.mixins = new Batman.Object() # Encoders # ------ Batman.Encoders = {} class Batman.Paginator extends Batman.Object class @Range constructor: (@offset, @limit) -> @reach = offset + limit coversOffsetAndLimit: (offset, limit) -> offset >= @offset and (offset + limit) <= @reach class @Cache extends @Range constructor: (@offset, @limit, @items) -> super @length = items.length itemsForOffsetAndLimit: (offset, limit) -> begin = offset-@offset end = begin + limit if begin < 0 padding = new Array(-begin) begin = 0 slice = @items.slice(begin, end) if padding padding.concat(slice) else slice offset: 0 limit: 10 totalCount: 0 markAsLoadingOffsetAndLimit: (offset, limit) -> @loadingRange = new Batman.Paginator.Range(offset, limit) markAsFinishedLoading: -> delete @loadingRange offsetFromPageAndLimit: (page, limit) -> Math.round((+page - 1) * limit) pageFromOffsetAndLimit: (offset, limit) -> offset / limit + 1 _load: (offset, limit) -> return if @loadingRange?.coversOffsetAndLimit(offset, limit) @markAsLoadingOffsetAndLimit(offset, limit) @loadItemsForOffsetAndLimit(offset, limit) toArray: -> cache = @get('cache') offset = @get('offset') limit = @get('limit') @_load(offset, limit) unless cache?.coversOffsetAndLimit(offset, limit) cache?.itemsForOffsetAndLimit(offset, limit) or [] page: -> @pageFromOffsetAndLimit(@get('offset'), @get('limit')) pageCount: -> Math.ceil(@get('totalCount') / @get('limit')) previousPage: -> @set('page', @get('page')-1) nextPage: -> @set('page', @get('page')+1) loadItemsForOffsetAndLimit: (offset, limit) -> # override on subclasses or instances updateCache: (offset, limit, items) -> cache = new Batman.Paginator.Cache(offset, limit, items) return if @loadingRange? and not cache.coversOffsetAndLimit(@loadingRange.offset, @loadingRange.limit) @markAsFinishedLoading() @set('cache', cache) @accessor 'toArray', @::toArray @accessor 'offset', 'limit', 'totalCount' get: Batman.Property.defaultAccessor.get set: (key, value) -> Batman.Property.defaultAccessor.set.call(this, key, +value) @accessor 'page', get: @::page set: (_,value) -> value = +value @set('offset', @offsetFromPageAndLimit(value, @get('limit'))) value @accessor 'pageCount', @::pageCount class Batman.ModelPaginator extends Batman.Paginator cachePadding: 0 paddedOffset: (offset) -> offset -= @cachePadding if offset < 0 then 0 else offset paddedLimit: (limit) -> limit + @cachePadding * 2 loadItemsForOffsetAndLimit: (offset, limit) -> params = @paramsForOffsetAndLimit(offset, limit) params[k] = v for k,v of @params @model.load params, (err, records) => if err? @markAsFinishedLoading() @fire('error', err) else @updateCache(@offsetFromParams(params), @limitFromParams(params), records) # override these to fetch records however you like: paramsForOffsetAndLimit: (offset, limit) -> offset: @paddedOffset(offset), limit: @paddedLimit(limit) offsetFromParams: (params) -> params.offset limitFromParams: (params) -> params.limit # Support AMD loaders if typeof define is 'function' define 'batman', [], -> Batman # Optionally export global sugar. Not sure what to do with this. Batman.exportHelpers = (onto) -> for k in ['mixin', 'unmixin', 'route', 'redirect', 'typeOf', 'redirect', 'setImmediate'] onto["$#{k}"] = Batman[k] onto Batman.exportGlobals = () -> Batman.exportHelpers(Batman.container)
[ { "context": "app.coffee\n# lotto-ionic\n# v0.0.2\n# Copyright 2016 Andreja Tonevski, https://github.com/atonevski/lotto-ionic\n# For l", "end": 71, "score": 0.9998804926872253, "start": 55, "tag": "NAME", "value": "Andreja Tonevski" }, { "context": "pyright 2016 Andreja Tonevski, https://github.com/atonevski/lotto-ionic\n# For license information see LICENSE", "end": 101, "score": 0.9997183084487915, "start": 92, "tag": "USERNAME", "value": "atonevski" } ]
www/coffee/app.coffee
atonevski/lotto-ionic
0
# # app.coffee # lotto-ionic # v0.0.2 # Copyright 2016 Andreja Tonevski, https://github.com/atonevski/lotto-ionic # For license information see LICENSE in the repository # # Ionic Starter App # angular.module is a global place for creating, registering and retrieving Angular modules # 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) # the 2nd parameter is an array of 'requires' angular.module 'app', ['ionic', 'ngCordova', 'app.util', 'app.upload', 'app.annual', 'app.weekly', 'app.stats', 'app.winners', 'app.drawn.numbers'] .config ($stateProvider, $urlRouterProvider) -> $stateProvider.state 'home', { url: '/home' templateUrl: 'views/home/home.html' } .state 'root', { url: '/' templateUrl: 'views/home/home.html' } .state 'annual', { url: '/annual' templateUrl: 'views/annual/annual.html' controller: 'Annual' } .state 'weekly', { url: '/weekly/:year' templateUrl: 'views/weekly/weekly.html' controller: 'Weekly' } .state 'stats', { url: '/stats' templateUrl: 'views/stats/home.html' } .state 'lotto-stats', { url: '/stats/lotto' templateUrl: 'views/stats/lfreqs.html' controller: 'LottoStats' } .state 'joker-stats', { url: '/stats/joker' templateUrl: 'views/stats/jfreqs.html' controller: 'JokerStats' } .state 'winners-stats', { url: '/stats/winners' templateUrl: 'views/stats/winners.html' controller: 'WinnersStats' } .state 'upload', { url: '/upload' templateUrl: 'views/upload/upload.html' controller: 'Upload' } .state 'winners', { url: '/winners' templateUrl: 'views/winners/winners.html' # controller: 'Winners' } .state 'lotto-winners', { url: '/winners/lotto' templateUrl: 'views/winners/lotto.html' controller: 'LottoWinners' } .state 'joker-winners', { url: '/winners/joker' templateUrl: 'views/winners/joker.html' controller: 'JokerWinners' } .state 'lotto-drawn-numbers', { url: '/drawn-numbers/lotto' templateUrl: 'views/drawn-numbers/lotto.html' controller: 'LottoDrawnNumbers' } .state 'about', { url: '/about' templateUrl: 'views/about/about.html' controller: 'About' } $urlRouterProvider.otherwise '/home' .run ($ionicPlatform, $cordovaAppVersion, $rootScope) -> $ionicPlatform.ready () -> if window.cordova && window.cordova.plugins.Keyboard # Hide the accessory bar by default (remove this to # show the accessory bar above the keyboard # for form inputs)g cordova.plugins.Keyboard.hideKeyboardAccessoryBar true # Don't remove this line unless you know what you are doing. It stops the viewport # from snapping when text inputs are focused. Ionic handles this internally for # a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll true if window.StatusBar StatusBar.styleDefault() # check internet connection # Cordova Connection available options # Value Description # Connection.UNKNOWN Unknown connection # Connection.ETHERNET Ethernet connection # Connection.WIFI WiFi connection # Connection.CELL_2G Cell 2G connection # Connection.CELL_3G Cell 3G connection # Connection.CELL_4G Cell 4G connection # Connection.NONE No network connection # # add cordova plugin: # cordova plugin add cordova-plugin-network-information # if navigator.connection # if navigator.connection.type == Connection.NONE # $ionicPopup.confirm { # title: "Интернет" # content: "Интернет е недостапен на уредот." # } # .then (result) -> # ionic.Platform.exitApp() unless result .controller 'Main', ($scope, $rootScope, $http, util, $cordovaAppVersion, $cordovaNetwork, $ionicPopup) -> ionic.Platform.ready () -> if $cordovaNetwork.getNetwork() == Connection.NONE $ionicPopup.confirm { title: 'Интернет' content: 'Интернет е недостапен на уредот.' cancelText: 'Откажи' cancelType: 'button-assertive' okText: 'Продолжи' okType: 'button-positive' } .then (result) -> ionic.Platform.exitApp() unless result if window.cordova $cordovaAppVersion.getVersionNumber().then (ver) -> $scope.appVersion = ver $cordovaAppVersion.getAppName().then (name) -> $scope.appName = name to_json = (d) -> # convert google query response to json re = /^([^(]+?\()(.*)\);$/g match = re.exec d JSON.parse match[2] # some global vars, and functions # NOTE: # This should be done through object merging $scope.uploadNeeded = no $scope.to_json = to_json # $scope.thou_sep = util.thou_sep # export to all child conotrollers # $scope.GS_KEY = util.GS_KEY # $scope.GS_URL = util.GS_URL # $scope.RES_RE = util.RES_RE # $scope.eval_row = util.eval_row # $scope.yesterday = util.yesterday # $scope.nextDraw = util.nextDraw # $scope.dateToDMY = util.dateToDMY # we can't use util.merge, so we do it # manually for k, v of util $scope[k] = v # get last year $scope.qurl = (q) -> "#{ $scope.GS_URL }tq?tqx=out:json&key=#{ $scope.GS_KEY }" + "&tq=#{ encodeURI q }" query = 'SELECT YEAR(B) ORDER BY YEAR(B) DESC LIMIT 1' $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.lastYear = ($scope.eval_row res.table.rows[0])[0] # device width/height $scope.width = window.innerWidth $scope.height = window.innerHeight console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }" # check for upload $scope.checkUpload = () -> unless $scope.lastDraw? # $scope.uploadNeeded = no # since we can't know $scope.uploadNeeded = no # since we can't know return no nextd = $scope.nextDraw $scope.lastDraw $scope.uploadNeeded = (nextd.date <= $scope.yesterday()) # we watch on lastDraw $rootScope.$watch 'lastDraw', (n, o) -> # old and new values if n if $rootScope.uploadNeeded? $scope.uploadNeeded = $rootScope.uploadNeeded else $scope.checkUpload() # get last draw number & date q = 'SELECT A, B ORDER BY B DESC LIMIT 1' $http.get $scope.qurl(q) .success (data, status) -> res = $scope.to_json data r = $scope.eval_row res.table.rows[0] $scope.lastDraw = draw: r[0] date: new Date r[1] $rootScope.lastDraw = draw: r[0] date: new Date r[1] $scope.checkUpload() .directive 'barChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.barChart.title = attrs.title if attrs.title? scope.barChart.width = parseInt(attrs.width) if attrs.width? scope.barChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 15, right: 10, bottom: 40, left: 60 } svg = d3.select el[0] .append 'svg' .attr 'width', scope.barChart.width + margin.left + margin.right .attr 'height', scope.barChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" y = d3.scale.linear().rangeRound [scope.barChart.height, 0] yAxis = d3.svg.axis().scale(y) .tickFormat (d) -> Math.round(d/10000)/100 + " M" .orient 'left' x = d3.scale.ordinal().rangeRoundBands [0, scope.barChart.width], 0.1 xAxis = d3.svg.axis().scale(x).orient 'bottom' y.domain [0, d3.max(scope.barChart.data)] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis x.domain scope.barChart.labels svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.barChart.height})" .call xAxis svg.append 'text' .attr 'x', x(scope.barChart.labels[Math.floor scope.barChart.labels.length/2]) .attr 'y', y(20 + d3.max(scope.barChart.data)) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'bar-chart-title' .text scope.barChart.title r = svg.selectAll '.bar' .data scope.barChart.data.map (d) -> Math.floor Math.random()*d .enter().append 'rect' .attr 'class', 'bar' .attr 'x', (d, i) -> x(scope.barChart.labels[i]) .attr 'y', (d) -> y(d) .attr 'height', (d) -> scope.barChart.height - y(d) .attr 'width', x.rangeBand() .attr 'title', (d, i) -> scope.thou_sep(scope.barChart.data[i]) r.transition().duration 1000 .ease 'elastic' .attr 'y', (d, i) -> y(scope.barChart.data[i]) .attr 'height', (d, i) -> scope.barChart.height - y(scope.barChart.data[i]) } .directive 'stackedBarChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.sbarChart.title = attrs.title if attrs.title? scope.sbarChart.width = parseInt(attrs.width) if attrs.width? scope.sbarChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 35, right: 120, bottom: 30, left: 40 } tooltip = d3.select el[0] .append 'div' .attr 'class', 'tooltip' .style 'opacity', 0 svg = d3.select el[0] .append 'svg' .attr 'width', scope.sbarChart.width + margin.left + margin.right .attr 'height', scope.sbarChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" lab = scope.sbarChart.labels remapped = scope.sbarChart.categories.map (cat) -> scope.sbarChart.data.map (d, i) -> { x: d[lab], y: d[cat], cat: cat } stacked = d3.layout.stack()(remapped) y = d3.scale.linear().rangeRound [scope.sbarChart.height, 0] yAxis = d3.svg.axis().scale(y) .tickFormat((d) -> if d > 100000.0 Math.round(d/10000)/100 + " M" else scope.thou_sep d ) .orient 'left' x = d3.scale.ordinal().rangeRoundBands [0, scope.sbarChart.width], 0.3, 0.2 xAxis = d3.svg.axis().scale(x).orient 'bottom' xAxis.tickValues scope.sbarChart.labVals if scope.sbarChart.labVals? x.domain stacked[0].map (d) -> d.x svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.sbarChart.height})" .call xAxis y.domain [0, d3.max(stacked[-1..][0], (d) -> return d.y0 + d.y)] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis .selectAll('line') .style "stroke-dasharray", "3, 3" color = d3.scale.category20() svg.append 'text' .attr 'x', x(stacked[0][Math.floor stacked[0].length/2].x) .attr 'y', y(20 + d3.max(stacked[-1..][0], ((d) -> d.y0 + d.y))) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'bar-chart-title' .text scope.sbarChart.title g = svg.selectAll 'g.vgroup' .data stacked .enter() .append 'g' .attr 'class', 'vgroup' .style 'fill', (d, i) -> d3.rgb(color(i)).brighter(1.2) .style 'stroke', (d, i) -> d3.rgb(color(i)).darker() r = g.selectAll 'rect' .data (d) -> d .enter() .append 'rect' .attr 'id', (d) -> "#{ d.cat }-#{ d.x }" .attr 'x', (d) -> x(d.x) .attr 'y', (d) -> y(d.y + d.y0) .attr 'height', (d) -> y(d.y0) - y(d.y + d.y0) .attr 'width', x.rangeBand() .on('click', (d, i) -> # d3.select "\##{ d.cat }-#{ d.x }" # .style 'opacity', 0.85 # .transition().duration(1500).ease 'exp' # .style 'opacity', 1 t = """ <p style='text-align: center;'> <b>#{ d.cat }/#{ d.x }</b> <hr /></p> <p style='text-align: center'> #{ scope.thou_sep(d.y) } </p> """ tooltip.html '' tooltip.transition().duration 1000 .style 'opacity', 0.75 tooltip.html t .style 'left', (d3.event.pageX + 10) + 'px' .style 'top', (d3.event.pageY - 75) + 'px' .style 'opacity', 1 tooltip.transition().duration 5000 .style 'opacity', 0 ) .append 'title' .html (d) -> "<strong>#{ d.cat }/#{ d.x }</strong>: #{ scope.thou_sep(d.y) }" legend = svg.append('g').attr 'class', 'legend' legend.selectAll '.legend-rect' .data scope.sbarChart.categories .enter() .append 'rect' .attr 'class', '.legend-rect' .attr('width', 16) .attr 'height', 16 .attr 'x', scope.sbarChart.width + 2 .attr 'y', (d, i) -> 20*i .style 'stroke', (d, i) -> d3.rgb(color(i)).darker() .style 'fill', (d, i) -> d3.rgb(color(i)).brighter(1.2) legend.selectAll 'text' .data scope.sbarChart.categories .enter() .append 'text' .attr 'class', 'legend' .attr 'x', scope.sbarChart.width + 24 .attr 'y', (d, i) -> 20*i + 8 .attr 'dy', 4 .text (d) -> d } .directive 'lineChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.lineChart.title = attrs.title if attrs.title? scope.lineChart.width = parseInt(attrs.width) if attrs.width? scope.lineChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 35, right: 120, bottom: 30, left: 40 } tooltip = d3.select el[0] .append 'div' .attr 'class', 'tooltip' .style 'opacity', 0 svg = d3.select el[0] .append 'svg' .attr 'width', scope.lineChart.width + margin.left + margin.right .attr 'height', scope.lineChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" y = d3.scale.linear().rangeRound [scope.lineChart.height, 0] yAxis = d3.svg.axis() .scale(y) .orient 'left' ymax = d3.max scope.series.map (s) -> d3.max(s.data.map (d) -> d.y) y.domain [0, d3.max scope.series.map (s) -> d3.max(s.data.map (d) -> d.y) ] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis x = d3.time.scale().range [0, scope.lineChart.width] xAxis = d3.svg.axis().scale(x) .orient 'bottom' .tickFormat d3.time.format("%W") x.domain [ d3.min(scope.series.map((s) -> s.data[0].x)), d3.max(scope.series.map((s) -> s.data[-1..][0].x)), ] svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.lineChart.height})" .call xAxis svg.append 'text' .attr 'x', scope.lineChart.width/2 .attr 'y', y(20 + ymax) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'line-chart-title' .text scope.lineChart.title line = d3.svg.line() .interpolate("monotone") .x (d) -> x(d.x) .y (d) -> y(d.y) win = [] for i, s of scope.series svg.append 'path' .datum s.data .attr 'class', 'line' .attr 'stroke', d3.scale.category10().range()[i] .attr 'd', line win[i] = s.data.filter (d) ->d.lx7 > 0 for i, w of win for ww in w d = [ { x: ww.x, y: 0, draw: ww.draw }, ww ] svg.append 'path' .datum d .attr 'id', "draw-#{ ww.draw }" .attr 'class', 'line' # .attr 'stroke-dasharray', "3, 3" .attr 'stroke', d3.scale.category10().range()[i] .attr 'stroke-dasharray', '0.8 1.6' .on 'click', (d, i) -> t = """ <p style='text-align: center;'> <b>коло: #{ d[1].draw }</b><br /> </p> """ tooltip.html t tooltip.transition().duration 1000 .style 'opacity', 0.75 tooltip.html t .style 'left', (d3.event.pageX) + 'px' .style 'top', (d3.event.pageY-60) + 'px' .style 'opacity', 1 tooltip.transition().duration 5000 .style 'opacity', 0 .attr 'd', line .append 'title' .html (d, i) -> "<strong>коло: #{ d[1].draw }</strong>" # hints for x7, 1st prize winners legend = svg.append('g').attr 'class', 'legend' legend.selectAll 'text' .data scope.series.map (s) -> s.name .enter() .append 'text' .attr 'class', 'legend' .attr 'x', scope.lineChart.width + 4 .attr 'y', (d, i) -> 20*i + 8 .attr 'dy', 4 .style 'fill', (d, i) ->d3.rgb(d3.scale.category10().range()[i]).darker(0.5) .text (d) -> d }
20369
# # app.coffee # lotto-ionic # v0.0.2 # Copyright 2016 <NAME>, https://github.com/atonevski/lotto-ionic # For license information see LICENSE in the repository # # Ionic Starter App # angular.module is a global place for creating, registering and retrieving Angular modules # 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) # the 2nd parameter is an array of 'requires' angular.module 'app', ['ionic', 'ngCordova', 'app.util', 'app.upload', 'app.annual', 'app.weekly', 'app.stats', 'app.winners', 'app.drawn.numbers'] .config ($stateProvider, $urlRouterProvider) -> $stateProvider.state 'home', { url: '/home' templateUrl: 'views/home/home.html' } .state 'root', { url: '/' templateUrl: 'views/home/home.html' } .state 'annual', { url: '/annual' templateUrl: 'views/annual/annual.html' controller: 'Annual' } .state 'weekly', { url: '/weekly/:year' templateUrl: 'views/weekly/weekly.html' controller: 'Weekly' } .state 'stats', { url: '/stats' templateUrl: 'views/stats/home.html' } .state 'lotto-stats', { url: '/stats/lotto' templateUrl: 'views/stats/lfreqs.html' controller: 'LottoStats' } .state 'joker-stats', { url: '/stats/joker' templateUrl: 'views/stats/jfreqs.html' controller: 'JokerStats' } .state 'winners-stats', { url: '/stats/winners' templateUrl: 'views/stats/winners.html' controller: 'WinnersStats' } .state 'upload', { url: '/upload' templateUrl: 'views/upload/upload.html' controller: 'Upload' } .state 'winners', { url: '/winners' templateUrl: 'views/winners/winners.html' # controller: 'Winners' } .state 'lotto-winners', { url: '/winners/lotto' templateUrl: 'views/winners/lotto.html' controller: 'LottoWinners' } .state 'joker-winners', { url: '/winners/joker' templateUrl: 'views/winners/joker.html' controller: 'JokerWinners' } .state 'lotto-drawn-numbers', { url: '/drawn-numbers/lotto' templateUrl: 'views/drawn-numbers/lotto.html' controller: 'LottoDrawnNumbers' } .state 'about', { url: '/about' templateUrl: 'views/about/about.html' controller: 'About' } $urlRouterProvider.otherwise '/home' .run ($ionicPlatform, $cordovaAppVersion, $rootScope) -> $ionicPlatform.ready () -> if window.cordova && window.cordova.plugins.Keyboard # Hide the accessory bar by default (remove this to # show the accessory bar above the keyboard # for form inputs)g cordova.plugins.Keyboard.hideKeyboardAccessoryBar true # Don't remove this line unless you know what you are doing. It stops the viewport # from snapping when text inputs are focused. Ionic handles this internally for # a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll true if window.StatusBar StatusBar.styleDefault() # check internet connection # Cordova Connection available options # Value Description # Connection.UNKNOWN Unknown connection # Connection.ETHERNET Ethernet connection # Connection.WIFI WiFi connection # Connection.CELL_2G Cell 2G connection # Connection.CELL_3G Cell 3G connection # Connection.CELL_4G Cell 4G connection # Connection.NONE No network connection # # add cordova plugin: # cordova plugin add cordova-plugin-network-information # if navigator.connection # if navigator.connection.type == Connection.NONE # $ionicPopup.confirm { # title: "Интернет" # content: "Интернет е недостапен на уредот." # } # .then (result) -> # ionic.Platform.exitApp() unless result .controller 'Main', ($scope, $rootScope, $http, util, $cordovaAppVersion, $cordovaNetwork, $ionicPopup) -> ionic.Platform.ready () -> if $cordovaNetwork.getNetwork() == Connection.NONE $ionicPopup.confirm { title: 'Интернет' content: 'Интернет е недостапен на уредот.' cancelText: 'Откажи' cancelType: 'button-assertive' okText: 'Продолжи' okType: 'button-positive' } .then (result) -> ionic.Platform.exitApp() unless result if window.cordova $cordovaAppVersion.getVersionNumber().then (ver) -> $scope.appVersion = ver $cordovaAppVersion.getAppName().then (name) -> $scope.appName = name to_json = (d) -> # convert google query response to json re = /^([^(]+?\()(.*)\);$/g match = re.exec d JSON.parse match[2] # some global vars, and functions # NOTE: # This should be done through object merging $scope.uploadNeeded = no $scope.to_json = to_json # $scope.thou_sep = util.thou_sep # export to all child conotrollers # $scope.GS_KEY = util.GS_KEY # $scope.GS_URL = util.GS_URL # $scope.RES_RE = util.RES_RE # $scope.eval_row = util.eval_row # $scope.yesterday = util.yesterday # $scope.nextDraw = util.nextDraw # $scope.dateToDMY = util.dateToDMY # we can't use util.merge, so we do it # manually for k, v of util $scope[k] = v # get last year $scope.qurl = (q) -> "#{ $scope.GS_URL }tq?tqx=out:json&key=#{ $scope.GS_KEY }" + "&tq=#{ encodeURI q }" query = 'SELECT YEAR(B) ORDER BY YEAR(B) DESC LIMIT 1' $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.lastYear = ($scope.eval_row res.table.rows[0])[0] # device width/height $scope.width = window.innerWidth $scope.height = window.innerHeight console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }" # check for upload $scope.checkUpload = () -> unless $scope.lastDraw? # $scope.uploadNeeded = no # since we can't know $scope.uploadNeeded = no # since we can't know return no nextd = $scope.nextDraw $scope.lastDraw $scope.uploadNeeded = (nextd.date <= $scope.yesterday()) # we watch on lastDraw $rootScope.$watch 'lastDraw', (n, o) -> # old and new values if n if $rootScope.uploadNeeded? $scope.uploadNeeded = $rootScope.uploadNeeded else $scope.checkUpload() # get last draw number & date q = 'SELECT A, B ORDER BY B DESC LIMIT 1' $http.get $scope.qurl(q) .success (data, status) -> res = $scope.to_json data r = $scope.eval_row res.table.rows[0] $scope.lastDraw = draw: r[0] date: new Date r[1] $rootScope.lastDraw = draw: r[0] date: new Date r[1] $scope.checkUpload() .directive 'barChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.barChart.title = attrs.title if attrs.title? scope.barChart.width = parseInt(attrs.width) if attrs.width? scope.barChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 15, right: 10, bottom: 40, left: 60 } svg = d3.select el[0] .append 'svg' .attr 'width', scope.barChart.width + margin.left + margin.right .attr 'height', scope.barChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" y = d3.scale.linear().rangeRound [scope.barChart.height, 0] yAxis = d3.svg.axis().scale(y) .tickFormat (d) -> Math.round(d/10000)/100 + " M" .orient 'left' x = d3.scale.ordinal().rangeRoundBands [0, scope.barChart.width], 0.1 xAxis = d3.svg.axis().scale(x).orient 'bottom' y.domain [0, d3.max(scope.barChart.data)] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis x.domain scope.barChart.labels svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.barChart.height})" .call xAxis svg.append 'text' .attr 'x', x(scope.barChart.labels[Math.floor scope.barChart.labels.length/2]) .attr 'y', y(20 + d3.max(scope.barChart.data)) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'bar-chart-title' .text scope.barChart.title r = svg.selectAll '.bar' .data scope.barChart.data.map (d) -> Math.floor Math.random()*d .enter().append 'rect' .attr 'class', 'bar' .attr 'x', (d, i) -> x(scope.barChart.labels[i]) .attr 'y', (d) -> y(d) .attr 'height', (d) -> scope.barChart.height - y(d) .attr 'width', x.rangeBand() .attr 'title', (d, i) -> scope.thou_sep(scope.barChart.data[i]) r.transition().duration 1000 .ease 'elastic' .attr 'y', (d, i) -> y(scope.barChart.data[i]) .attr 'height', (d, i) -> scope.barChart.height - y(scope.barChart.data[i]) } .directive 'stackedBarChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.sbarChart.title = attrs.title if attrs.title? scope.sbarChart.width = parseInt(attrs.width) if attrs.width? scope.sbarChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 35, right: 120, bottom: 30, left: 40 } tooltip = d3.select el[0] .append 'div' .attr 'class', 'tooltip' .style 'opacity', 0 svg = d3.select el[0] .append 'svg' .attr 'width', scope.sbarChart.width + margin.left + margin.right .attr 'height', scope.sbarChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" lab = scope.sbarChart.labels remapped = scope.sbarChart.categories.map (cat) -> scope.sbarChart.data.map (d, i) -> { x: d[lab], y: d[cat], cat: cat } stacked = d3.layout.stack()(remapped) y = d3.scale.linear().rangeRound [scope.sbarChart.height, 0] yAxis = d3.svg.axis().scale(y) .tickFormat((d) -> if d > 100000.0 Math.round(d/10000)/100 + " M" else scope.thou_sep d ) .orient 'left' x = d3.scale.ordinal().rangeRoundBands [0, scope.sbarChart.width], 0.3, 0.2 xAxis = d3.svg.axis().scale(x).orient 'bottom' xAxis.tickValues scope.sbarChart.labVals if scope.sbarChart.labVals? x.domain stacked[0].map (d) -> d.x svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.sbarChart.height})" .call xAxis y.domain [0, d3.max(stacked[-1..][0], (d) -> return d.y0 + d.y)] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis .selectAll('line') .style "stroke-dasharray", "3, 3" color = d3.scale.category20() svg.append 'text' .attr 'x', x(stacked[0][Math.floor stacked[0].length/2].x) .attr 'y', y(20 + d3.max(stacked[-1..][0], ((d) -> d.y0 + d.y))) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'bar-chart-title' .text scope.sbarChart.title g = svg.selectAll 'g.vgroup' .data stacked .enter() .append 'g' .attr 'class', 'vgroup' .style 'fill', (d, i) -> d3.rgb(color(i)).brighter(1.2) .style 'stroke', (d, i) -> d3.rgb(color(i)).darker() r = g.selectAll 'rect' .data (d) -> d .enter() .append 'rect' .attr 'id', (d) -> "#{ d.cat }-#{ d.x }" .attr 'x', (d) -> x(d.x) .attr 'y', (d) -> y(d.y + d.y0) .attr 'height', (d) -> y(d.y0) - y(d.y + d.y0) .attr 'width', x.rangeBand() .on('click', (d, i) -> # d3.select "\##{ d.cat }-#{ d.x }" # .style 'opacity', 0.85 # .transition().duration(1500).ease 'exp' # .style 'opacity', 1 t = """ <p style='text-align: center;'> <b>#{ d.cat }/#{ d.x }</b> <hr /></p> <p style='text-align: center'> #{ scope.thou_sep(d.y) } </p> """ tooltip.html '' tooltip.transition().duration 1000 .style 'opacity', 0.75 tooltip.html t .style 'left', (d3.event.pageX + 10) + 'px' .style 'top', (d3.event.pageY - 75) + 'px' .style 'opacity', 1 tooltip.transition().duration 5000 .style 'opacity', 0 ) .append 'title' .html (d) -> "<strong>#{ d.cat }/#{ d.x }</strong>: #{ scope.thou_sep(d.y) }" legend = svg.append('g').attr 'class', 'legend' legend.selectAll '.legend-rect' .data scope.sbarChart.categories .enter() .append 'rect' .attr 'class', '.legend-rect' .attr('width', 16) .attr 'height', 16 .attr 'x', scope.sbarChart.width + 2 .attr 'y', (d, i) -> 20*i .style 'stroke', (d, i) -> d3.rgb(color(i)).darker() .style 'fill', (d, i) -> d3.rgb(color(i)).brighter(1.2) legend.selectAll 'text' .data scope.sbarChart.categories .enter() .append 'text' .attr 'class', 'legend' .attr 'x', scope.sbarChart.width + 24 .attr 'y', (d, i) -> 20*i + 8 .attr 'dy', 4 .text (d) -> d } .directive 'lineChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.lineChart.title = attrs.title if attrs.title? scope.lineChart.width = parseInt(attrs.width) if attrs.width? scope.lineChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 35, right: 120, bottom: 30, left: 40 } tooltip = d3.select el[0] .append 'div' .attr 'class', 'tooltip' .style 'opacity', 0 svg = d3.select el[0] .append 'svg' .attr 'width', scope.lineChart.width + margin.left + margin.right .attr 'height', scope.lineChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" y = d3.scale.linear().rangeRound [scope.lineChart.height, 0] yAxis = d3.svg.axis() .scale(y) .orient 'left' ymax = d3.max scope.series.map (s) -> d3.max(s.data.map (d) -> d.y) y.domain [0, d3.max scope.series.map (s) -> d3.max(s.data.map (d) -> d.y) ] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis x = d3.time.scale().range [0, scope.lineChart.width] xAxis = d3.svg.axis().scale(x) .orient 'bottom' .tickFormat d3.time.format("%W") x.domain [ d3.min(scope.series.map((s) -> s.data[0].x)), d3.max(scope.series.map((s) -> s.data[-1..][0].x)), ] svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.lineChart.height})" .call xAxis svg.append 'text' .attr 'x', scope.lineChart.width/2 .attr 'y', y(20 + ymax) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'line-chart-title' .text scope.lineChart.title line = d3.svg.line() .interpolate("monotone") .x (d) -> x(d.x) .y (d) -> y(d.y) win = [] for i, s of scope.series svg.append 'path' .datum s.data .attr 'class', 'line' .attr 'stroke', d3.scale.category10().range()[i] .attr 'd', line win[i] = s.data.filter (d) ->d.lx7 > 0 for i, w of win for ww in w d = [ { x: ww.x, y: 0, draw: ww.draw }, ww ] svg.append 'path' .datum d .attr 'id', "draw-#{ ww.draw }" .attr 'class', 'line' # .attr 'stroke-dasharray', "3, 3" .attr 'stroke', d3.scale.category10().range()[i] .attr 'stroke-dasharray', '0.8 1.6' .on 'click', (d, i) -> t = """ <p style='text-align: center;'> <b>коло: #{ d[1].draw }</b><br /> </p> """ tooltip.html t tooltip.transition().duration 1000 .style 'opacity', 0.75 tooltip.html t .style 'left', (d3.event.pageX) + 'px' .style 'top', (d3.event.pageY-60) + 'px' .style 'opacity', 1 tooltip.transition().duration 5000 .style 'opacity', 0 .attr 'd', line .append 'title' .html (d, i) -> "<strong>коло: #{ d[1].draw }</strong>" # hints for x7, 1st prize winners legend = svg.append('g').attr 'class', 'legend' legend.selectAll 'text' .data scope.series.map (s) -> s.name .enter() .append 'text' .attr 'class', 'legend' .attr 'x', scope.lineChart.width + 4 .attr 'y', (d, i) -> 20*i + 8 .attr 'dy', 4 .style 'fill', (d, i) ->d3.rgb(d3.scale.category10().range()[i]).darker(0.5) .text (d) -> d }
true
# # app.coffee # lotto-ionic # v0.0.2 # Copyright 2016 PI:NAME:<NAME>END_PI, https://github.com/atonevski/lotto-ionic # For license information see LICENSE in the repository # # Ionic Starter App # angular.module is a global place for creating, registering and retrieving Angular modules # 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) # the 2nd parameter is an array of 'requires' angular.module 'app', ['ionic', 'ngCordova', 'app.util', 'app.upload', 'app.annual', 'app.weekly', 'app.stats', 'app.winners', 'app.drawn.numbers'] .config ($stateProvider, $urlRouterProvider) -> $stateProvider.state 'home', { url: '/home' templateUrl: 'views/home/home.html' } .state 'root', { url: '/' templateUrl: 'views/home/home.html' } .state 'annual', { url: '/annual' templateUrl: 'views/annual/annual.html' controller: 'Annual' } .state 'weekly', { url: '/weekly/:year' templateUrl: 'views/weekly/weekly.html' controller: 'Weekly' } .state 'stats', { url: '/stats' templateUrl: 'views/stats/home.html' } .state 'lotto-stats', { url: '/stats/lotto' templateUrl: 'views/stats/lfreqs.html' controller: 'LottoStats' } .state 'joker-stats', { url: '/stats/joker' templateUrl: 'views/stats/jfreqs.html' controller: 'JokerStats' } .state 'winners-stats', { url: '/stats/winners' templateUrl: 'views/stats/winners.html' controller: 'WinnersStats' } .state 'upload', { url: '/upload' templateUrl: 'views/upload/upload.html' controller: 'Upload' } .state 'winners', { url: '/winners' templateUrl: 'views/winners/winners.html' # controller: 'Winners' } .state 'lotto-winners', { url: '/winners/lotto' templateUrl: 'views/winners/lotto.html' controller: 'LottoWinners' } .state 'joker-winners', { url: '/winners/joker' templateUrl: 'views/winners/joker.html' controller: 'JokerWinners' } .state 'lotto-drawn-numbers', { url: '/drawn-numbers/lotto' templateUrl: 'views/drawn-numbers/lotto.html' controller: 'LottoDrawnNumbers' } .state 'about', { url: '/about' templateUrl: 'views/about/about.html' controller: 'About' } $urlRouterProvider.otherwise '/home' .run ($ionicPlatform, $cordovaAppVersion, $rootScope) -> $ionicPlatform.ready () -> if window.cordova && window.cordova.plugins.Keyboard # Hide the accessory bar by default (remove this to # show the accessory bar above the keyboard # for form inputs)g cordova.plugins.Keyboard.hideKeyboardAccessoryBar true # Don't remove this line unless you know what you are doing. It stops the viewport # from snapping when text inputs are focused. Ionic handles this internally for # a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll true if window.StatusBar StatusBar.styleDefault() # check internet connection # Cordova Connection available options # Value Description # Connection.UNKNOWN Unknown connection # Connection.ETHERNET Ethernet connection # Connection.WIFI WiFi connection # Connection.CELL_2G Cell 2G connection # Connection.CELL_3G Cell 3G connection # Connection.CELL_4G Cell 4G connection # Connection.NONE No network connection # # add cordova plugin: # cordova plugin add cordova-plugin-network-information # if navigator.connection # if navigator.connection.type == Connection.NONE # $ionicPopup.confirm { # title: "Интернет" # content: "Интернет е недостапен на уредот." # } # .then (result) -> # ionic.Platform.exitApp() unless result .controller 'Main', ($scope, $rootScope, $http, util, $cordovaAppVersion, $cordovaNetwork, $ionicPopup) -> ionic.Platform.ready () -> if $cordovaNetwork.getNetwork() == Connection.NONE $ionicPopup.confirm { title: 'Интернет' content: 'Интернет е недостапен на уредот.' cancelText: 'Откажи' cancelType: 'button-assertive' okText: 'Продолжи' okType: 'button-positive' } .then (result) -> ionic.Platform.exitApp() unless result if window.cordova $cordovaAppVersion.getVersionNumber().then (ver) -> $scope.appVersion = ver $cordovaAppVersion.getAppName().then (name) -> $scope.appName = name to_json = (d) -> # convert google query response to json re = /^([^(]+?\()(.*)\);$/g match = re.exec d JSON.parse match[2] # some global vars, and functions # NOTE: # This should be done through object merging $scope.uploadNeeded = no $scope.to_json = to_json # $scope.thou_sep = util.thou_sep # export to all child conotrollers # $scope.GS_KEY = util.GS_KEY # $scope.GS_URL = util.GS_URL # $scope.RES_RE = util.RES_RE # $scope.eval_row = util.eval_row # $scope.yesterday = util.yesterday # $scope.nextDraw = util.nextDraw # $scope.dateToDMY = util.dateToDMY # we can't use util.merge, so we do it # manually for k, v of util $scope[k] = v # get last year $scope.qurl = (q) -> "#{ $scope.GS_URL }tq?tqx=out:json&key=#{ $scope.GS_KEY }" + "&tq=#{ encodeURI q }" query = 'SELECT YEAR(B) ORDER BY YEAR(B) DESC LIMIT 1' $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.lastYear = ($scope.eval_row res.table.rows[0])[0] # device width/height $scope.width = window.innerWidth $scope.height = window.innerHeight console.log "WxH: #{ window.innerWidth }x#{ window.innerHeight }" # check for upload $scope.checkUpload = () -> unless $scope.lastDraw? # $scope.uploadNeeded = no # since we can't know $scope.uploadNeeded = no # since we can't know return no nextd = $scope.nextDraw $scope.lastDraw $scope.uploadNeeded = (nextd.date <= $scope.yesterday()) # we watch on lastDraw $rootScope.$watch 'lastDraw', (n, o) -> # old and new values if n if $rootScope.uploadNeeded? $scope.uploadNeeded = $rootScope.uploadNeeded else $scope.checkUpload() # get last draw number & date q = 'SELECT A, B ORDER BY B DESC LIMIT 1' $http.get $scope.qurl(q) .success (data, status) -> res = $scope.to_json data r = $scope.eval_row res.table.rows[0] $scope.lastDraw = draw: r[0] date: new Date r[1] $rootScope.lastDraw = draw: r[0] date: new Date r[1] $scope.checkUpload() .directive 'barChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.barChart.title = attrs.title if attrs.title? scope.barChart.width = parseInt(attrs.width) if attrs.width? scope.barChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 15, right: 10, bottom: 40, left: 60 } svg = d3.select el[0] .append 'svg' .attr 'width', scope.barChart.width + margin.left + margin.right .attr 'height', scope.barChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" y = d3.scale.linear().rangeRound [scope.barChart.height, 0] yAxis = d3.svg.axis().scale(y) .tickFormat (d) -> Math.round(d/10000)/100 + " M" .orient 'left' x = d3.scale.ordinal().rangeRoundBands [0, scope.barChart.width], 0.1 xAxis = d3.svg.axis().scale(x).orient 'bottom' y.domain [0, d3.max(scope.barChart.data)] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis x.domain scope.barChart.labels svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.barChart.height})" .call xAxis svg.append 'text' .attr 'x', x(scope.barChart.labels[Math.floor scope.barChart.labels.length/2]) .attr 'y', y(20 + d3.max(scope.barChart.data)) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'bar-chart-title' .text scope.barChart.title r = svg.selectAll '.bar' .data scope.barChart.data.map (d) -> Math.floor Math.random()*d .enter().append 'rect' .attr 'class', 'bar' .attr 'x', (d, i) -> x(scope.barChart.labels[i]) .attr 'y', (d) -> y(d) .attr 'height', (d) -> scope.barChart.height - y(d) .attr 'width', x.rangeBand() .attr 'title', (d, i) -> scope.thou_sep(scope.barChart.data[i]) r.transition().duration 1000 .ease 'elastic' .attr 'y', (d, i) -> y(scope.barChart.data[i]) .attr 'height', (d, i) -> scope.barChart.height - y(scope.barChart.data[i]) } .directive 'stackedBarChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.sbarChart.title = attrs.title if attrs.title? scope.sbarChart.width = parseInt(attrs.width) if attrs.width? scope.sbarChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 35, right: 120, bottom: 30, left: 40 } tooltip = d3.select el[0] .append 'div' .attr 'class', 'tooltip' .style 'opacity', 0 svg = d3.select el[0] .append 'svg' .attr 'width', scope.sbarChart.width + margin.left + margin.right .attr 'height', scope.sbarChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" lab = scope.sbarChart.labels remapped = scope.sbarChart.categories.map (cat) -> scope.sbarChart.data.map (d, i) -> { x: d[lab], y: d[cat], cat: cat } stacked = d3.layout.stack()(remapped) y = d3.scale.linear().rangeRound [scope.sbarChart.height, 0] yAxis = d3.svg.axis().scale(y) .tickFormat((d) -> if d > 100000.0 Math.round(d/10000)/100 + " M" else scope.thou_sep d ) .orient 'left' x = d3.scale.ordinal().rangeRoundBands [0, scope.sbarChart.width], 0.3, 0.2 xAxis = d3.svg.axis().scale(x).orient 'bottom' xAxis.tickValues scope.sbarChart.labVals if scope.sbarChart.labVals? x.domain stacked[0].map (d) -> d.x svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.sbarChart.height})" .call xAxis y.domain [0, d3.max(stacked[-1..][0], (d) -> return d.y0 + d.y)] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis .selectAll('line') .style "stroke-dasharray", "3, 3" color = d3.scale.category20() svg.append 'text' .attr 'x', x(stacked[0][Math.floor stacked[0].length/2].x) .attr 'y', y(20 + d3.max(stacked[-1..][0], ((d) -> d.y0 + d.y))) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'bar-chart-title' .text scope.sbarChart.title g = svg.selectAll 'g.vgroup' .data stacked .enter() .append 'g' .attr 'class', 'vgroup' .style 'fill', (d, i) -> d3.rgb(color(i)).brighter(1.2) .style 'stroke', (d, i) -> d3.rgb(color(i)).darker() r = g.selectAll 'rect' .data (d) -> d .enter() .append 'rect' .attr 'id', (d) -> "#{ d.cat }-#{ d.x }" .attr 'x', (d) -> x(d.x) .attr 'y', (d) -> y(d.y + d.y0) .attr 'height', (d) -> y(d.y0) - y(d.y + d.y0) .attr 'width', x.rangeBand() .on('click', (d, i) -> # d3.select "\##{ d.cat }-#{ d.x }" # .style 'opacity', 0.85 # .transition().duration(1500).ease 'exp' # .style 'opacity', 1 t = """ <p style='text-align: center;'> <b>#{ d.cat }/#{ d.x }</b> <hr /></p> <p style='text-align: center'> #{ scope.thou_sep(d.y) } </p> """ tooltip.html '' tooltip.transition().duration 1000 .style 'opacity', 0.75 tooltip.html t .style 'left', (d3.event.pageX + 10) + 'px' .style 'top', (d3.event.pageY - 75) + 'px' .style 'opacity', 1 tooltip.transition().duration 5000 .style 'opacity', 0 ) .append 'title' .html (d) -> "<strong>#{ d.cat }/#{ d.x }</strong>: #{ scope.thou_sep(d.y) }" legend = svg.append('g').attr 'class', 'legend' legend.selectAll '.legend-rect' .data scope.sbarChart.categories .enter() .append 'rect' .attr 'class', '.legend-rect' .attr('width', 16) .attr 'height', 16 .attr 'x', scope.sbarChart.width + 2 .attr 'y', (d, i) -> 20*i .style 'stroke', (d, i) -> d3.rgb(color(i)).darker() .style 'fill', (d, i) -> d3.rgb(color(i)).brighter(1.2) legend.selectAll 'text' .data scope.sbarChart.categories .enter() .append 'text' .attr 'class', 'legend' .attr 'x', scope.sbarChart.width + 24 .attr 'y', (d, i) -> 20*i + 8 .attr 'dy', 4 .text (d) -> d } .directive 'lineChart', () -> { restrict: 'A' replace: false link: (scope, el, attrs) -> scope.lineChart.title = attrs.title if attrs.title? scope.lineChart.width = parseInt(attrs.width) if attrs.width? scope.lineChart.height = parseInt(attrs.height) if attrs.height? margin = { top: 35, right: 120, bottom: 30, left: 40 } tooltip = d3.select el[0] .append 'div' .attr 'class', 'tooltip' .style 'opacity', 0 svg = d3.select el[0] .append 'svg' .attr 'width', scope.lineChart.width + margin.left + margin.right .attr 'height', scope.lineChart.height + margin.top + margin.bottom .append 'g' .attr 'transform', "translate(#{margin.left}, #{margin.top})" y = d3.scale.linear().rangeRound [scope.lineChart.height, 0] yAxis = d3.svg.axis() .scale(y) .orient 'left' ymax = d3.max scope.series.map (s) -> d3.max(s.data.map (d) -> d.y) y.domain [0, d3.max scope.series.map (s) -> d3.max(s.data.map (d) -> d.y) ] svg.append 'g' .attr 'class', 'y axis' .transition().duration 1000 .call yAxis x = d3.time.scale().range [0, scope.lineChart.width] xAxis = d3.svg.axis().scale(x) .orient 'bottom' .tickFormat d3.time.format("%W") x.domain [ d3.min(scope.series.map((s) -> s.data[0].x)), d3.max(scope.series.map((s) -> s.data[-1..][0].x)), ] svg.append 'g' .attr 'class', 'x axis' .attr 'transform', "translate(0, #{scope.lineChart.height})" .call xAxis svg.append 'text' .attr 'x', scope.lineChart.width/2 .attr 'y', y(20 + ymax) .attr 'dy', '-0.35em' .attr 'text-anchor', 'middle' .attr 'class', 'line-chart-title' .text scope.lineChart.title line = d3.svg.line() .interpolate("monotone") .x (d) -> x(d.x) .y (d) -> y(d.y) win = [] for i, s of scope.series svg.append 'path' .datum s.data .attr 'class', 'line' .attr 'stroke', d3.scale.category10().range()[i] .attr 'd', line win[i] = s.data.filter (d) ->d.lx7 > 0 for i, w of win for ww in w d = [ { x: ww.x, y: 0, draw: ww.draw }, ww ] svg.append 'path' .datum d .attr 'id', "draw-#{ ww.draw }" .attr 'class', 'line' # .attr 'stroke-dasharray', "3, 3" .attr 'stroke', d3.scale.category10().range()[i] .attr 'stroke-dasharray', '0.8 1.6' .on 'click', (d, i) -> t = """ <p style='text-align: center;'> <b>коло: #{ d[1].draw }</b><br /> </p> """ tooltip.html t tooltip.transition().duration 1000 .style 'opacity', 0.75 tooltip.html t .style 'left', (d3.event.pageX) + 'px' .style 'top', (d3.event.pageY-60) + 'px' .style 'opacity', 1 tooltip.transition().duration 5000 .style 'opacity', 0 .attr 'd', line .append 'title' .html (d, i) -> "<strong>коло: #{ d[1].draw }</strong>" # hints for x7, 1st prize winners legend = svg.append('g').attr 'class', 'legend' legend.selectAll 'text' .data scope.series.map (s) -> s.name .enter() .append 'text' .attr 'class', 'legend' .attr 'x', scope.lineChart.width + 4 .attr 'y', (d, i) -> 20*i + 8 .attr 'dy', 4 .style 'fill', (d, i) ->d3.rgb(d3.scale.category10().range()[i]).darker(0.5) .text (d) -> d }
[ { "context": "application/x-www-form-urlencoded'\n username: client.id\n password: client.secret\n data =\n gr", "end": 318, "score": 0.9995718002319336, "start": 309, "tag": "USERNAME", "value": "client.id" }, { "context": "encoded'\n username: client.id\n password: client.secret\n data =\n grant_type: 'password'\n use", "end": 348, "score": 0.9992445111274719, "start": 335, "tag": "PASSWORD", "value": "client.secret" }, { "context": "ata =\n grant_type: 'password'\n username: user.id\n password: user.secret\n scope: scope.jo", "end": 412, "score": 0.9995334148406982, "start": 405, "tag": "USERNAME", "value": "user.id" }, { "context": "'password'\n username: user.id\n password: user.secret\n scope: scope.join(' ')\n {statusCode, sta", "end": 440, "score": 0.999200165271759, "start": 429, "tag": "PASSWORD", "value": "user.secret" } ]
test/1-api.coffee
twhtanghk/activerecord-model
0
co = require 'co' util = require 'util' assert = require 'assert' describe 'api', -> api = null oauth2 = null before -> {api, oauth2} = sails.config it 'post', -> co -> {url, client, user, scope} = oauth2 opts = 'Content-Type': 'application/x-www-form-urlencoded' username: client.id password: client.secret data = grant_type: 'password' username: user.id password: user.secret scope: scope.join(' ') {statusCode, statusMessage, body} = yield api().post url.token, data, opts assert statusCode == 200 and not body.error?, "#{statusMessage}: #{util.inspect body}" console.log body.access_token
26537
co = require 'co' util = require 'util' assert = require 'assert' describe 'api', -> api = null oauth2 = null before -> {api, oauth2} = sails.config it 'post', -> co -> {url, client, user, scope} = oauth2 opts = 'Content-Type': 'application/x-www-form-urlencoded' username: client.id password: <PASSWORD> data = grant_type: 'password' username: user.id password: <PASSWORD> scope: scope.join(' ') {statusCode, statusMessage, body} = yield api().post url.token, data, opts assert statusCode == 200 and not body.error?, "#{statusMessage}: #{util.inspect body}" console.log body.access_token
true
co = require 'co' util = require 'util' assert = require 'assert' describe 'api', -> api = null oauth2 = null before -> {api, oauth2} = sails.config it 'post', -> co -> {url, client, user, scope} = oauth2 opts = 'Content-Type': 'application/x-www-form-urlencoded' username: client.id password: PI:PASSWORD:<PASSWORD>END_PI data = grant_type: 'password' username: user.id password: PI:PASSWORD:<PASSWORD>END_PI scope: scope.join(' ') {statusCode, statusMessage, body} = yield api().post url.token, data, opts assert statusCode == 200 and not body.error?, "#{statusMessage}: #{util.inspect body}" console.log body.access_token
[ { "context": "ams =\n actor:\n displayName: \"Assaf\"\n verb: \"posted\"\n Activ", "end": 422, "score": 0.9997724890708923, "start": 417, "tag": "NAME", "value": "Assaf" }, { "context": "owser.query(\".activity .actor .name\").innerHTML, \"Assaf\"\n\n it \"should not show actor image\", ->\n ", "end": 878, "score": 0.9995769262313843, "start": 873, "tag": "NAME", "value": "Assaf" }, { "context": "ser.query(\".activity .actor .name\").textContent, \"Teresa T.\"\n\n it \"should include actor name in title\", -", "end": 1581, "score": 0.9951990842819214, "start": 1573, "tag": "NAME", "value": "Teresa T" }, { "context": ">\n assert browser.document.title.endsWith(\" Teresa T. posted\")\n\n \n describe \"image\", ->\n b", "end": 1692, "score": 0.9812862277030945, "start": 1684, "tag": "NAME", "value": "Teresa T" }, { "context": "ams =\n actor:\n displayName: \"Assaf\"\n image:\n url: \"ht", "end": 1824, "score": 0.9997560977935791, "start": 1819, "tag": "NAME", "value": "Assaf" }, { "context": "ams =\n actor:\n displayName: \"Assaf\"\n url: \"http://labnotes.org/\"", "end": 2432, "score": 0.9996379017829895, "start": 2427, "tag": "NAME", "value": "Assaf" }, { "context": "r.query(\".activity .actor a .name\").textContent, \"Assaf\"\n\n it \"should place profile photo inside lin", "end": 2972, "score": 0.9995805025100708, "start": 2967, "tag": "NAME", "value": "Assaf" }, { "context": "->\n params =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n Activity.create", "end": 3377, "score": 0.9996457099914551, "start": 3372, "tag": "NAME", "value": "Assaf" }, { "context": " params =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n Activity.cr", "end": 3808, "score": 0.9996168613433838, "start": 3803, "tag": "NAME", "value": "Assaf" }, { "context": "arams =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n o", "end": 4152, "score": 0.999665379524231, "start": 4147, "tag": "NAME", "value": "Assaf" }, { "context": " params =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n object:\n ", "end": 4837, "score": 0.9994832277297974, "start": 4832, "tag": "NAME", "value": "Assaf" }, { "context": "arams =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n o", "end": 5573, "score": 0.999355137348175, "start": 5568, "tag": "NAME", "value": "Assaf" }, { "context": "arams =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n o", "end": 6360, "score": 0.99942946434021, "start": 6355, "tag": "NAME", "value": "Assaf" }, { "context": "arams =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n o", "end": 7177, "score": 0.9770435094833374, "start": 7172, "tag": "NAME", "value": "Assaf" }, { "context": " params =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n published", "end": 8048, "score": 0.9828587770462036, "start": 8043, "tag": "NAME", "value": "Assaf" }, { "context": " params =\n actor: { displayName: \"Assaf\" }\n verb: \"tested\"\n location:", "end": 8543, "score": 0.9485218524932861, "start": 8538, "tag": "NAME", "value": "Assaf" } ]
server/test/view_activity.coffee
assaf/vanity.js
2
{ setup } = require("./helper") # must be at top assert = require("assert") Browser = require("zombie") Activity = require("../models/activity") describe "activity", -> browser = new Browser() before setup ### # -- Activity actor -- describe "actor", -> describe "name only", -> activity_id = null before (done)-> params = actor: displayName: "Assaf" verb: "posted" Activity.create params, (error, id)-> activity_id = id browser.visit "/activity/#{activity_id}", done it "should include activity identifier", -> assert id = browser.query(".activity").getAttribute("id") assert.equal id, "activity-#{activity_id}" it "should show actor name", -> assert.equal browser.query(".activity .actor .name").innerHTML, "Assaf" it "should not show actor image", -> assert !browser.query(".activity .actor img") it "should not link to actor", -> assert !browser.query(".activity .actor a") it "should include actor name in title", -> assert browser.document.title.endsWith(" Assaf posted") describe "no name but id", -> before (done)-> params = actor: id: "29245d14" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should make name up from actor ID", -> assert.equal browser.query(".activity .actor .name").textContent, "Teresa T." it "should include actor name in title", -> assert browser.document.title.endsWith(" Teresa T. posted") describe "image", -> before (done)-> params = actor: displayName: "Assaf" image: url: "http://awe.sm/5hWp5" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should include avatar", -> assert.equal browser.query(".activity .actor img.avatar").getAttribute("src"), "http://awe.sm/5hWp5" it "should place avatar before display name", -> assert browser.query(".activity .actor img.avatar + span.name") describe "url", -> before (done)-> params = actor: displayName: "Assaf" url: "http://labnotes.org/" image: url: "http://awe.sm/5hWp5" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should link to actor", -> assert.equal browser.query(".activity .actor a").getAttribute("href"), "http://labnotes.org/" it "should place display name inside link", -> assert.equal browser.query(".activity .actor a .name").textContent, "Assaf" it "should place profile photo inside link", -> assert.equal browser.query(".activity .actor img.avatar").getAttribute("src"), "http://awe.sm/5hWp5" it "should include actor name in title", -> assert browser.document.title.endsWith(" Assaf posted") # -- Activity verb -- describe "verb", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show verb after actor", -> assert.equal browser.query(".activity .actor + .verb").textContent, "tested" # -- Activity verb -- describe "object", -> describe "missing", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should not show object part", -> assert !browser.query(".object") describe "name only", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" object: displayName: "this view" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object following verb", -> assert browser.query(".activity .verb + .object") it "should show object display name", -> assert.equal browser.query(".activity .object").textContent.trim(), "this view" it "should include object name in title", -> assert browser.document.title.endsWith(" Assaf tested this view") describe "URL only", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" object: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object as link", -> assert.equal browser.query(".activity .object a").getAttribute("href"), "http://awe.sm/5hWp5" it "should show URL as object", -> assert.equal browser.query(".activity .object a").textContent, "http://awe.sm/5hWp5" it "should include object URL in title", -> assert browser.document.title.endsWith(" Assaf tested http://awe.sm/5hWp5") describe "name and URL", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" object: displayName: "this link" url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object as link", -> assert.equal browser.query(".activity .object a").getAttribute("href"), "http://awe.sm/5hWp5" it "should show display name as object", -> assert.equal browser.query(".activity .object a").textContent, "this link" it "should include object name in title", -> assert browser.document.title.endsWith(" Assaf tested this link") describe "with image (no URL)", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" object: displayName: "this link" image: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show image media following object", -> assert browser.query(".activity .object + .image.media") it "should show media as link to full photo", -> assert.equal browser.query(".activity a.image").getAttribute("href"), "http://awe.sm/5hWp5" it "should show image", -> assert.equal browser.query(".activity a.image img").getAttribute("src"), "http://awe.sm/5hWp5" describe "with image (and URL)", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" object: displayName: "this link" url: "http://awe.sm/5hbLb" image: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show image media following object", -> assert browser.query(".activity .object + .image.media") it "should show media as link to object", -> assert.equal browser.query(".activity a.image").getAttribute("href"), "http://awe.sm/5hbLb" it "should show image", -> assert.equal browser.query(".activity a.image img").getAttribute("src"), "http://awe.sm/5hWp5" # -- Activity time stamp -- describe "timestamp", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" published: new Date(1331706824865) Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show activity timestamp in current locale", -> assert.equal browser.query(".activity .published").textContent, "Tue Mar 13 2012 23:33:44 GMT-0700 (PDT)" # -- Activity location -- describe "location", -> before (done)-> params = actor: { displayName: "Assaf" } verb: "tested" location: "San Francisco" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show activity location following timestamp", -> assert browser.query(".activity .published + .location") it "should show activity location", -> assert.equal browser.query(".activity .location").textContent, "San Francisco, CA, USA" ###
190668
{ setup } = require("./helper") # must be at top assert = require("assert") Browser = require("zombie") Activity = require("../models/activity") describe "activity", -> browser = new Browser() before setup ### # -- Activity actor -- describe "actor", -> describe "name only", -> activity_id = null before (done)-> params = actor: displayName: "<NAME>" verb: "posted" Activity.create params, (error, id)-> activity_id = id browser.visit "/activity/#{activity_id}", done it "should include activity identifier", -> assert id = browser.query(".activity").getAttribute("id") assert.equal id, "activity-#{activity_id}" it "should show actor name", -> assert.equal browser.query(".activity .actor .name").innerHTML, "<NAME>" it "should not show actor image", -> assert !browser.query(".activity .actor img") it "should not link to actor", -> assert !browser.query(".activity .actor a") it "should include actor name in title", -> assert browser.document.title.endsWith(" Assaf posted") describe "no name but id", -> before (done)-> params = actor: id: "29245d14" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should make name up from actor ID", -> assert.equal browser.query(".activity .actor .name").textContent, "<NAME>." it "should include actor name in title", -> assert browser.document.title.endsWith(" <NAME>. posted") describe "image", -> before (done)-> params = actor: displayName: "<NAME>" image: url: "http://awe.sm/5hWp5" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should include avatar", -> assert.equal browser.query(".activity .actor img.avatar").getAttribute("src"), "http://awe.sm/5hWp5" it "should place avatar before display name", -> assert browser.query(".activity .actor img.avatar + span.name") describe "url", -> before (done)-> params = actor: displayName: "<NAME>" url: "http://labnotes.org/" image: url: "http://awe.sm/5hWp5" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should link to actor", -> assert.equal browser.query(".activity .actor a").getAttribute("href"), "http://labnotes.org/" it "should place display name inside link", -> assert.equal browser.query(".activity .actor a .name").textContent, "<NAME>" it "should place profile photo inside link", -> assert.equal browser.query(".activity .actor img.avatar").getAttribute("src"), "http://awe.sm/5hWp5" it "should include actor name in title", -> assert browser.document.title.endsWith(" Assaf posted") # -- Activity verb -- describe "verb", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show verb after actor", -> assert.equal browser.query(".activity .actor + .verb").textContent, "tested" # -- Activity verb -- describe "object", -> describe "missing", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should not show object part", -> assert !browser.query(".object") describe "name only", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" object: displayName: "this view" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object following verb", -> assert browser.query(".activity .verb + .object") it "should show object display name", -> assert.equal browser.query(".activity .object").textContent.trim(), "this view" it "should include object name in title", -> assert browser.document.title.endsWith(" Assaf tested this view") describe "URL only", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" object: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object as link", -> assert.equal browser.query(".activity .object a").getAttribute("href"), "http://awe.sm/5hWp5" it "should show URL as object", -> assert.equal browser.query(".activity .object a").textContent, "http://awe.sm/5hWp5" it "should include object URL in title", -> assert browser.document.title.endsWith(" Assaf tested http://awe.sm/5hWp5") describe "name and URL", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" object: displayName: "this link" url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object as link", -> assert.equal browser.query(".activity .object a").getAttribute("href"), "http://awe.sm/5hWp5" it "should show display name as object", -> assert.equal browser.query(".activity .object a").textContent, "this link" it "should include object name in title", -> assert browser.document.title.endsWith(" Assaf tested this link") describe "with image (no URL)", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" object: displayName: "this link" image: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show image media following object", -> assert browser.query(".activity .object + .image.media") it "should show media as link to full photo", -> assert.equal browser.query(".activity a.image").getAttribute("href"), "http://awe.sm/5hWp5" it "should show image", -> assert.equal browser.query(".activity a.image img").getAttribute("src"), "http://awe.sm/5hWp5" describe "with image (and URL)", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" object: displayName: "this link" url: "http://awe.sm/5hbLb" image: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show image media following object", -> assert browser.query(".activity .object + .image.media") it "should show media as link to object", -> assert.equal browser.query(".activity a.image").getAttribute("href"), "http://awe.sm/5hbLb" it "should show image", -> assert.equal browser.query(".activity a.image img").getAttribute("src"), "http://awe.sm/5hWp5" # -- Activity time stamp -- describe "timestamp", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" published: new Date(1331706824865) Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show activity timestamp in current locale", -> assert.equal browser.query(".activity .published").textContent, "Tue Mar 13 2012 23:33:44 GMT-0700 (PDT)" # -- Activity location -- describe "location", -> before (done)-> params = actor: { displayName: "<NAME>" } verb: "tested" location: "San Francisco" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show activity location following timestamp", -> assert browser.query(".activity .published + .location") it "should show activity location", -> assert.equal browser.query(".activity .location").textContent, "San Francisco, CA, USA" ###
true
{ setup } = require("./helper") # must be at top assert = require("assert") Browser = require("zombie") Activity = require("../models/activity") describe "activity", -> browser = new Browser() before setup ### # -- Activity actor -- describe "actor", -> describe "name only", -> activity_id = null before (done)-> params = actor: displayName: "PI:NAME:<NAME>END_PI" verb: "posted" Activity.create params, (error, id)-> activity_id = id browser.visit "/activity/#{activity_id}", done it "should include activity identifier", -> assert id = browser.query(".activity").getAttribute("id") assert.equal id, "activity-#{activity_id}" it "should show actor name", -> assert.equal browser.query(".activity .actor .name").innerHTML, "PI:NAME:<NAME>END_PI" it "should not show actor image", -> assert !browser.query(".activity .actor img") it "should not link to actor", -> assert !browser.query(".activity .actor a") it "should include actor name in title", -> assert browser.document.title.endsWith(" Assaf posted") describe "no name but id", -> before (done)-> params = actor: id: "29245d14" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should make name up from actor ID", -> assert.equal browser.query(".activity .actor .name").textContent, "PI:NAME:<NAME>END_PI." it "should include actor name in title", -> assert browser.document.title.endsWith(" PI:NAME:<NAME>END_PI. posted") describe "image", -> before (done)-> params = actor: displayName: "PI:NAME:<NAME>END_PI" image: url: "http://awe.sm/5hWp5" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should include avatar", -> assert.equal browser.query(".activity .actor img.avatar").getAttribute("src"), "http://awe.sm/5hWp5" it "should place avatar before display name", -> assert browser.query(".activity .actor img.avatar + span.name") describe "url", -> before (done)-> params = actor: displayName: "PI:NAME:<NAME>END_PI" url: "http://labnotes.org/" image: url: "http://awe.sm/5hWp5" verb: "posted" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should link to actor", -> assert.equal browser.query(".activity .actor a").getAttribute("href"), "http://labnotes.org/" it "should place display name inside link", -> assert.equal browser.query(".activity .actor a .name").textContent, "PI:NAME:<NAME>END_PI" it "should place profile photo inside link", -> assert.equal browser.query(".activity .actor img.avatar").getAttribute("src"), "http://awe.sm/5hWp5" it "should include actor name in title", -> assert browser.document.title.endsWith(" Assaf posted") # -- Activity verb -- describe "verb", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show verb after actor", -> assert.equal browser.query(".activity .actor + .verb").textContent, "tested" # -- Activity verb -- describe "object", -> describe "missing", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should not show object part", -> assert !browser.query(".object") describe "name only", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" object: displayName: "this view" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object following verb", -> assert browser.query(".activity .verb + .object") it "should show object display name", -> assert.equal browser.query(".activity .object").textContent.trim(), "this view" it "should include object name in title", -> assert browser.document.title.endsWith(" Assaf tested this view") describe "URL only", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" object: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object as link", -> assert.equal browser.query(".activity .object a").getAttribute("href"), "http://awe.sm/5hWp5" it "should show URL as object", -> assert.equal browser.query(".activity .object a").textContent, "http://awe.sm/5hWp5" it "should include object URL in title", -> assert browser.document.title.endsWith(" Assaf tested http://awe.sm/5hWp5") describe "name and URL", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" object: displayName: "this link" url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show object as link", -> assert.equal browser.query(".activity .object a").getAttribute("href"), "http://awe.sm/5hWp5" it "should show display name as object", -> assert.equal browser.query(".activity .object a").textContent, "this link" it "should include object name in title", -> assert browser.document.title.endsWith(" Assaf tested this link") describe "with image (no URL)", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" object: displayName: "this link" image: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show image media following object", -> assert browser.query(".activity .object + .image.media") it "should show media as link to full photo", -> assert.equal browser.query(".activity a.image").getAttribute("href"), "http://awe.sm/5hWp5" it "should show image", -> assert.equal browser.query(".activity a.image img").getAttribute("src"), "http://awe.sm/5hWp5" describe "with image (and URL)", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" object: displayName: "this link" url: "http://awe.sm/5hbLb" image: url: "http://awe.sm/5hWp5" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show image media following object", -> assert browser.query(".activity .object + .image.media") it "should show media as link to object", -> assert.equal browser.query(".activity a.image").getAttribute("href"), "http://awe.sm/5hbLb" it "should show image", -> assert.equal browser.query(".activity a.image img").getAttribute("src"), "http://awe.sm/5hWp5" # -- Activity time stamp -- describe "timestamp", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" published: new Date(1331706824865) Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show activity timestamp in current locale", -> assert.equal browser.query(".activity .published").textContent, "Tue Mar 13 2012 23:33:44 GMT-0700 (PDT)" # -- Activity location -- describe "location", -> before (done)-> params = actor: { displayName: "PI:NAME:<NAME>END_PI" } verb: "tested" location: "San Francisco" Activity.create params, (error, activity_id)-> browser.visit "/activity/#{activity_id}", done it "should show activity location following timestamp", -> assert browser.query(".activity .published + .location") it "should show activity location", -> assert.equal browser.query(".activity .location").textContent, "San Francisco, CA, USA" ###
[ { "context": "=node(3, 1)\n # WHERE (n.age < 30 and n.name = \"Tobias\") or not(n.name = \"Tobias\")\n # RETURN n\n #\n ", "end": 327, "score": 0.9980943202972412, "start": 321, "tag": "NAME", "value": "Tobias" }, { "context": ".age < 30 and n.name = \"Tobias\") or not(n.name = \"Tobias\")\n # RETURN n\n #\n # START n=node(3, 1)\n #", "end": 353, "score": 0.998536229133606, "start": 347, "tag": "NAME", "value": "Tobias" } ]
node_modules/tower/packages/tower-store/shared/neo4j/serialization.coffee
MagicPower2/Power
1
# @todo # http://docs.neo4j.org/chunked/stable/security-server.html # http://sujitpal.blogspot.com/2009/05/using-neo4j-to-load-and-query-owl.html Tower.StoreNeo4jSerialization = # @example conditions (http://docs.neo4j.org/chunked/stable/query-where.html) # START n=node(3, 1) # WHERE (n.age < 30 and n.name = "Tobias") or not(n.name = "Tobias") # RETURN n # # START n=node(3, 1) # WHERE n.name =~ /(?i)ANDR.*/ # RETURN n # # @example select fields (http://docs.neo4j.org/chunked/stable/query-return.html) # START a=node(1) # RETURN a.age AS SomethingTotallyDifferent # # @example order (http://docs.neo4j.org/chunked/stable/query-order.html) # START n=node(3,1,2) # RETURN n # ORDER BY n.name # # @example skip, limit, pagination (http://docs.neo4j.org/chunked/stable/query-skip.html) # START n=node(3, 4, 5, 1, 2) # RETURN n # ORDER BY n.name # SKIP 1 # LIMIT 2 serializeToCypher: (criteria) -> conditions = criteria.conditions() module.exports = Tower.StoreNeo4jSerialization
199858
# @todo # http://docs.neo4j.org/chunked/stable/security-server.html # http://sujitpal.blogspot.com/2009/05/using-neo4j-to-load-and-query-owl.html Tower.StoreNeo4jSerialization = # @example conditions (http://docs.neo4j.org/chunked/stable/query-where.html) # START n=node(3, 1) # WHERE (n.age < 30 and n.name = "<NAME>") or not(n.name = "<NAME>") # RETURN n # # START n=node(3, 1) # WHERE n.name =~ /(?i)ANDR.*/ # RETURN n # # @example select fields (http://docs.neo4j.org/chunked/stable/query-return.html) # START a=node(1) # RETURN a.age AS SomethingTotallyDifferent # # @example order (http://docs.neo4j.org/chunked/stable/query-order.html) # START n=node(3,1,2) # RETURN n # ORDER BY n.name # # @example skip, limit, pagination (http://docs.neo4j.org/chunked/stable/query-skip.html) # START n=node(3, 4, 5, 1, 2) # RETURN n # ORDER BY n.name # SKIP 1 # LIMIT 2 serializeToCypher: (criteria) -> conditions = criteria.conditions() module.exports = Tower.StoreNeo4jSerialization
true
# @todo # http://docs.neo4j.org/chunked/stable/security-server.html # http://sujitpal.blogspot.com/2009/05/using-neo4j-to-load-and-query-owl.html Tower.StoreNeo4jSerialization = # @example conditions (http://docs.neo4j.org/chunked/stable/query-where.html) # START n=node(3, 1) # WHERE (n.age < 30 and n.name = "PI:NAME:<NAME>END_PI") or not(n.name = "PI:NAME:<NAME>END_PI") # RETURN n # # START n=node(3, 1) # WHERE n.name =~ /(?i)ANDR.*/ # RETURN n # # @example select fields (http://docs.neo4j.org/chunked/stable/query-return.html) # START a=node(1) # RETURN a.age AS SomethingTotallyDifferent # # @example order (http://docs.neo4j.org/chunked/stable/query-order.html) # START n=node(3,1,2) # RETURN n # ORDER BY n.name # # @example skip, limit, pagination (http://docs.neo4j.org/chunked/stable/query-skip.html) # START n=node(3, 4, 5, 1, 2) # RETURN n # ORDER BY n.name # SKIP 1 # LIMIT 2 serializeToCypher: (criteria) -> conditions = criteria.conditions() module.exports = Tower.StoreNeo4jSerialization
[ { "context": "###\n termap - Terminal Map Viewer\n by Michael Strassburger <codepoet@cpan.org>\n\n Handling of and access to ", "end": 60, "score": 0.9998739361763, "start": 40, "tag": "NAME", "value": "Michael Strassburger" }, { "context": " - Terminal Map Viewer\n by Michael Strassburger <codepoet@cpan.org>\n\n Handling of and access to single VectorTiles\n", "end": 79, "score": 0.9999313354492188, "start": 62, "tag": "EMAIL", "value": "codepoet@cpan.org" } ]
src/Tile.coffee
82ndAirborneDiv/mapsc
1
### termap - Terminal Map Viewer by Michael Strassburger <codepoet@cpan.org> Handling of and access to single VectorTiles ### VectorTile = require('@mapbox/vector-tile').VectorTile Protobuf = require 'pbf' Promise = require 'bluebird' zlib = require 'zlib' rbush = require 'rbush' x256 = require 'x256' earcut = require 'earcut' config = require "./config" utils = require "./utils" class Tile layers: {} constructor: (@styler) -> load: (buffer) -> @_unzipIfNeeded buffer .then (buffer) => @_loadTile buffer .then => @_loadLayers() .then => this _loadTile: (buffer) -> @tile = new VectorTile new Protobuf buffer _unzipIfNeeded: (buffer) -> new Promise (resolve, reject) => if @_isGzipped buffer zlib.gunzip buffer, (err, data) -> return reject err if err resolve data else resolve buffer _isGzipped: (buffer) -> buffer.slice(0,2).indexOf(Buffer.from([0x1f, 0x8b])) is 0 _loadLayers: () -> layers = {} colorCache = {} for name, layer of @tile.layers nodes = [] #continue if name is "water" for i in [0...layer.length] # TODO: caching of similar attributes to avoid looking up the style each time #continue if @styler and not @styler.getStyleFor layer, feature feature = layer.feature i feature.properties.$type = type = [undefined, "Point", "LineString", "Polygon"][feature.type] if @styler style = @styler.getStyleFor name, feature continue unless style color = style.paint['line-color'] or style.paint['fill-color'] or style.paint['text-color'] # TODO: style zoom stops handling if color instanceof Object color = color.stops[0][1] colorCode = colorCache[color] or colorCache[color] = x256 utils.hex2rgb color # TODO: monkey patching test case for tiles with a reduced extent 4096 / 8 -> 512 # use feature.loadGeometry() again as soon as we got a 512 extent tileset geometries = feature.loadGeometry() #@_reduceGeometry feature, 8 sort = feature.properties.localrank or feature.properties.scalerank label = if style.type is "symbol" feature.properties["name_"+config.language] or feature.properties.name_en or feature.properties.name or feature.properties.house_num else undefined if style.type is "fill" nodes.push @_addBoundaries true, # id: feature.id layer: name style: style label: label sort: sort points: geometries color: colorCode else for points in geometries nodes.push @_addBoundaries false, # id: feature.id layer: name style: style label: label sort: sort points: points color: colorCode tree = rbush 18 tree.load nodes layers[name] = extent: layer.extent tree: tree @layers = layers _addBoundaries: (deep, data) -> minX = Infinity maxX = -Infinity minY = Infinity maxY = -Infinity for p in (if deep then data.points[0] else data.points) minX = p.x if p.x < minX maxX = p.x if p.x > maxX minY = p.y if p.y < minY maxY = p.y if p.y > maxY data.minX = minX data.maxX = maxX data.minY = minY data.maxY = maxY data _reduceGeometry: (feature, factor) -> for points, i in feature.loadGeometry() reduced = [] last = null for point in points p = x: Math.floor point.x/factor y: Math.floor point.y/factor if last and last.x is p.x and last.y is p.y continue reduced.push last = p reduced module.exports = Tile
126658
### termap - Terminal Map Viewer by <NAME> <<EMAIL>> Handling of and access to single VectorTiles ### VectorTile = require('@mapbox/vector-tile').VectorTile Protobuf = require 'pbf' Promise = require 'bluebird' zlib = require 'zlib' rbush = require 'rbush' x256 = require 'x256' earcut = require 'earcut' config = require "./config" utils = require "./utils" class Tile layers: {} constructor: (@styler) -> load: (buffer) -> @_unzipIfNeeded buffer .then (buffer) => @_loadTile buffer .then => @_loadLayers() .then => this _loadTile: (buffer) -> @tile = new VectorTile new Protobuf buffer _unzipIfNeeded: (buffer) -> new Promise (resolve, reject) => if @_isGzipped buffer zlib.gunzip buffer, (err, data) -> return reject err if err resolve data else resolve buffer _isGzipped: (buffer) -> buffer.slice(0,2).indexOf(Buffer.from([0x1f, 0x8b])) is 0 _loadLayers: () -> layers = {} colorCache = {} for name, layer of @tile.layers nodes = [] #continue if name is "water" for i in [0...layer.length] # TODO: caching of similar attributes to avoid looking up the style each time #continue if @styler and not @styler.getStyleFor layer, feature feature = layer.feature i feature.properties.$type = type = [undefined, "Point", "LineString", "Polygon"][feature.type] if @styler style = @styler.getStyleFor name, feature continue unless style color = style.paint['line-color'] or style.paint['fill-color'] or style.paint['text-color'] # TODO: style zoom stops handling if color instanceof Object color = color.stops[0][1] colorCode = colorCache[color] or colorCache[color] = x256 utils.hex2rgb color # TODO: monkey patching test case for tiles with a reduced extent 4096 / 8 -> 512 # use feature.loadGeometry() again as soon as we got a 512 extent tileset geometries = feature.loadGeometry() #@_reduceGeometry feature, 8 sort = feature.properties.localrank or feature.properties.scalerank label = if style.type is "symbol" feature.properties["name_"+config.language] or feature.properties.name_en or feature.properties.name or feature.properties.house_num else undefined if style.type is "fill" nodes.push @_addBoundaries true, # id: feature.id layer: name style: style label: label sort: sort points: geometries color: colorCode else for points in geometries nodes.push @_addBoundaries false, # id: feature.id layer: name style: style label: label sort: sort points: points color: colorCode tree = rbush 18 tree.load nodes layers[name] = extent: layer.extent tree: tree @layers = layers _addBoundaries: (deep, data) -> minX = Infinity maxX = -Infinity minY = Infinity maxY = -Infinity for p in (if deep then data.points[0] else data.points) minX = p.x if p.x < minX maxX = p.x if p.x > maxX minY = p.y if p.y < minY maxY = p.y if p.y > maxY data.minX = minX data.maxX = maxX data.minY = minY data.maxY = maxY data _reduceGeometry: (feature, factor) -> for points, i in feature.loadGeometry() reduced = [] last = null for point in points p = x: Math.floor point.x/factor y: Math.floor point.y/factor if last and last.x is p.x and last.y is p.y continue reduced.push last = p reduced module.exports = Tile
true
### termap - Terminal Map Viewer by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Handling of and access to single VectorTiles ### VectorTile = require('@mapbox/vector-tile').VectorTile Protobuf = require 'pbf' Promise = require 'bluebird' zlib = require 'zlib' rbush = require 'rbush' x256 = require 'x256' earcut = require 'earcut' config = require "./config" utils = require "./utils" class Tile layers: {} constructor: (@styler) -> load: (buffer) -> @_unzipIfNeeded buffer .then (buffer) => @_loadTile buffer .then => @_loadLayers() .then => this _loadTile: (buffer) -> @tile = new VectorTile new Protobuf buffer _unzipIfNeeded: (buffer) -> new Promise (resolve, reject) => if @_isGzipped buffer zlib.gunzip buffer, (err, data) -> return reject err if err resolve data else resolve buffer _isGzipped: (buffer) -> buffer.slice(0,2).indexOf(Buffer.from([0x1f, 0x8b])) is 0 _loadLayers: () -> layers = {} colorCache = {} for name, layer of @tile.layers nodes = [] #continue if name is "water" for i in [0...layer.length] # TODO: caching of similar attributes to avoid looking up the style each time #continue if @styler and not @styler.getStyleFor layer, feature feature = layer.feature i feature.properties.$type = type = [undefined, "Point", "LineString", "Polygon"][feature.type] if @styler style = @styler.getStyleFor name, feature continue unless style color = style.paint['line-color'] or style.paint['fill-color'] or style.paint['text-color'] # TODO: style zoom stops handling if color instanceof Object color = color.stops[0][1] colorCode = colorCache[color] or colorCache[color] = x256 utils.hex2rgb color # TODO: monkey patching test case for tiles with a reduced extent 4096 / 8 -> 512 # use feature.loadGeometry() again as soon as we got a 512 extent tileset geometries = feature.loadGeometry() #@_reduceGeometry feature, 8 sort = feature.properties.localrank or feature.properties.scalerank label = if style.type is "symbol" feature.properties["name_"+config.language] or feature.properties.name_en or feature.properties.name or feature.properties.house_num else undefined if style.type is "fill" nodes.push @_addBoundaries true, # id: feature.id layer: name style: style label: label sort: sort points: geometries color: colorCode else for points in geometries nodes.push @_addBoundaries false, # id: feature.id layer: name style: style label: label sort: sort points: points color: colorCode tree = rbush 18 tree.load nodes layers[name] = extent: layer.extent tree: tree @layers = layers _addBoundaries: (deep, data) -> minX = Infinity maxX = -Infinity minY = Infinity maxY = -Infinity for p in (if deep then data.points[0] else data.points) minX = p.x if p.x < minX maxX = p.x if p.x > maxX minY = p.y if p.y < minY maxY = p.y if p.y > maxY data.minX = minX data.maxX = maxX data.minY = minY data.maxY = maxY data _reduceGeometry: (feature, factor) -> for points, i in feature.loadGeometry() reduced = [] last = null for point in points p = x: Math.floor point.x/factor y: Math.floor point.y/factor if last and last.x is p.x and last.y is p.y continue reduced.push last = p reduced module.exports = Tile
[ { "context": "->\n expect(MyLibrary.Product.where(token: 'jshf8e').klass()).toEqual(ActiveResource::Relation)\n\n ", "end": 487, "score": 0.8882865905761719, "start": 481, "tag": "PASSWORD", "value": "jshf8e" }, { "context": "->\n expect(MyLibrary.Product.where(token: 'jshf8e').customFind()).toEqual('found');\n\n describe '", "end": 681, "score": 0.9117167592048645, "start": 675, "tag": "PASSWORD", "value": "jshf8e" }, { "context": "->\n expect(MyLibrary.Product.where(token: 'jshf8e').links()).toEqual({ related: 'https://example.co", "end": 839, "score": 0.9062037467956543, "start": 833, "tag": "PASSWORD", "value": "jshf8e" }, { "context": "eEach ->\n MyLibrary.Product.findBy(token: 'jshf8e')\n .then window.onSuccess\n\n @promis", "end": 2901, "score": 0.9816809892654419, "start": 2895, "tag": "PASSWORD", "value": "jshf8e" }, { "context": " expect(@paramStr).toContain('filter[token]=jshf8e')\n\n it 'returns a resource of the type reque", "end": 3354, "score": 0.8086908459663391, "start": 3348, "tag": "PASSWORD", "value": "jshf8e" }, { "context": "uery', ->\n MyLibrary.Product.where(token: 'jshf8e').all()\n\n moxios.wait =>\n @paramS", "end": 5002, "score": 0.9615055322647095, "start": 4996, "tag": "PASSWORD", "value": "jshf8e" }, { "context": " expect(@paramStr).toContain('filter[token]=jshf8e')\n\n it 'merges filters', ->\n MyLibrar", "end": 5160, "score": 0.7504004240036011, "start": 5154, "tag": "PASSWORD", "value": "jshf8e" }, { "context": "ters', ->\n MyLibrary.Product.where(token: 'jshf8e').where(another: 'param').all()\n\n moxios.w", "end": 5240, "score": 0.9533730745315552, "start": 5234, "tag": "PASSWORD", "value": "jshf8e" }, { "context": " expect(@paramStr).toContain('filter[token]=jshf8e&filter[another]=param')\n\n describe 'when val", "end": 5422, "score": 0.6531416773796082, "start": 5416, "tag": "PASSWORD", "value": "jshf8e" } ]
spec/relation.coffee
nicklandgrebe/active-resource.js
95
describe 'ActiveResource', -> beforeEach -> moxios.install(MyLibrary.interface.axios) window.onSuccess = jasmine.createSpy('onSuccess') window.onFailure = jasmine.createSpy('onFailure') window.onCompletion = jasmine.createSpy('onCompletion') afterEach -> moxios.uninstall() describe '::Relation', -> describe 'when calling Relation extension methods on Base', -> it 'creates a new Relation', -> expect(MyLibrary.Product.where(token: 'jshf8e').klass()).toEqual(ActiveResource::Relation) describe 'when calling custom method of Base on Relation', -> it 'calls method', -> expect(MyLibrary.Product.where(token: 'jshf8e').customFind()).toEqual('found'); describe '#links()', -> it 'returns the correct links', -> expect(MyLibrary.Product.where(token: 'jshf8e').links()).toEqual({ related: 'https://example.com/api/v1/products/' }) describe '#all()', -> beforeEach -> MyLibrary.Product.all() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve all resources', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related']) it 'returns a collection of the type requested', -> @promise.then => expect(@result.isA?(ActiveResource::Collection)).toBeTruthy() describe '#each()', -> beforeEach -> @i = 0 MyLibrary.Product.each (p) => @i += 1 @promise = moxios.wait => @response = JsonApiResponses.Product.all.success moxios.requests.mostRecent().respondWith(@response) it 'makes a call to retrieve all resources', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related']) it 'iterates over each resource returned', -> @promise.then => expect(@i).toEqual(@response.response.data.length) describe '#find()', -> beforeEach -> MyLibrary.Product.find(1) .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a resource', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related'] + '1/') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#findBy()', -> beforeEach -> MyLibrary.Product.findBy(token: 'jshf8e') .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve filtered resources', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=jshf8e') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#first()', -> beforeEach -> MyLibrary.Product.first() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a single resource via index', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=1') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#last()', -> beforeEach -> MyLibrary.Product.last() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a single resource starting from the back, via index', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=1&offset=-1') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#where()', -> it 'adds filters to a query', -> MyLibrary.Product.where(token: 'jshf8e').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=jshf8e') it 'merges filters', -> MyLibrary.Product.where(token: 'jshf8e').where(another: 'param').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=jshf8e&filter[another]=param') describe 'when value is null', -> it 'sets filter to null', -> MyLibrary.OrderItem.where(order: null).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=%00') describe 'when value is resource', -> it 'adds resource primary key as value', -> MyLibrary.OrderItem.where(order: MyLibrary.Order.build(id: '5')).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=5') describe 'when value is array of resources', -> it 'adds resource primary key as value', -> MyLibrary.OrderItem.where(order: [ MyLibrary.Order.build(id: '5'), MyLibrary.Order.build(id: '6') ]).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=5,6') describe '#order()', -> it 'adds sort params to a query', -> MyLibrary.Product.order(createdAt: 'asc').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('sort=created_at') it 'merges sorts', -> MyLibrary.Product.order(createdAt: 'asc').order(updatedAt: 'desc').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('sort=created_at,-updated_at') describe '#select()', -> it 'determines the root model to apply fields to', -> MyLibrary.Product.select('id', 'createdAt').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id,created_at') it 'determines the model to apply nested fields to', -> MyLibrary.Product.select('id', { orders: 'price' }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id&fields[orders]=price') it 'underscores class names', -> MyLibrary.Product.select(timeSlots: 'startsAt').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[time_slots]=starts_at') it 'merges fields', -> MyLibrary.Product.select('id', 'createdAt').select(orders: 'price').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id,created_at&fields[orders]=price') describe '#includes()', -> it 'adds root level includes', -> MyLibrary.Product.includes('merchant', 'attributeValues').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,attribute_values') it 'adds nested includes', -> MyLibrary.Product.includes('merchant', { orders: ['attributeValues','giftCards'] }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,orders.attribute_values,orders.gift_cards') it 'adds multiple nested includes', -> MyLibrary.Product.includes('merchant', { orders: { attributeValues: 'value', giftCards: 'value' }, timeSlots: 'product' }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,orders.attribute_values.value,orders.gift_cards.value,time_slots.product') describe 'nested includes', -> beforeEach -> MyLibrary.OrderItem.find('3') .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.OrderItem.find.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'constructs nested includes together', -> @promise.then => order = @result.order() expect(order.orderItems().size()).toEqual(3) order.orderItems().target().each((orderItem) => expect(orderItem.order()).toBe(order) ) describe '#page()', -> beforeEach -> MyLibrary.Product.page(2).all() .then window.onSuccess @promise = moxios.wait => true it 'adds a page number to the query', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('page[number]=2') describe 'when no links in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasNextPage returns false', -> @promise2.then => expect(@resources.hasNextPage()).toBeFalsy(); it 'nextPage returns null', -> @promise2.then => expect(@resources.nextPage()).toBeUndefined(); it 'hasPrevPage returns false', -> @promise2.then => expect(@resources.hasPrevPage()).toBeFalsy(); it 'prevPage returns null', -> @promise2.then => expect(@resources.prevPage()).toBeUndefined(); describe 'when next link in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasNextPage returns true', -> @promise2.then => expect(@resources.hasNextPage()).toBeTruthy(); describe 'requesting nextPage', -> beforeEach -> @promise3 = @promise2.then => @resources.nextPage() .then window.onSuccess moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) it 'nextPage requests next link', -> @promise3.then => expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products?page[number]=3&page[size]=2') describe 'requesting same nextPage again', -> beforeEach -> @promise4 = @promise3.then => @requestCount = moxios.requests.count() @resources.nextPage() it 'does not request nextPage again', -> @promise4.then => expect(@requestCount).toEqual(moxios.requests.count()) describe 'when prev link in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasPrevPage returns true', -> @promise2.then => expect(@resources.hasPrevPage()).toBeTruthy(); describe 'requesting prevPage', -> beforeEach -> @promise3 = @promise2.then => @resources.prevPage() .then window.onSuccess moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) it 'prevPage requests prev link', -> @promise3.then => expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products?page[number]=1&page[size]=2') describe 'requesting same prevPage again', -> beforeEach -> @promise4 = @promise3.then => @requestCount = moxios.requests.count() @resources.prevPage() it 'does not request prevPage again', -> @promise4.then => expect(@requestCount).toEqual(moxios.requests.count()) describe 'when meta in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'meta attributes added', -> @promise2.then => expect(@resources.meta().totalPages).toBeDefined() describe '#perPage()', -> it 'adds a page size to the query', -> MyLibrary.Product.perPage(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('page[size]=2') describe '#limit()', -> it 'adds a limit to the query', -> MyLibrary.Product.limit(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=2') describe '#offset()', -> it 'adds an offset to the query', -> MyLibrary.Product.offset(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('offset=2') describe '#build()', -> beforeEach -> @product = MyLibrary.Product.build(title: 'A product title') it 'assigns attributes to the built resource', -> expect(@product.title).toEqual('A product title') it 'builds a resource of Base\'s type', -> expect(@product.isA?(MyLibrary.Product)).toBeTruthy() describe 'when called from Relation', -> beforeEach -> @product = MyLibrary.Product.where(title: 'My title').build() it 'builds a resource of Relation\'s base type', -> expect(@product.isA?(MyLibrary.Product)).toBeTruthy() it 'adds filters to the attributes assigned', -> expect(@product.title).toEqual('My title') describe '#create()', -> describe 'in general', -> beforeEach -> MyLibrary.Product.create(title: 'Another title', description: 'Another description', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.success) .then => @result = window.onCompletion.calls.mostRecent().args[0] it 'executes the completion callback', -> @promise.then => expect(window.onCompletion).toHaveBeenCalled() it 'builds a resource of class\'s type', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() it 'assigns attributes to the created resource', -> @promise.then => expect(@result.title).toEqual('Another title') describe 'on success', -> beforeEach -> MyLibrary.Product.create(title: 'Another title', description: 'Another description', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.success) .then => @result = window.onCompletion.calls.mostRecent().args[0] it 'creates a persisted resource', -> @promise.then => expect(@result.persisted( )).toBeTruthy() describe 'on failure', -> beforeEach -> MyLibrary.Product.create(title: '', description: '', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.failure) .catch => Promise.reject(@result = window.onCompletion.calls.mostRecent().args[0]) it 'does not create a persisted resource', -> @promise.catch => expect(@result.persisted?()).toBeFalsy() it 'adds errors', -> @promise.catch => expect(@result.errors().empty?()).toBeFalsy()
89588
describe 'ActiveResource', -> beforeEach -> moxios.install(MyLibrary.interface.axios) window.onSuccess = jasmine.createSpy('onSuccess') window.onFailure = jasmine.createSpy('onFailure') window.onCompletion = jasmine.createSpy('onCompletion') afterEach -> moxios.uninstall() describe '::Relation', -> describe 'when calling Relation extension methods on Base', -> it 'creates a new Relation', -> expect(MyLibrary.Product.where(token: '<PASSWORD>').klass()).toEqual(ActiveResource::Relation) describe 'when calling custom method of Base on Relation', -> it 'calls method', -> expect(MyLibrary.Product.where(token: '<PASSWORD>').customFind()).toEqual('found'); describe '#links()', -> it 'returns the correct links', -> expect(MyLibrary.Product.where(token: '<PASSWORD>').links()).toEqual({ related: 'https://example.com/api/v1/products/' }) describe '#all()', -> beforeEach -> MyLibrary.Product.all() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve all resources', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related']) it 'returns a collection of the type requested', -> @promise.then => expect(@result.isA?(ActiveResource::Collection)).toBeTruthy() describe '#each()', -> beforeEach -> @i = 0 MyLibrary.Product.each (p) => @i += 1 @promise = moxios.wait => @response = JsonApiResponses.Product.all.success moxios.requests.mostRecent().respondWith(@response) it 'makes a call to retrieve all resources', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related']) it 'iterates over each resource returned', -> @promise.then => expect(@i).toEqual(@response.response.data.length) describe '#find()', -> beforeEach -> MyLibrary.Product.find(1) .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a resource', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related'] + '1/') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#findBy()', -> beforeEach -> MyLibrary.Product.findBy(token: '<PASSWORD>') .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve filtered resources', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=<PASSWORD>') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#first()', -> beforeEach -> MyLibrary.Product.first() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a single resource via index', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=1') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#last()', -> beforeEach -> MyLibrary.Product.last() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a single resource starting from the back, via index', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=1&offset=-1') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#where()', -> it 'adds filters to a query', -> MyLibrary.Product.where(token: '<PASSWORD>').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=<PASSWORD>') it 'merges filters', -> MyLibrary.Product.where(token: '<PASSWORD>').where(another: 'param').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=<PASSWORD>&filter[another]=param') describe 'when value is null', -> it 'sets filter to null', -> MyLibrary.OrderItem.where(order: null).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=%00') describe 'when value is resource', -> it 'adds resource primary key as value', -> MyLibrary.OrderItem.where(order: MyLibrary.Order.build(id: '5')).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=5') describe 'when value is array of resources', -> it 'adds resource primary key as value', -> MyLibrary.OrderItem.where(order: [ MyLibrary.Order.build(id: '5'), MyLibrary.Order.build(id: '6') ]).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=5,6') describe '#order()', -> it 'adds sort params to a query', -> MyLibrary.Product.order(createdAt: 'asc').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('sort=created_at') it 'merges sorts', -> MyLibrary.Product.order(createdAt: 'asc').order(updatedAt: 'desc').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('sort=created_at,-updated_at') describe '#select()', -> it 'determines the root model to apply fields to', -> MyLibrary.Product.select('id', 'createdAt').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id,created_at') it 'determines the model to apply nested fields to', -> MyLibrary.Product.select('id', { orders: 'price' }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id&fields[orders]=price') it 'underscores class names', -> MyLibrary.Product.select(timeSlots: 'startsAt').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[time_slots]=starts_at') it 'merges fields', -> MyLibrary.Product.select('id', 'createdAt').select(orders: 'price').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id,created_at&fields[orders]=price') describe '#includes()', -> it 'adds root level includes', -> MyLibrary.Product.includes('merchant', 'attributeValues').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,attribute_values') it 'adds nested includes', -> MyLibrary.Product.includes('merchant', { orders: ['attributeValues','giftCards'] }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,orders.attribute_values,orders.gift_cards') it 'adds multiple nested includes', -> MyLibrary.Product.includes('merchant', { orders: { attributeValues: 'value', giftCards: 'value' }, timeSlots: 'product' }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,orders.attribute_values.value,orders.gift_cards.value,time_slots.product') describe 'nested includes', -> beforeEach -> MyLibrary.OrderItem.find('3') .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.OrderItem.find.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'constructs nested includes together', -> @promise.then => order = @result.order() expect(order.orderItems().size()).toEqual(3) order.orderItems().target().each((orderItem) => expect(orderItem.order()).toBe(order) ) describe '#page()', -> beforeEach -> MyLibrary.Product.page(2).all() .then window.onSuccess @promise = moxios.wait => true it 'adds a page number to the query', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('page[number]=2') describe 'when no links in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasNextPage returns false', -> @promise2.then => expect(@resources.hasNextPage()).toBeFalsy(); it 'nextPage returns null', -> @promise2.then => expect(@resources.nextPage()).toBeUndefined(); it 'hasPrevPage returns false', -> @promise2.then => expect(@resources.hasPrevPage()).toBeFalsy(); it 'prevPage returns null', -> @promise2.then => expect(@resources.prevPage()).toBeUndefined(); describe 'when next link in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasNextPage returns true', -> @promise2.then => expect(@resources.hasNextPage()).toBeTruthy(); describe 'requesting nextPage', -> beforeEach -> @promise3 = @promise2.then => @resources.nextPage() .then window.onSuccess moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) it 'nextPage requests next link', -> @promise3.then => expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products?page[number]=3&page[size]=2') describe 'requesting same nextPage again', -> beforeEach -> @promise4 = @promise3.then => @requestCount = moxios.requests.count() @resources.nextPage() it 'does not request nextPage again', -> @promise4.then => expect(@requestCount).toEqual(moxios.requests.count()) describe 'when prev link in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasPrevPage returns true', -> @promise2.then => expect(@resources.hasPrevPage()).toBeTruthy(); describe 'requesting prevPage', -> beforeEach -> @promise3 = @promise2.then => @resources.prevPage() .then window.onSuccess moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) it 'prevPage requests prev link', -> @promise3.then => expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products?page[number]=1&page[size]=2') describe 'requesting same prevPage again', -> beforeEach -> @promise4 = @promise3.then => @requestCount = moxios.requests.count() @resources.prevPage() it 'does not request prevPage again', -> @promise4.then => expect(@requestCount).toEqual(moxios.requests.count()) describe 'when meta in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'meta attributes added', -> @promise2.then => expect(@resources.meta().totalPages).toBeDefined() describe '#perPage()', -> it 'adds a page size to the query', -> MyLibrary.Product.perPage(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('page[size]=2') describe '#limit()', -> it 'adds a limit to the query', -> MyLibrary.Product.limit(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=2') describe '#offset()', -> it 'adds an offset to the query', -> MyLibrary.Product.offset(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('offset=2') describe '#build()', -> beforeEach -> @product = MyLibrary.Product.build(title: 'A product title') it 'assigns attributes to the built resource', -> expect(@product.title).toEqual('A product title') it 'builds a resource of Base\'s type', -> expect(@product.isA?(MyLibrary.Product)).toBeTruthy() describe 'when called from Relation', -> beforeEach -> @product = MyLibrary.Product.where(title: 'My title').build() it 'builds a resource of Relation\'s base type', -> expect(@product.isA?(MyLibrary.Product)).toBeTruthy() it 'adds filters to the attributes assigned', -> expect(@product.title).toEqual('My title') describe '#create()', -> describe 'in general', -> beforeEach -> MyLibrary.Product.create(title: 'Another title', description: 'Another description', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.success) .then => @result = window.onCompletion.calls.mostRecent().args[0] it 'executes the completion callback', -> @promise.then => expect(window.onCompletion).toHaveBeenCalled() it 'builds a resource of class\'s type', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() it 'assigns attributes to the created resource', -> @promise.then => expect(@result.title).toEqual('Another title') describe 'on success', -> beforeEach -> MyLibrary.Product.create(title: 'Another title', description: 'Another description', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.success) .then => @result = window.onCompletion.calls.mostRecent().args[0] it 'creates a persisted resource', -> @promise.then => expect(@result.persisted( )).toBeTruthy() describe 'on failure', -> beforeEach -> MyLibrary.Product.create(title: '', description: '', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.failure) .catch => Promise.reject(@result = window.onCompletion.calls.mostRecent().args[0]) it 'does not create a persisted resource', -> @promise.catch => expect(@result.persisted?()).toBeFalsy() it 'adds errors', -> @promise.catch => expect(@result.errors().empty?()).toBeFalsy()
true
describe 'ActiveResource', -> beforeEach -> moxios.install(MyLibrary.interface.axios) window.onSuccess = jasmine.createSpy('onSuccess') window.onFailure = jasmine.createSpy('onFailure') window.onCompletion = jasmine.createSpy('onCompletion') afterEach -> moxios.uninstall() describe '::Relation', -> describe 'when calling Relation extension methods on Base', -> it 'creates a new Relation', -> expect(MyLibrary.Product.where(token: 'PI:PASSWORD:<PASSWORD>END_PI').klass()).toEqual(ActiveResource::Relation) describe 'when calling custom method of Base on Relation', -> it 'calls method', -> expect(MyLibrary.Product.where(token: 'PI:PASSWORD:<PASSWORD>END_PI').customFind()).toEqual('found'); describe '#links()', -> it 'returns the correct links', -> expect(MyLibrary.Product.where(token: 'PI:PASSWORD:<PASSWORD>END_PI').links()).toEqual({ related: 'https://example.com/api/v1/products/' }) describe '#all()', -> beforeEach -> MyLibrary.Product.all() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve all resources', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related']) it 'returns a collection of the type requested', -> @promise.then => expect(@result.isA?(ActiveResource::Collection)).toBeTruthy() describe '#each()', -> beforeEach -> @i = 0 MyLibrary.Product.each (p) => @i += 1 @promise = moxios.wait => @response = JsonApiResponses.Product.all.success moxios.requests.mostRecent().respondWith(@response) it 'makes a call to retrieve all resources', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related']) it 'iterates over each resource returned', -> @promise.then => expect(@i).toEqual(@response.response.data.length) describe '#find()', -> beforeEach -> MyLibrary.Product.find(1) .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a resource', -> @promise.then => expect(moxios.requests.mostRecent().url).toEqual(MyLibrary.Product.links()['related'] + '1/') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#findBy()', -> beforeEach -> MyLibrary.Product.findBy(token: 'PI:PASSWORD:<PASSWORD>END_PI') .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve filtered resources', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=PI:PASSWORD:<PASSWORD>END_PI') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#first()', -> beforeEach -> MyLibrary.Product.first() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a single resource via index', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=1') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#last()', -> beforeEach -> MyLibrary.Product.last() .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'makes a call to retrieve a single resource starting from the back, via index', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=1&offset=-1') it 'returns a resource of the type requested', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() describe '#where()', -> it 'adds filters to a query', -> MyLibrary.Product.where(token: 'PI:PASSWORD:<PASSWORD>END_PI').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=PI:PASSWORD:<PASSWORD>END_PI') it 'merges filters', -> MyLibrary.Product.where(token: 'PI:PASSWORD:<PASSWORD>END_PI').where(another: 'param').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[token]=PI:PASSWORD:<PASSWORD>END_PI&filter[another]=param') describe 'when value is null', -> it 'sets filter to null', -> MyLibrary.OrderItem.where(order: null).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=%00') describe 'when value is resource', -> it 'adds resource primary key as value', -> MyLibrary.OrderItem.where(order: MyLibrary.Order.build(id: '5')).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=5') describe 'when value is array of resources', -> it 'adds resource primary key as value', -> MyLibrary.OrderItem.where(order: [ MyLibrary.Order.build(id: '5'), MyLibrary.Order.build(id: '6') ]).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('filter[order]=5,6') describe '#order()', -> it 'adds sort params to a query', -> MyLibrary.Product.order(createdAt: 'asc').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('sort=created_at') it 'merges sorts', -> MyLibrary.Product.order(createdAt: 'asc').order(updatedAt: 'desc').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('sort=created_at,-updated_at') describe '#select()', -> it 'determines the root model to apply fields to', -> MyLibrary.Product.select('id', 'createdAt').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id,created_at') it 'determines the model to apply nested fields to', -> MyLibrary.Product.select('id', { orders: 'price' }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id&fields[orders]=price') it 'underscores class names', -> MyLibrary.Product.select(timeSlots: 'startsAt').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[time_slots]=starts_at') it 'merges fields', -> MyLibrary.Product.select('id', 'createdAt').select(orders: 'price').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('fields[products]=id,created_at&fields[orders]=price') describe '#includes()', -> it 'adds root level includes', -> MyLibrary.Product.includes('merchant', 'attributeValues').all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,attribute_values') it 'adds nested includes', -> MyLibrary.Product.includes('merchant', { orders: ['attributeValues','giftCards'] }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,orders.attribute_values,orders.gift_cards') it 'adds multiple nested includes', -> MyLibrary.Product.includes('merchant', { orders: { attributeValues: 'value', giftCards: 'value' }, timeSlots: 'product' }).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('include=merchant,orders.attribute_values.value,orders.gift_cards.value,time_slots.product') describe 'nested includes', -> beforeEach -> MyLibrary.OrderItem.find('3') .then window.onSuccess @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.OrderItem.find.success) .then => @result = window.onSuccess.calls.mostRecent().args[0] it 'constructs nested includes together', -> @promise.then => order = @result.order() expect(order.orderItems().size()).toEqual(3) order.orderItems().target().each((orderItem) => expect(orderItem.order()).toBe(order) ) describe '#page()', -> beforeEach -> MyLibrary.Product.page(2).all() .then window.onSuccess @promise = moxios.wait => true it 'adds a page number to the query', -> @promise.then => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('page[number]=2') describe 'when no links in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.success) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasNextPage returns false', -> @promise2.then => expect(@resources.hasNextPage()).toBeFalsy(); it 'nextPage returns null', -> @promise2.then => expect(@resources.nextPage()).toBeUndefined(); it 'hasPrevPage returns false', -> @promise2.then => expect(@resources.hasPrevPage()).toBeFalsy(); it 'prevPage returns null', -> @promise2.then => expect(@resources.prevPage()).toBeUndefined(); describe 'when next link in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasNextPage returns true', -> @promise2.then => expect(@resources.hasNextPage()).toBeTruthy(); describe 'requesting nextPage', -> beforeEach -> @promise3 = @promise2.then => @resources.nextPage() .then window.onSuccess moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) it 'nextPage requests next link', -> @promise3.then => expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products?page[number]=3&page[size]=2') describe 'requesting same nextPage again', -> beforeEach -> @promise4 = @promise3.then => @requestCount = moxios.requests.count() @resources.nextPage() it 'does not request nextPage again', -> @promise4.then => expect(@requestCount).toEqual(moxios.requests.count()) describe 'when prev link in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'hasPrevPage returns true', -> @promise2.then => expect(@resources.hasPrevPage()).toBeTruthy(); describe 'requesting prevPage', -> beforeEach -> @promise3 = @promise2.then => @resources.prevPage() .then window.onSuccess moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) it 'prevPage requests prev link', -> @promise3.then => expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products?page[number]=1&page[size]=2') describe 'requesting same prevPage again', -> beforeEach -> @promise4 = @promise3.then => @requestCount = moxios.requests.count() @resources.prevPage() it 'does not request prevPage again', -> @promise4.then => expect(@requestCount).toEqual(moxios.requests.count()) describe 'when meta in response', -> beforeEach -> @promise2 = @promise.then => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.all.paginated) .then => @resources = window.onSuccess.calls.mostRecent().args[0] it 'meta attributes added', -> @promise2.then => expect(@resources.meta().totalPages).toBeDefined() describe '#perPage()', -> it 'adds a page size to the query', -> MyLibrary.Product.perPage(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('page[size]=2') describe '#limit()', -> it 'adds a limit to the query', -> MyLibrary.Product.limit(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('limit=2') describe '#offset()', -> it 'adds an offset to the query', -> MyLibrary.Product.offset(2).all() moxios.wait => @paramStr = requestParams(moxios.requests.mostRecent()) expect(@paramStr).toContain('offset=2') describe '#build()', -> beforeEach -> @product = MyLibrary.Product.build(title: 'A product title') it 'assigns attributes to the built resource', -> expect(@product.title).toEqual('A product title') it 'builds a resource of Base\'s type', -> expect(@product.isA?(MyLibrary.Product)).toBeTruthy() describe 'when called from Relation', -> beforeEach -> @product = MyLibrary.Product.where(title: 'My title').build() it 'builds a resource of Relation\'s base type', -> expect(@product.isA?(MyLibrary.Product)).toBeTruthy() it 'adds filters to the attributes assigned', -> expect(@product.title).toEqual('My title') describe '#create()', -> describe 'in general', -> beforeEach -> MyLibrary.Product.create(title: 'Another title', description: 'Another description', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.success) .then => @result = window.onCompletion.calls.mostRecent().args[0] it 'executes the completion callback', -> @promise.then => expect(window.onCompletion).toHaveBeenCalled() it 'builds a resource of class\'s type', -> @promise.then => expect(@result.isA?(MyLibrary.Product)).toBeTruthy() it 'assigns attributes to the created resource', -> @promise.then => expect(@result.title).toEqual('Another title') describe 'on success', -> beforeEach -> MyLibrary.Product.create(title: 'Another title', description: 'Another description', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.success) .then => @result = window.onCompletion.calls.mostRecent().args[0] it 'creates a persisted resource', -> @promise.then => expect(@result.persisted( )).toBeTruthy() describe 'on failure', -> beforeEach -> MyLibrary.Product.create(title: '', description: '', window.onCompletion) @promise = moxios.wait => moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.save.failure) .catch => Promise.reject(@result = window.onCompletion.calls.mostRecent().args[0]) it 'does not create a persisted resource', -> @promise.catch => expect(@result.persisted?()).toBeFalsy() it 'adds errors', -> @promise.catch => expect(@result.errors().empty?()).toBeFalsy()
[ { "context": "###\nContent: obtiene el Tab.\n@autor Ronny Cabrera\n###\nyOSON.AppCore.addModule \"getTab\", (Sb) ->\n\tde", "end": 49, "score": 0.9998816847801208, "start": 36, "tag": "NAME", "value": "Ronny Cabrera" } ]
frontend/resources/coffee/modules/inicio/inicio/getTab.coffee
ronnyfly2/openvios
0
### Content: obtiene el Tab. @autor Ronny Cabrera ### yOSON.AppCore.addModule "getTab", (Sb) -> defaults = tabItem : '.list_numbers li' st = {} dom = {} catchDom = (st)-> dom.tabItem = $(st.tabItem) return suscribeEvents = -> dom.tabItem.on 'click', events.getTabActive return events = getTabActive:()-> dom.tabItem.removeClass('actived') $(this).addClass('actived') return functions = {} initialize = (opts) -> st = $.extend({}, defaults, opts) catchDom(st) suscribeEvents() return return { init: initialize } ,[]
100273
### Content: obtiene el Tab. @autor <NAME> ### yOSON.AppCore.addModule "getTab", (Sb) -> defaults = tabItem : '.list_numbers li' st = {} dom = {} catchDom = (st)-> dom.tabItem = $(st.tabItem) return suscribeEvents = -> dom.tabItem.on 'click', events.getTabActive return events = getTabActive:()-> dom.tabItem.removeClass('actived') $(this).addClass('actived') return functions = {} initialize = (opts) -> st = $.extend({}, defaults, opts) catchDom(st) suscribeEvents() return return { init: initialize } ,[]
true
### Content: obtiene el Tab. @autor PI:NAME:<NAME>END_PI ### yOSON.AppCore.addModule "getTab", (Sb) -> defaults = tabItem : '.list_numbers li' st = {} dom = {} catchDom = (st)-> dom.tabItem = $(st.tabItem) return suscribeEvents = -> dom.tabItem.on 'click', events.getTabActive return events = getTabActive:()-> dom.tabItem.removeClass('actived') $(this).addClass('actived') return functions = {} initialize = (opts) -> st = $.extend({}, defaults, opts) catchDom(st) suscribeEvents() return return { init: initialize } ,[]
[ { "context": " when 'intersectsBufferRowRange'\n key = 'intersectsRowRange'\n when 'intersectsScreenRowRange'\n ", "end": 17082, "score": 0.8671441078186035, "start": 17064, "tag": "KEY", "value": "intersectsRowRange" }, { "context": " when 'intersectsScreenRowRange'\n key = 'intersectsRowRange'\n [startScreenRow, endScreenRow] = value", "end": 17159, "score": 0.9054893851280212, "start": 17141, "tag": "KEY", "value": "intersectsRowRange" } ]
src/display-marker-layer.coffee
FeodorFitsner/hang-1-text-buffer
0
{Emitter, CompositeDisposable} = require 'event-kit' DisplayMarker = require './display-marker' Range = require './range' Point = require './point' # Public: *Experimental:* A container for a related set of markers at the # {DisplayLayer} level. Wraps an underlying {MarkerLayer} on the {TextBuffer}. # # This API is experimental and subject to change on any release. module.exports = class DisplayMarkerLayer constructor: (@displayLayer, @bufferMarkerLayer, @ownsBufferMarkerLayer) -> {@id} = @bufferMarkerLayer @bufferMarkerLayer.displayMarkerLayers.add(this) @markersById = {} @destroyed = false @emitter = new Emitter @subscriptions = new CompositeDisposable @markersWithDestroyListeners = new Set @subscriptions.add(@bufferMarkerLayer.onDidUpdate(@emitDidUpdate.bind(this))) ### Section: Lifecycle ### # Essential: Destroy this layer. destroy: -> return if @destroyed @destroyed = true @clear() @subscriptions.dispose() @bufferMarkerLayer.displayMarkerLayers.delete(this) @bufferMarkerLayer.destroy() if @ownsBufferMarkerLayer @displayLayer.didDestroyMarkerLayer(@id) @emitter.emit('did-destroy') @emitter.clear() # Public: Destroy all markers in this layer. clear: -> @bufferMarkerLayer.clear() didClearBufferMarkerLayer: -> @markersWithDestroyListeners.forEach (marker) -> marker.didDestroyBufferMarker() @markersById = {} # Essential: Determine whether this layer has been destroyed. # # Returns a {Boolean}. isDestroyed: -> @destroyed ### Section: Event Subscription ### # Public: Subscribe to be notified synchronously when this layer is destroyed. # # Returns a {Disposable}. onDidDestroy: (callback) -> @emitter.on('did-destroy', callback) # Public: Subscribe to be notified asynchronously whenever markers are # created, updated, or destroyed on this layer. *Prefer this method for # optimal performance when interacting with layers that could contain large # numbers of markers.* # # * `callback` A {Function} that will be called with no arguments when changes # occur on this layer. # # Subscribers are notified once, asynchronously when any number of changes # occur in a given tick of the event loop. You should re-query the layer # to determine the state of markers in which you're interested in. It may # be counter-intuitive, but this is much more efficient than subscribing to # events on individual markers, which are expensive to deliver. # # Returns a {Disposable}. onDidUpdate: (callback) -> @emitter.on('did-update', callback) # Public: Subscribe to be notified synchronously whenever markers are created # on this layer. *Avoid this method for optimal performance when interacting # with layers that could contain large numbers of markers.* # # * `callback` A {Function} that will be called with a {TextEditorMarker} # whenever a new marker is created. # # You should prefer {onDidUpdate} when synchronous notifications aren't # absolutely necessary. # # Returns a {Disposable}. onDidCreateMarker: (callback) -> @bufferMarkerLayer.onDidCreateMarker (bufferMarker) => callback(@getMarker(bufferMarker.id)) ### Section: Marker creation ### # Public: Create a marker with the given screen range. # # * `range` A {Range} or range-compatible {Array} # * `options` A hash of key-value pairs to associate with the marker. There # are also reserved property names that have marker-specific meaning. # * `reversed` (optional) {Boolean} Creates the marker in a reversed # orientation. (default: false) # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # * `clipDirection` {String} If `'backward'`, returns the first valid # position preceding an invalid position. If `'forward'`, returns the # first valid position following an invalid position. If `'closest'`, # returns the first valid position closest to an invalid position. # Defaults to `'closest'`. Applies to the start and end of the given range. # # Returns a {DisplayMarker}. markScreenRange: (screenRange, options) -> screenRange = Range.fromObject(screenRange) bufferRange = @displayLayer.translateScreenRange(screenRange, options) @getMarker(@bufferMarkerLayer.markRange(bufferRange, options).id) # Public: Create a marker on this layer with its head at the given screen # position and no tail. # # * `screenPosition` A {Point} or point-compatible {Array} # * `options` (optional) An {Object} with the following keys: # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # * `clipDirection` {String} If `'backward'`, returns the first valid # position preceding an invalid position. If `'forward'`, returns the # first valid position following an invalid position. If `'closest'`, # returns the first valid position closest to an invalid position. # Defaults to `'closest'`. # # Returns a {DisplayMarker}. markScreenPosition: (screenPosition, options) -> screenPosition = Point.fromObject(screenPosition) bufferPosition = @displayLayer.translateScreenPosition(screenPosition, options) @getMarker(@bufferMarkerLayer.markPosition(bufferPosition, options).id) # Public: Create a marker with the given buffer range. # # * `range` A {Range} or range-compatible {Array} # * `options` A hash of key-value pairs to associate with the marker. There # are also reserved property names that have marker-specific meaning. # * `reversed` (optional) {Boolean} Creates the marker in a reversed # orientation. (default: false) # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # # Returns a {DisplayMarker}. markBufferRange: (bufferRange, options) -> bufferRange = Range.fromObject(bufferRange) @getMarker(@bufferMarkerLayer.markRange(bufferRange, options).id) # Public: Create a marker on this layer with its head at the given buffer # position and no tail. # # * `bufferPosition` A {Point} or point-compatible {Array} # * `options` (optional) An {Object} with the following keys: # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # # Returns a {DisplayMarker}. markBufferPosition: (bufferPosition, options) -> @getMarker(@bufferMarkerLayer.markPosition(Point.fromObject(bufferPosition), options).id) ### Section: Querying ### # Essential: Get an existing marker by its id. # # Returns a {DisplayMarker}. getMarker: (id) -> if displayMarker = @markersById[id] displayMarker else if bufferMarker = @bufferMarkerLayer.getMarker(id) @markersById[id] = new DisplayMarker(this, bufferMarker) # Essential: Get all markers in the layer. # # Returns an {Array} of {DisplayMarker}s. getMarkers: -> @bufferMarkerLayer.getMarkers().map ({id}) => @getMarker(id) # Public: Get the number of markers in the marker layer. # # Returns a {Number}. getMarkerCount: -> @bufferMarkerLayer.getMarkerCount() # Public: Find markers in the layer conforming to the given parameters. # # This method finds markers based on the given properties. Markers can be # associated with custom properties that will be compared with basic equality. # In addition, there are several special properties that will be compared # with the range of the markers rather than their properties. # # * `properties` An {Object} containing properties that each returned marker # must satisfy. Markers can be associated with custom properties, which are # compared with basic equality. In addition, several reserved properties # can be used to filter markers based on their current range: # * `startBufferPosition` Only include markers starting at this {Point} in buffer coordinates. # * `endBufferPosition` Only include markers ending at this {Point} in buffer coordinates. # * `startScreenPosition` Only include markers starting at this {Point} in screen coordinates. # * `endScreenPosition` Only include markers ending at this {Point} in screen coordinates. # * `startBufferRow` Only include markers starting at this row in buffer coordinates. # * `endBufferRow` Only include markers ending at this row in buffer coordinates. # * `startScreenRow` Only include markers starting at this row in screen coordinates. # * `endScreenRow` Only include markers ending at this row in screen coordinates. # * `intersectsBufferRowRange` Only include markers intersecting this {Array} # of `[startRow, endRow]` in buffer coordinates. # * `intersectsScreenRowRange` Only include markers intersecting this {Array} # of `[startRow, endRow]` in screen coordinates. # * `containsBufferRange` Only include markers containing this {Range} in buffer coordinates. # * `containsBufferPosition` Only include markers containing this {Point} in buffer coordinates. # * `containedInBufferRange` Only include markers contained in this {Range} in buffer coordinates. # * `containedInScreenRange` Only include markers contained in this {Range} in screen coordinates. # * `intersectsBufferRange` Only include markers intersecting this {Range} in buffer coordinates. # * `intersectsScreenRange` Only include markers intersecting this {Range} in screen coordinates. # # Returns an {Array} of {DisplayMarker}s findMarkers: (params) -> params = @translateToBufferMarkerLayerFindParams(params) @bufferMarkerLayer.findMarkers(params).map (stringMarker) => @getMarker(stringMarker.id) ### Section: Private ### translateBufferPosition: (bufferPosition, options) -> @displayLayer.translateBufferPosition(bufferPosition, options) translateBufferRange: (bufferRange, options) -> @displayLayer.translateBufferRange(bufferRange, options) translateScreenPosition: (screenPosition, options) -> @displayLayer.translateScreenPosition(screenPosition, options) translateScreenRange: (screenRange, options) -> @displayLayer.translateScreenRange(screenRange, options) emitDidUpdate: -> @emitter.emit('did-update') notifyObserversIfMarkerScreenPositionsChanged: -> for marker in @getMarkers() marker.notifyObservers(false) return destroyMarker: (id) -> if marker = @markersById[id] marker.didDestroyBufferMarker() didDestroyMarker: (marker) -> @markersWithDestroyListeners.delete(marker) delete @markersById[marker.id] translateToBufferMarkerLayerFindParams: (params) -> bufferMarkerLayerFindParams = {} for key, value of params switch key when 'startBufferPosition' key = 'startPosition' when 'endBufferPosition' key = 'endPosition' when 'startScreenPosition' key = 'startPosition' value = @displayLayer.translateScreenPosition(value) when 'endScreenPosition' key = 'endPosition' value = @displayLayer.translateScreenPosition(value) when 'startBufferRow' key = 'startRow' when 'endBufferRow' key = 'endRow' when 'startScreenRow' key = 'startRow' value = @displayLayer.translateScreenPosition(Point(value, 0)).row when 'endScreenRow' key = 'endRow' value = @displayLayer.translateScreenPosition(Point(value, Infinity)).row when 'intersectsBufferRowRange' key = 'intersectsRowRange' when 'intersectsScreenRowRange' key = 'intersectsRowRange' [startScreenRow, endScreenRow] = value startBufferRow = @displayLayer.translateScreenPosition(Point(startScreenRow, 0)).row endBufferRow = @displayLayer.translateScreenPosition(Point(endScreenRow, Infinity)).row value = [startBufferRow, endBufferRow] when 'containsBufferRange' key = 'containsRange' when 'containsScreenRange' key = 'containsRange' value = @displayLayer.translateScreenRange(value) when 'containsBufferPosition' key = 'containsPosition' when 'containsScreenPosition' key = 'containsPosition' value = @displayLayer.translateScreenPosition(value) when 'containedInBufferRange' key = 'containedInRange' when 'containedInScreenRange' key = 'containedInRange' value = @displayLayer.translateScreenRange(value) when 'intersectsBufferRange' key = 'intersectsRange' when 'intersectsScreenRange' key = 'intersectsRange' value = @displayLayer.translateScreenRange(value) bufferMarkerLayerFindParams[key] = value bufferMarkerLayerFindParams
78485
{Emitter, CompositeDisposable} = require 'event-kit' DisplayMarker = require './display-marker' Range = require './range' Point = require './point' # Public: *Experimental:* A container for a related set of markers at the # {DisplayLayer} level. Wraps an underlying {MarkerLayer} on the {TextBuffer}. # # This API is experimental and subject to change on any release. module.exports = class DisplayMarkerLayer constructor: (@displayLayer, @bufferMarkerLayer, @ownsBufferMarkerLayer) -> {@id} = @bufferMarkerLayer @bufferMarkerLayer.displayMarkerLayers.add(this) @markersById = {} @destroyed = false @emitter = new Emitter @subscriptions = new CompositeDisposable @markersWithDestroyListeners = new Set @subscriptions.add(@bufferMarkerLayer.onDidUpdate(@emitDidUpdate.bind(this))) ### Section: Lifecycle ### # Essential: Destroy this layer. destroy: -> return if @destroyed @destroyed = true @clear() @subscriptions.dispose() @bufferMarkerLayer.displayMarkerLayers.delete(this) @bufferMarkerLayer.destroy() if @ownsBufferMarkerLayer @displayLayer.didDestroyMarkerLayer(@id) @emitter.emit('did-destroy') @emitter.clear() # Public: Destroy all markers in this layer. clear: -> @bufferMarkerLayer.clear() didClearBufferMarkerLayer: -> @markersWithDestroyListeners.forEach (marker) -> marker.didDestroyBufferMarker() @markersById = {} # Essential: Determine whether this layer has been destroyed. # # Returns a {Boolean}. isDestroyed: -> @destroyed ### Section: Event Subscription ### # Public: Subscribe to be notified synchronously when this layer is destroyed. # # Returns a {Disposable}. onDidDestroy: (callback) -> @emitter.on('did-destroy', callback) # Public: Subscribe to be notified asynchronously whenever markers are # created, updated, or destroyed on this layer. *Prefer this method for # optimal performance when interacting with layers that could contain large # numbers of markers.* # # * `callback` A {Function} that will be called with no arguments when changes # occur on this layer. # # Subscribers are notified once, asynchronously when any number of changes # occur in a given tick of the event loop. You should re-query the layer # to determine the state of markers in which you're interested in. It may # be counter-intuitive, but this is much more efficient than subscribing to # events on individual markers, which are expensive to deliver. # # Returns a {Disposable}. onDidUpdate: (callback) -> @emitter.on('did-update', callback) # Public: Subscribe to be notified synchronously whenever markers are created # on this layer. *Avoid this method for optimal performance when interacting # with layers that could contain large numbers of markers.* # # * `callback` A {Function} that will be called with a {TextEditorMarker} # whenever a new marker is created. # # You should prefer {onDidUpdate} when synchronous notifications aren't # absolutely necessary. # # Returns a {Disposable}. onDidCreateMarker: (callback) -> @bufferMarkerLayer.onDidCreateMarker (bufferMarker) => callback(@getMarker(bufferMarker.id)) ### Section: Marker creation ### # Public: Create a marker with the given screen range. # # * `range` A {Range} or range-compatible {Array} # * `options` A hash of key-value pairs to associate with the marker. There # are also reserved property names that have marker-specific meaning. # * `reversed` (optional) {Boolean} Creates the marker in a reversed # orientation. (default: false) # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # * `clipDirection` {String} If `'backward'`, returns the first valid # position preceding an invalid position. If `'forward'`, returns the # first valid position following an invalid position. If `'closest'`, # returns the first valid position closest to an invalid position. # Defaults to `'closest'`. Applies to the start and end of the given range. # # Returns a {DisplayMarker}. markScreenRange: (screenRange, options) -> screenRange = Range.fromObject(screenRange) bufferRange = @displayLayer.translateScreenRange(screenRange, options) @getMarker(@bufferMarkerLayer.markRange(bufferRange, options).id) # Public: Create a marker on this layer with its head at the given screen # position and no tail. # # * `screenPosition` A {Point} or point-compatible {Array} # * `options` (optional) An {Object} with the following keys: # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # * `clipDirection` {String} If `'backward'`, returns the first valid # position preceding an invalid position. If `'forward'`, returns the # first valid position following an invalid position. If `'closest'`, # returns the first valid position closest to an invalid position. # Defaults to `'closest'`. # # Returns a {DisplayMarker}. markScreenPosition: (screenPosition, options) -> screenPosition = Point.fromObject(screenPosition) bufferPosition = @displayLayer.translateScreenPosition(screenPosition, options) @getMarker(@bufferMarkerLayer.markPosition(bufferPosition, options).id) # Public: Create a marker with the given buffer range. # # * `range` A {Range} or range-compatible {Array} # * `options` A hash of key-value pairs to associate with the marker. There # are also reserved property names that have marker-specific meaning. # * `reversed` (optional) {Boolean} Creates the marker in a reversed # orientation. (default: false) # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # # Returns a {DisplayMarker}. markBufferRange: (bufferRange, options) -> bufferRange = Range.fromObject(bufferRange) @getMarker(@bufferMarkerLayer.markRange(bufferRange, options).id) # Public: Create a marker on this layer with its head at the given buffer # position and no tail. # # * `bufferPosition` A {Point} or point-compatible {Array} # * `options` (optional) An {Object} with the following keys: # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # # Returns a {DisplayMarker}. markBufferPosition: (bufferPosition, options) -> @getMarker(@bufferMarkerLayer.markPosition(Point.fromObject(bufferPosition), options).id) ### Section: Querying ### # Essential: Get an existing marker by its id. # # Returns a {DisplayMarker}. getMarker: (id) -> if displayMarker = @markersById[id] displayMarker else if bufferMarker = @bufferMarkerLayer.getMarker(id) @markersById[id] = new DisplayMarker(this, bufferMarker) # Essential: Get all markers in the layer. # # Returns an {Array} of {DisplayMarker}s. getMarkers: -> @bufferMarkerLayer.getMarkers().map ({id}) => @getMarker(id) # Public: Get the number of markers in the marker layer. # # Returns a {Number}. getMarkerCount: -> @bufferMarkerLayer.getMarkerCount() # Public: Find markers in the layer conforming to the given parameters. # # This method finds markers based on the given properties. Markers can be # associated with custom properties that will be compared with basic equality. # In addition, there are several special properties that will be compared # with the range of the markers rather than their properties. # # * `properties` An {Object} containing properties that each returned marker # must satisfy. Markers can be associated with custom properties, which are # compared with basic equality. In addition, several reserved properties # can be used to filter markers based on their current range: # * `startBufferPosition` Only include markers starting at this {Point} in buffer coordinates. # * `endBufferPosition` Only include markers ending at this {Point} in buffer coordinates. # * `startScreenPosition` Only include markers starting at this {Point} in screen coordinates. # * `endScreenPosition` Only include markers ending at this {Point} in screen coordinates. # * `startBufferRow` Only include markers starting at this row in buffer coordinates. # * `endBufferRow` Only include markers ending at this row in buffer coordinates. # * `startScreenRow` Only include markers starting at this row in screen coordinates. # * `endScreenRow` Only include markers ending at this row in screen coordinates. # * `intersectsBufferRowRange` Only include markers intersecting this {Array} # of `[startRow, endRow]` in buffer coordinates. # * `intersectsScreenRowRange` Only include markers intersecting this {Array} # of `[startRow, endRow]` in screen coordinates. # * `containsBufferRange` Only include markers containing this {Range} in buffer coordinates. # * `containsBufferPosition` Only include markers containing this {Point} in buffer coordinates. # * `containedInBufferRange` Only include markers contained in this {Range} in buffer coordinates. # * `containedInScreenRange` Only include markers contained in this {Range} in screen coordinates. # * `intersectsBufferRange` Only include markers intersecting this {Range} in buffer coordinates. # * `intersectsScreenRange` Only include markers intersecting this {Range} in screen coordinates. # # Returns an {Array} of {DisplayMarker}s findMarkers: (params) -> params = @translateToBufferMarkerLayerFindParams(params) @bufferMarkerLayer.findMarkers(params).map (stringMarker) => @getMarker(stringMarker.id) ### Section: Private ### translateBufferPosition: (bufferPosition, options) -> @displayLayer.translateBufferPosition(bufferPosition, options) translateBufferRange: (bufferRange, options) -> @displayLayer.translateBufferRange(bufferRange, options) translateScreenPosition: (screenPosition, options) -> @displayLayer.translateScreenPosition(screenPosition, options) translateScreenRange: (screenRange, options) -> @displayLayer.translateScreenRange(screenRange, options) emitDidUpdate: -> @emitter.emit('did-update') notifyObserversIfMarkerScreenPositionsChanged: -> for marker in @getMarkers() marker.notifyObservers(false) return destroyMarker: (id) -> if marker = @markersById[id] marker.didDestroyBufferMarker() didDestroyMarker: (marker) -> @markersWithDestroyListeners.delete(marker) delete @markersById[marker.id] translateToBufferMarkerLayerFindParams: (params) -> bufferMarkerLayerFindParams = {} for key, value of params switch key when 'startBufferPosition' key = 'startPosition' when 'endBufferPosition' key = 'endPosition' when 'startScreenPosition' key = 'startPosition' value = @displayLayer.translateScreenPosition(value) when 'endScreenPosition' key = 'endPosition' value = @displayLayer.translateScreenPosition(value) when 'startBufferRow' key = 'startRow' when 'endBufferRow' key = 'endRow' when 'startScreenRow' key = 'startRow' value = @displayLayer.translateScreenPosition(Point(value, 0)).row when 'endScreenRow' key = 'endRow' value = @displayLayer.translateScreenPosition(Point(value, Infinity)).row when 'intersectsBufferRowRange' key = '<KEY>' when 'intersectsScreenRowRange' key = '<KEY>' [startScreenRow, endScreenRow] = value startBufferRow = @displayLayer.translateScreenPosition(Point(startScreenRow, 0)).row endBufferRow = @displayLayer.translateScreenPosition(Point(endScreenRow, Infinity)).row value = [startBufferRow, endBufferRow] when 'containsBufferRange' key = 'containsRange' when 'containsScreenRange' key = 'containsRange' value = @displayLayer.translateScreenRange(value) when 'containsBufferPosition' key = 'containsPosition' when 'containsScreenPosition' key = 'containsPosition' value = @displayLayer.translateScreenPosition(value) when 'containedInBufferRange' key = 'containedInRange' when 'containedInScreenRange' key = 'containedInRange' value = @displayLayer.translateScreenRange(value) when 'intersectsBufferRange' key = 'intersectsRange' when 'intersectsScreenRange' key = 'intersectsRange' value = @displayLayer.translateScreenRange(value) bufferMarkerLayerFindParams[key] = value bufferMarkerLayerFindParams
true
{Emitter, CompositeDisposable} = require 'event-kit' DisplayMarker = require './display-marker' Range = require './range' Point = require './point' # Public: *Experimental:* A container for a related set of markers at the # {DisplayLayer} level. Wraps an underlying {MarkerLayer} on the {TextBuffer}. # # This API is experimental and subject to change on any release. module.exports = class DisplayMarkerLayer constructor: (@displayLayer, @bufferMarkerLayer, @ownsBufferMarkerLayer) -> {@id} = @bufferMarkerLayer @bufferMarkerLayer.displayMarkerLayers.add(this) @markersById = {} @destroyed = false @emitter = new Emitter @subscriptions = new CompositeDisposable @markersWithDestroyListeners = new Set @subscriptions.add(@bufferMarkerLayer.onDidUpdate(@emitDidUpdate.bind(this))) ### Section: Lifecycle ### # Essential: Destroy this layer. destroy: -> return if @destroyed @destroyed = true @clear() @subscriptions.dispose() @bufferMarkerLayer.displayMarkerLayers.delete(this) @bufferMarkerLayer.destroy() if @ownsBufferMarkerLayer @displayLayer.didDestroyMarkerLayer(@id) @emitter.emit('did-destroy') @emitter.clear() # Public: Destroy all markers in this layer. clear: -> @bufferMarkerLayer.clear() didClearBufferMarkerLayer: -> @markersWithDestroyListeners.forEach (marker) -> marker.didDestroyBufferMarker() @markersById = {} # Essential: Determine whether this layer has been destroyed. # # Returns a {Boolean}. isDestroyed: -> @destroyed ### Section: Event Subscription ### # Public: Subscribe to be notified synchronously when this layer is destroyed. # # Returns a {Disposable}. onDidDestroy: (callback) -> @emitter.on('did-destroy', callback) # Public: Subscribe to be notified asynchronously whenever markers are # created, updated, or destroyed on this layer. *Prefer this method for # optimal performance when interacting with layers that could contain large # numbers of markers.* # # * `callback` A {Function} that will be called with no arguments when changes # occur on this layer. # # Subscribers are notified once, asynchronously when any number of changes # occur in a given tick of the event loop. You should re-query the layer # to determine the state of markers in which you're interested in. It may # be counter-intuitive, but this is much more efficient than subscribing to # events on individual markers, which are expensive to deliver. # # Returns a {Disposable}. onDidUpdate: (callback) -> @emitter.on('did-update', callback) # Public: Subscribe to be notified synchronously whenever markers are created # on this layer. *Avoid this method for optimal performance when interacting # with layers that could contain large numbers of markers.* # # * `callback` A {Function} that will be called with a {TextEditorMarker} # whenever a new marker is created. # # You should prefer {onDidUpdate} when synchronous notifications aren't # absolutely necessary. # # Returns a {Disposable}. onDidCreateMarker: (callback) -> @bufferMarkerLayer.onDidCreateMarker (bufferMarker) => callback(@getMarker(bufferMarker.id)) ### Section: Marker creation ### # Public: Create a marker with the given screen range. # # * `range` A {Range} or range-compatible {Array} # * `options` A hash of key-value pairs to associate with the marker. There # are also reserved property names that have marker-specific meaning. # * `reversed` (optional) {Boolean} Creates the marker in a reversed # orientation. (default: false) # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # * `clipDirection` {String} If `'backward'`, returns the first valid # position preceding an invalid position. If `'forward'`, returns the # first valid position following an invalid position. If `'closest'`, # returns the first valid position closest to an invalid position. # Defaults to `'closest'`. Applies to the start and end of the given range. # # Returns a {DisplayMarker}. markScreenRange: (screenRange, options) -> screenRange = Range.fromObject(screenRange) bufferRange = @displayLayer.translateScreenRange(screenRange, options) @getMarker(@bufferMarkerLayer.markRange(bufferRange, options).id) # Public: Create a marker on this layer with its head at the given screen # position and no tail. # # * `screenPosition` A {Point} or point-compatible {Array} # * `options` (optional) An {Object} with the following keys: # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # * `clipDirection` {String} If `'backward'`, returns the first valid # position preceding an invalid position. If `'forward'`, returns the # first valid position following an invalid position. If `'closest'`, # returns the first valid position closest to an invalid position. # Defaults to `'closest'`. # # Returns a {DisplayMarker}. markScreenPosition: (screenPosition, options) -> screenPosition = Point.fromObject(screenPosition) bufferPosition = @displayLayer.translateScreenPosition(screenPosition, options) @getMarker(@bufferMarkerLayer.markPosition(bufferPosition, options).id) # Public: Create a marker with the given buffer range. # # * `range` A {Range} or range-compatible {Array} # * `options` A hash of key-value pairs to associate with the marker. There # are also reserved property names that have marker-specific meaning. # * `reversed` (optional) {Boolean} Creates the marker in a reversed # orientation. (default: false) # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # # Returns a {DisplayMarker}. markBufferRange: (bufferRange, options) -> bufferRange = Range.fromObject(bufferRange) @getMarker(@bufferMarkerLayer.markRange(bufferRange, options).id) # Public: Create a marker on this layer with its head at the given buffer # position and no tail. # # * `bufferPosition` A {Point} or point-compatible {Array} # * `options` (optional) An {Object} with the following keys: # * `invalidate` (optional) {String} Determines the rules by which changes # to the buffer *invalidate* the marker. (default: 'overlap') It can be # any of the following strategies, in order of fragility: # * __never__: The marker is never marked as invalid. This is a good choice for # markers representing selections in an editor. # * __surround__: The marker is invalidated by changes that completely surround it. # * __overlap__: The marker is invalidated by changes that surround the # start or end of the marker. This is the default. # * __inside__: The marker is invalidated by changes that extend into the # inside of the marker. Changes that end at the marker's start or # start at the marker's end do not invalidate the marker. # * __touch__: The marker is invalidated by a change that touches the marked # region in any way, including changes that end at the marker's # start or start at the marker's end. This is the most fragile strategy. # * `exclusive` {Boolean} indicating whether insertions at the start or end # of the marked range should be interpreted as happening *outside* the # marker. Defaults to `false`, except when using the `inside` # invalidation strategy or when when the marker has no tail, in which # case it defaults to true. Explicitly assigning this option overrides # behavior in all circumstances. # # Returns a {DisplayMarker}. markBufferPosition: (bufferPosition, options) -> @getMarker(@bufferMarkerLayer.markPosition(Point.fromObject(bufferPosition), options).id) ### Section: Querying ### # Essential: Get an existing marker by its id. # # Returns a {DisplayMarker}. getMarker: (id) -> if displayMarker = @markersById[id] displayMarker else if bufferMarker = @bufferMarkerLayer.getMarker(id) @markersById[id] = new DisplayMarker(this, bufferMarker) # Essential: Get all markers in the layer. # # Returns an {Array} of {DisplayMarker}s. getMarkers: -> @bufferMarkerLayer.getMarkers().map ({id}) => @getMarker(id) # Public: Get the number of markers in the marker layer. # # Returns a {Number}. getMarkerCount: -> @bufferMarkerLayer.getMarkerCount() # Public: Find markers in the layer conforming to the given parameters. # # This method finds markers based on the given properties. Markers can be # associated with custom properties that will be compared with basic equality. # In addition, there are several special properties that will be compared # with the range of the markers rather than their properties. # # * `properties` An {Object} containing properties that each returned marker # must satisfy. Markers can be associated with custom properties, which are # compared with basic equality. In addition, several reserved properties # can be used to filter markers based on their current range: # * `startBufferPosition` Only include markers starting at this {Point} in buffer coordinates. # * `endBufferPosition` Only include markers ending at this {Point} in buffer coordinates. # * `startScreenPosition` Only include markers starting at this {Point} in screen coordinates. # * `endScreenPosition` Only include markers ending at this {Point} in screen coordinates. # * `startBufferRow` Only include markers starting at this row in buffer coordinates. # * `endBufferRow` Only include markers ending at this row in buffer coordinates. # * `startScreenRow` Only include markers starting at this row in screen coordinates. # * `endScreenRow` Only include markers ending at this row in screen coordinates. # * `intersectsBufferRowRange` Only include markers intersecting this {Array} # of `[startRow, endRow]` in buffer coordinates. # * `intersectsScreenRowRange` Only include markers intersecting this {Array} # of `[startRow, endRow]` in screen coordinates. # * `containsBufferRange` Only include markers containing this {Range} in buffer coordinates. # * `containsBufferPosition` Only include markers containing this {Point} in buffer coordinates. # * `containedInBufferRange` Only include markers contained in this {Range} in buffer coordinates. # * `containedInScreenRange` Only include markers contained in this {Range} in screen coordinates. # * `intersectsBufferRange` Only include markers intersecting this {Range} in buffer coordinates. # * `intersectsScreenRange` Only include markers intersecting this {Range} in screen coordinates. # # Returns an {Array} of {DisplayMarker}s findMarkers: (params) -> params = @translateToBufferMarkerLayerFindParams(params) @bufferMarkerLayer.findMarkers(params).map (stringMarker) => @getMarker(stringMarker.id) ### Section: Private ### translateBufferPosition: (bufferPosition, options) -> @displayLayer.translateBufferPosition(bufferPosition, options) translateBufferRange: (bufferRange, options) -> @displayLayer.translateBufferRange(bufferRange, options) translateScreenPosition: (screenPosition, options) -> @displayLayer.translateScreenPosition(screenPosition, options) translateScreenRange: (screenRange, options) -> @displayLayer.translateScreenRange(screenRange, options) emitDidUpdate: -> @emitter.emit('did-update') notifyObserversIfMarkerScreenPositionsChanged: -> for marker in @getMarkers() marker.notifyObservers(false) return destroyMarker: (id) -> if marker = @markersById[id] marker.didDestroyBufferMarker() didDestroyMarker: (marker) -> @markersWithDestroyListeners.delete(marker) delete @markersById[marker.id] translateToBufferMarkerLayerFindParams: (params) -> bufferMarkerLayerFindParams = {} for key, value of params switch key when 'startBufferPosition' key = 'startPosition' when 'endBufferPosition' key = 'endPosition' when 'startScreenPosition' key = 'startPosition' value = @displayLayer.translateScreenPosition(value) when 'endScreenPosition' key = 'endPosition' value = @displayLayer.translateScreenPosition(value) when 'startBufferRow' key = 'startRow' when 'endBufferRow' key = 'endRow' when 'startScreenRow' key = 'startRow' value = @displayLayer.translateScreenPosition(Point(value, 0)).row when 'endScreenRow' key = 'endRow' value = @displayLayer.translateScreenPosition(Point(value, Infinity)).row when 'intersectsBufferRowRange' key = 'PI:KEY:<KEY>END_PI' when 'intersectsScreenRowRange' key = 'PI:KEY:<KEY>END_PI' [startScreenRow, endScreenRow] = value startBufferRow = @displayLayer.translateScreenPosition(Point(startScreenRow, 0)).row endBufferRow = @displayLayer.translateScreenPosition(Point(endScreenRow, Infinity)).row value = [startBufferRow, endBufferRow] when 'containsBufferRange' key = 'containsRange' when 'containsScreenRange' key = 'containsRange' value = @displayLayer.translateScreenRange(value) when 'containsBufferPosition' key = 'containsPosition' when 'containsScreenPosition' key = 'containsPosition' value = @displayLayer.translateScreenPosition(value) when 'containedInBufferRange' key = 'containedInRange' when 'containedInScreenRange' key = 'containedInRange' value = @displayLayer.translateScreenRange(value) when 'intersectsBufferRange' key = 'intersectsRange' when 'intersectsScreenRange' key = 'intersectsRange' value = @displayLayer.translateScreenRange(value) bufferMarkerLayerFindParams[key] = value bufferMarkerLayerFindParams
[ { "context": "module.exports = ->\n port: 5000\n\n name: 'Bumpin.js'\n\n hosturl: 'http://localhost:5000'\n cdn: ", "end": 47, "score": 0.46238383650779724, "start": 43, "tag": "NAME", "value": "Bump" }, { "context": "module.exports = ->\n port: 5000\n\n name: 'Bumpin.js'\n\n hosturl: 'http://localhost:5000'\n cdn: './'\n", "end": 52, "score": 0.5030220150947571, "start": 47, "tag": "USERNAME", "value": "in.js" } ]
config.coffee
rongierlach/bumpin.js
0
module.exports = -> port: 5000 name: 'Bumpin.js' hosturl: 'http://localhost:5000' cdn: './' version: '?v=0' env: 'development' title: 'Bumpin.js' site_description: "Affect DOM elements with the Web Audio API" site_keywords: ["bumpin.js", "audio", "visualizer", "dancer", "codepen", "webaudio", "api", "DOM"] google_analytics: 'UA-XXXXXXXX-XX'
185201
module.exports = -> port: 5000 name: '<NAME>in.js' hosturl: 'http://localhost:5000' cdn: './' version: '?v=0' env: 'development' title: 'Bumpin.js' site_description: "Affect DOM elements with the Web Audio API" site_keywords: ["bumpin.js", "audio", "visualizer", "dancer", "codepen", "webaudio", "api", "DOM"] google_analytics: 'UA-XXXXXXXX-XX'
true
module.exports = -> port: 5000 name: 'PI:NAME:<NAME>END_PIin.js' hosturl: 'http://localhost:5000' cdn: './' version: '?v=0' env: 'development' title: 'Bumpin.js' site_description: "Affect DOM elements with the Web Audio API" site_keywords: ["bumpin.js", "audio", "visualizer", "dancer", "codepen", "webaudio", "api", "DOM"] google_analytics: 'UA-XXXXXXXX-XX'
[ { "context": "###\n mapscii - Terminal Map Viewer\n by Michael Strassburger <codepoet@cpan.org>\n\n UI and central command cen", "end": 61, "score": 0.9998716115951538, "start": 41, "tag": "NAME", "value": "Michael Strassburger" }, { "context": " - Terminal Map Viewer\n by Michael Strassburger <codepoet@cpan.org>\n\n UI and central command center\n###\n\nkeypress =", "end": 80, "score": 0.9999324083328247, "start": 63, "tag": "EMAIL", "value": "codepoet@cpan.org" } ]
src/Mapscii.coffee
82ndAirborneDiv/mapsc
1
### mapscii - Terminal Map Viewer by Michael Strassburger <codepoet@cpan.org> UI and central command center ### keypress = require 'keypress' TermMouse = require 'term-mouse' Promise = require 'bluebird' Renderer = require './Renderer' TileSource = require './TileSource' utils = require './utils' config = require './config' module.exports = class Mapscii width: null height: null canvas: null mouse: null mouseDragging: false mousePosition: x: 0, y: 0 tileSource: null renderer: null zoom: 0 center: # sf lat: 37.787946, lon: -122.407522 # iceland lat: 64.124229, lon: -21.811552 # rgbg # lat: 49.019493, lon: 12.098341 lat: 52.51298, lon: 13.42012 minZoom: null constructor: (options) -> config[key] = val for key, val of options init: -> Promise .resolve() .then => unless config.headless @_initKeyboard() @_initMouse() @_initTileSource() .then => @_initRenderer() .then => @_draw() .then => @notify("Welcome to MapSCII! Use your cursors to navigate, a/z to zoom, q to quit.") _initTileSource: -> @tileSource = new TileSource() @tileSource.init config.source _initKeyboard: -> keypress config.input config.input.setRawMode true if config.input.setRawMode config.input.resume() config.input.on 'keypress', (ch, key) => @_onKey key _initMouse: -> @mouse = TermMouse input: config.input, output: config.output @mouse.start() @mouse.on 'click', (event) => @_onClick event @mouse.on 'scroll', (event) => @_onMouseScroll event @mouse.on 'move', (event) => @_onMouseMove event _initRenderer: -> @renderer = new Renderer config.output, @tileSource @renderer.loadStyleFile config.styleFile config.output.on 'resize', => @_resizeRenderer() @_draw() @_resizeRenderer() @zoom = if config.initialZoom isnt null then config.initialZoom else @minZoom _resizeRenderer: (cb) -> if config.size @width = config.size.width @height = config.size.height else @width = config.output.columns >> 1 << 2 @height = config.output.rows * 4 - 4 @minZoom = 4-Math.log(4096/@width)/Math.LN2 @renderer.setSize @width, @height _updateMousePosition: (event) -> projected = x: (event.x-.5)*2 y: (event.y-.5)*4 size = utils.tilesizeAtZoom @zoom [dx, dy] = [projected.x-@width/2, projected.y-@height/2] z = utils.baseZoom @zoom center = utils.ll2tile @center.lon, @center.lat, z @mousePosition = utils.normalize utils.tile2ll center.x+(dx/size), center.y+(dy/size), z _onClick: (event) -> return if event.x < 0 or event.x > @width/2 or event.y < 0 or event.y > @height/4 @_updateMousePosition event if @mouseDragging and event.button is "left" @mouseDragging = false else @setCenter @mousePosition.lat, @mousePosition.lon @_draw() _onMouseScroll: (event) -> @_updateMousePosition event # TODO: handle .x/y for directed zoom @zoomBy config.zoomStep * if event.button is "up" then 1 else -1 @_draw() _onMouseMove: (event) -> return if event.x < 0 or event.x > @width/2 or event.y < 0 or event.y > @height/4 return if config.mouseCallback and not config.mouseCallback event # start dragging if event.button is "left" if @mouseDragging dx = (@mouseDragging.x-event.x)*2 dy = (@mouseDragging.y-event.y)*4 size = utils.tilesizeAtZoom @zoom newCenter = utils.tile2ll @mouseDragging.center.x+(dx/size), @mouseDragging.center.y+(dy/size), utils.baseZoom(@zoom) @setCenter newCenter.lat, newCenter.lon @_draw() else @mouseDragging = x: event.x, y: event.y, center: utils.ll2tile @center.lon, @center.lat, utils.baseZoom(@zoom) @_updateMousePosition event @notify @_getFooter() _onKey: (key) -> if config.keyCallback and not config.keyCallback key return # check if the pressed key is configured draw = switch key?.name when "q" if config.quitCallback config.quitCallback() else process.exit 0 when "a" then @zoomBy config.zoomStep when "z", "y" @zoomBy -config.zoomStep when "left" then @moveBy 0, -8/Math.pow(2, @zoom) when "right" then @moveBy 0, 8/Math.pow(2, @zoom) when "up" then @moveBy 6/Math.pow(2, @zoom), 0 when "down" then @moveBy -6/Math.pow(2, @zoom), 0 when "c" config.useBraille = !config.useBraille true else null if draw isnt null @_draw() _draw: -> @renderer .draw @center, @zoom .then (frame) => @_write frame @notify @_getFooter() .catch => @notify "renderer is busy" _getFooter: -> # tile = utils.ll2tile @center.lon, @center.lat, @zoom # "tile: #{utils.digits tile.x, 3}, #{utils.digits tile.x, 3} "+ "center: #{utils.digits @center.lat, 3}, #{utils.digits @center.lon, 3} "+ "zoom: #{utils.digits @zoom, 2} "+ "mouse: #{utils.digits @mousePosition.lat, 3}, #{utils.digits @mousePosition.lon, 3} " notify: (text) -> config.onUpdate() if config.onUpdate @_write "\r\x1B[K"+text unless config.headless _write: (output) -> config.output.write output zoomBy: (step) -> return @zoom = @minZoom if @zoom+step < @minZoom return @zoom = config.maxZoom if @zoom+step > config.maxZoom @zoom += step moveBy: (lat, lon) -> @setCenter @center.lat+lat, @center.lon+lon setCenter: (lat, lon) -> @center = utils.normalize lon: lon, lat: lat
189652
### mapscii - Terminal Map Viewer by <NAME> <<EMAIL>> UI and central command center ### keypress = require 'keypress' TermMouse = require 'term-mouse' Promise = require 'bluebird' Renderer = require './Renderer' TileSource = require './TileSource' utils = require './utils' config = require './config' module.exports = class Mapscii width: null height: null canvas: null mouse: null mouseDragging: false mousePosition: x: 0, y: 0 tileSource: null renderer: null zoom: 0 center: # sf lat: 37.787946, lon: -122.407522 # iceland lat: 64.124229, lon: -21.811552 # rgbg # lat: 49.019493, lon: 12.098341 lat: 52.51298, lon: 13.42012 minZoom: null constructor: (options) -> config[key] = val for key, val of options init: -> Promise .resolve() .then => unless config.headless @_initKeyboard() @_initMouse() @_initTileSource() .then => @_initRenderer() .then => @_draw() .then => @notify("Welcome to MapSCII! Use your cursors to navigate, a/z to zoom, q to quit.") _initTileSource: -> @tileSource = new TileSource() @tileSource.init config.source _initKeyboard: -> keypress config.input config.input.setRawMode true if config.input.setRawMode config.input.resume() config.input.on 'keypress', (ch, key) => @_onKey key _initMouse: -> @mouse = TermMouse input: config.input, output: config.output @mouse.start() @mouse.on 'click', (event) => @_onClick event @mouse.on 'scroll', (event) => @_onMouseScroll event @mouse.on 'move', (event) => @_onMouseMove event _initRenderer: -> @renderer = new Renderer config.output, @tileSource @renderer.loadStyleFile config.styleFile config.output.on 'resize', => @_resizeRenderer() @_draw() @_resizeRenderer() @zoom = if config.initialZoom isnt null then config.initialZoom else @minZoom _resizeRenderer: (cb) -> if config.size @width = config.size.width @height = config.size.height else @width = config.output.columns >> 1 << 2 @height = config.output.rows * 4 - 4 @minZoom = 4-Math.log(4096/@width)/Math.LN2 @renderer.setSize @width, @height _updateMousePosition: (event) -> projected = x: (event.x-.5)*2 y: (event.y-.5)*4 size = utils.tilesizeAtZoom @zoom [dx, dy] = [projected.x-@width/2, projected.y-@height/2] z = utils.baseZoom @zoom center = utils.ll2tile @center.lon, @center.lat, z @mousePosition = utils.normalize utils.tile2ll center.x+(dx/size), center.y+(dy/size), z _onClick: (event) -> return if event.x < 0 or event.x > @width/2 or event.y < 0 or event.y > @height/4 @_updateMousePosition event if @mouseDragging and event.button is "left" @mouseDragging = false else @setCenter @mousePosition.lat, @mousePosition.lon @_draw() _onMouseScroll: (event) -> @_updateMousePosition event # TODO: handle .x/y for directed zoom @zoomBy config.zoomStep * if event.button is "up" then 1 else -1 @_draw() _onMouseMove: (event) -> return if event.x < 0 or event.x > @width/2 or event.y < 0 or event.y > @height/4 return if config.mouseCallback and not config.mouseCallback event # start dragging if event.button is "left" if @mouseDragging dx = (@mouseDragging.x-event.x)*2 dy = (@mouseDragging.y-event.y)*4 size = utils.tilesizeAtZoom @zoom newCenter = utils.tile2ll @mouseDragging.center.x+(dx/size), @mouseDragging.center.y+(dy/size), utils.baseZoom(@zoom) @setCenter newCenter.lat, newCenter.lon @_draw() else @mouseDragging = x: event.x, y: event.y, center: utils.ll2tile @center.lon, @center.lat, utils.baseZoom(@zoom) @_updateMousePosition event @notify @_getFooter() _onKey: (key) -> if config.keyCallback and not config.keyCallback key return # check if the pressed key is configured draw = switch key?.name when "q" if config.quitCallback config.quitCallback() else process.exit 0 when "a" then @zoomBy config.zoomStep when "z", "y" @zoomBy -config.zoomStep when "left" then @moveBy 0, -8/Math.pow(2, @zoom) when "right" then @moveBy 0, 8/Math.pow(2, @zoom) when "up" then @moveBy 6/Math.pow(2, @zoom), 0 when "down" then @moveBy -6/Math.pow(2, @zoom), 0 when "c" config.useBraille = !config.useBraille true else null if draw isnt null @_draw() _draw: -> @renderer .draw @center, @zoom .then (frame) => @_write frame @notify @_getFooter() .catch => @notify "renderer is busy" _getFooter: -> # tile = utils.ll2tile @center.lon, @center.lat, @zoom # "tile: #{utils.digits tile.x, 3}, #{utils.digits tile.x, 3} "+ "center: #{utils.digits @center.lat, 3}, #{utils.digits @center.lon, 3} "+ "zoom: #{utils.digits @zoom, 2} "+ "mouse: #{utils.digits @mousePosition.lat, 3}, #{utils.digits @mousePosition.lon, 3} " notify: (text) -> config.onUpdate() if config.onUpdate @_write "\r\x1B[K"+text unless config.headless _write: (output) -> config.output.write output zoomBy: (step) -> return @zoom = @minZoom if @zoom+step < @minZoom return @zoom = config.maxZoom if @zoom+step > config.maxZoom @zoom += step moveBy: (lat, lon) -> @setCenter @center.lat+lat, @center.lon+lon setCenter: (lat, lon) -> @center = utils.normalize lon: lon, lat: lat
true
### mapscii - Terminal Map Viewer by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> UI and central command center ### keypress = require 'keypress' TermMouse = require 'term-mouse' Promise = require 'bluebird' Renderer = require './Renderer' TileSource = require './TileSource' utils = require './utils' config = require './config' module.exports = class Mapscii width: null height: null canvas: null mouse: null mouseDragging: false mousePosition: x: 0, y: 0 tileSource: null renderer: null zoom: 0 center: # sf lat: 37.787946, lon: -122.407522 # iceland lat: 64.124229, lon: -21.811552 # rgbg # lat: 49.019493, lon: 12.098341 lat: 52.51298, lon: 13.42012 minZoom: null constructor: (options) -> config[key] = val for key, val of options init: -> Promise .resolve() .then => unless config.headless @_initKeyboard() @_initMouse() @_initTileSource() .then => @_initRenderer() .then => @_draw() .then => @notify("Welcome to MapSCII! Use your cursors to navigate, a/z to zoom, q to quit.") _initTileSource: -> @tileSource = new TileSource() @tileSource.init config.source _initKeyboard: -> keypress config.input config.input.setRawMode true if config.input.setRawMode config.input.resume() config.input.on 'keypress', (ch, key) => @_onKey key _initMouse: -> @mouse = TermMouse input: config.input, output: config.output @mouse.start() @mouse.on 'click', (event) => @_onClick event @mouse.on 'scroll', (event) => @_onMouseScroll event @mouse.on 'move', (event) => @_onMouseMove event _initRenderer: -> @renderer = new Renderer config.output, @tileSource @renderer.loadStyleFile config.styleFile config.output.on 'resize', => @_resizeRenderer() @_draw() @_resizeRenderer() @zoom = if config.initialZoom isnt null then config.initialZoom else @minZoom _resizeRenderer: (cb) -> if config.size @width = config.size.width @height = config.size.height else @width = config.output.columns >> 1 << 2 @height = config.output.rows * 4 - 4 @minZoom = 4-Math.log(4096/@width)/Math.LN2 @renderer.setSize @width, @height _updateMousePosition: (event) -> projected = x: (event.x-.5)*2 y: (event.y-.5)*4 size = utils.tilesizeAtZoom @zoom [dx, dy] = [projected.x-@width/2, projected.y-@height/2] z = utils.baseZoom @zoom center = utils.ll2tile @center.lon, @center.lat, z @mousePosition = utils.normalize utils.tile2ll center.x+(dx/size), center.y+(dy/size), z _onClick: (event) -> return if event.x < 0 or event.x > @width/2 or event.y < 0 or event.y > @height/4 @_updateMousePosition event if @mouseDragging and event.button is "left" @mouseDragging = false else @setCenter @mousePosition.lat, @mousePosition.lon @_draw() _onMouseScroll: (event) -> @_updateMousePosition event # TODO: handle .x/y for directed zoom @zoomBy config.zoomStep * if event.button is "up" then 1 else -1 @_draw() _onMouseMove: (event) -> return if event.x < 0 or event.x > @width/2 or event.y < 0 or event.y > @height/4 return if config.mouseCallback and not config.mouseCallback event # start dragging if event.button is "left" if @mouseDragging dx = (@mouseDragging.x-event.x)*2 dy = (@mouseDragging.y-event.y)*4 size = utils.tilesizeAtZoom @zoom newCenter = utils.tile2ll @mouseDragging.center.x+(dx/size), @mouseDragging.center.y+(dy/size), utils.baseZoom(@zoom) @setCenter newCenter.lat, newCenter.lon @_draw() else @mouseDragging = x: event.x, y: event.y, center: utils.ll2tile @center.lon, @center.lat, utils.baseZoom(@zoom) @_updateMousePosition event @notify @_getFooter() _onKey: (key) -> if config.keyCallback and not config.keyCallback key return # check if the pressed key is configured draw = switch key?.name when "q" if config.quitCallback config.quitCallback() else process.exit 0 when "a" then @zoomBy config.zoomStep when "z", "y" @zoomBy -config.zoomStep when "left" then @moveBy 0, -8/Math.pow(2, @zoom) when "right" then @moveBy 0, 8/Math.pow(2, @zoom) when "up" then @moveBy 6/Math.pow(2, @zoom), 0 when "down" then @moveBy -6/Math.pow(2, @zoom), 0 when "c" config.useBraille = !config.useBraille true else null if draw isnt null @_draw() _draw: -> @renderer .draw @center, @zoom .then (frame) => @_write frame @notify @_getFooter() .catch => @notify "renderer is busy" _getFooter: -> # tile = utils.ll2tile @center.lon, @center.lat, @zoom # "tile: #{utils.digits tile.x, 3}, #{utils.digits tile.x, 3} "+ "center: #{utils.digits @center.lat, 3}, #{utils.digits @center.lon, 3} "+ "zoom: #{utils.digits @zoom, 2} "+ "mouse: #{utils.digits @mousePosition.lat, 3}, #{utils.digits @mousePosition.lon, 3} " notify: (text) -> config.onUpdate() if config.onUpdate @_write "\r\x1B[K"+text unless config.headless _write: (output) -> config.output.write output zoomBy: (step) -> return @zoom = @minZoom if @zoom+step < @minZoom return @zoom = config.maxZoom if @zoom+step > config.maxZoom @zoom += step moveBy: (lat, lon) -> @setCenter @center.lat+lat, @center.lon+lon setCenter: (lat, lon) -> @center = utils.normalize lon: lon, lat: lat
[ { "context": ": ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'No", "end": 1349, "score": 0.9301509857177734, "start": 1344, "tag": "NAME", "value": "Junio" }, { "context": "', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre',", "end": 1358, "score": 0.9294619560241699, "start": 1353, "tag": "NAME", "value": "Julio" }, { "context": "ro', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciemb", "end": 1367, "score": 0.7413101196289062, "start": 1362, "tag": "NAME", "value": "Agost" }, { "context": "', 'Diciembre']\r\n 'PL': ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Si", "end": 1459, "score": 0.579677939414978, "start": 1456, "tag": "NAME", "value": "Mar" }, { "context": "bre']\r\n 'PL': ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzes", "end": 1474, "score": 0.9403043985366821, "start": 1466, "tag": "NAME", "value": "Kwiecień" }, { "context": " 'PL': ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', '", "end": 1481, "score": 0.9886214733123779, "start": 1478, "tag": "NAME", "value": "Maj" }, { "context": "['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik'", "end": 1493, "score": 0.9616556167602539, "start": 1485, "tag": "NAME", "value": "Czerwiec" }, { "context": "'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopa", "end": 1503, "score": 0.9424172043800354, "start": 1497, "tag": "NAME", "value": "Lipiec" }, { "context": "arzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzie", "end": 1515, "score": 0.9626348614692688, "start": 1507, "tag": "NAME", "value": "Sierpień" }, { "context": "ecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień']\r\n\r\n\r\n c", "end": 1527, "score": 0.9558936953544617, "start": 1519, "tag": "NAME", "value": "Wrzesień" }, { "context": "', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień']\r\n\r\n\r\n constToHumanStri", "end": 1542, "score": 0.9982365965843201, "start": 1531, "tag": "NAME", "value": "Październik" }, { "context": "'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień']\r\n\r\n\r\n constToHumanString: (constan", "end": 1554, "score": 0.7350625395774841, "start": 1546, "tag": "NAME", "value": "Listopad" } ]
app/assets/javascripts/actionable/core/constants.js.coffee
pawelszymanski/actionable-gem
1
class Constants constructor: -> @STRING = '_string' @INTEGER_POSITIVE = '_integer_positive' @INTEGER_NOT_NEGATIVE = '_integer_not_negative' @BOOLEAN = '_boolean' @REGEXP = '_regexp' @REQUIRED = '_required' @SELECTOR = '_selector' @SELF = '_self' @EMPTY = '' @RESTORE = '_restore' @REPLACE = '_replace' @DAYS_OF_WEEK = 'EN': ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] 'DE': ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] 'FR': ['Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa', 'Di'] 'IT': ['Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa', 'Do'] 'ES': ['Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá', 'Do'] 'PL': ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'N'] @MONTHS = 'EN': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] 'DE': ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'] 'FR': ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'] 'IT': ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'] 'ES': ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'] 'PL': ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'] constToHumanString: (constant) => return 'empty' if constant is @EMPTY return '?' @Constants = new Constants
218901
class Constants constructor: -> @STRING = '_string' @INTEGER_POSITIVE = '_integer_positive' @INTEGER_NOT_NEGATIVE = '_integer_not_negative' @BOOLEAN = '_boolean' @REGEXP = '_regexp' @REQUIRED = '_required' @SELECTOR = '_selector' @SELF = '_self' @EMPTY = '' @RESTORE = '_restore' @REPLACE = '_replace' @DAYS_OF_WEEK = 'EN': ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] 'DE': ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] 'FR': ['Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa', 'Di'] 'IT': ['Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa', 'Do'] 'ES': ['Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá', 'Do'] 'PL': ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'N'] @MONTHS = 'EN': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] 'DE': ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'] 'FR': ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'] 'IT': ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'] 'ES': ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', '<NAME>', '<NAME>', '<NAME>o', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'] 'PL': ['Styczeń', 'Luty', '<NAME>zec', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Grudzień'] constToHumanString: (constant) => return 'empty' if constant is @EMPTY return '?' @Constants = new Constants
true
class Constants constructor: -> @STRING = '_string' @INTEGER_POSITIVE = '_integer_positive' @INTEGER_NOT_NEGATIVE = '_integer_not_negative' @BOOLEAN = '_boolean' @REGEXP = '_regexp' @REQUIRED = '_required' @SELECTOR = '_selector' @SELF = '_self' @EMPTY = '' @RESTORE = '_restore' @REPLACE = '_replace' @DAYS_OF_WEEK = 'EN': ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] 'DE': ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] 'FR': ['Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa', 'Di'] 'IT': ['Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa', 'Do'] 'ES': ['Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá', 'Do'] 'PL': ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'N'] @MONTHS = 'EN': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] 'DE': ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'] 'FR': ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'] 'IT': ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'] 'ES': ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PIo', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'] 'PL': ['Styczeń', 'Luty', 'PI:NAME:<NAME>END_PIzec', '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', 'Grudzień'] constToHumanString: (constant) => return 'empty' if constant is @EMPTY return '?' @Constants = new Constants
[ { "context": "ole.log sentence()\n\nclass Person\n constructor: (@name) ->\n\n greet: ->\n Action.say -> \"My name is #{", "end": 97, "score": 0.8354071378707886, "start": 93, "tag": "USERNAME", "value": "name" }, { "context": "ame) ->\n\n greet: ->\n Action.say -> \"My name is #{@name}!\"\n Action.say => \"My name is #{@name}!\"\n\n", "end": 144, "score": 0.697166919708252, "start": 144, "tag": "NAME", "value": "" }, { "context": " ->\n\n greet: ->\n Action.say -> \"My name is #{@name}!\"\n Action.say => \"My name is #{@name}!\"\n\nnew ", "end": 152, "score": 0.9873575568199158, "start": 148, "tag": "USERNAME", "value": "name" }, { "context": "y name is #{@name}!\"\n Action.say => \"My name is #{@name}!\"\n\nnew Person('Alex').greet()\n", "end": 185, "score": 0.540774405002594, "start": 185, "tag": "NAME", "value": "" }, { "context": "me is #{@name}!\"\n Action.say => \"My name is #{@name}!\"\n\nnew Person('Alex').greet()\n", "end": 193, "score": 0.9920147657394409, "start": 189, "tag": "USERNAME", "value": "name" }, { "context": "Action.say => \"My name is #{@name}!\"\n\nnew Person('Alex').greet()\n", "end": 214, "score": 0.9731804132461548, "start": 210, "tag": "NAME", "value": "Alex" } ]
code/coffeescript/method-block-binding.coffee
evmorov/ruby-coffeescript
29
class Action @say: (sentence) -> console.log sentence() class Person constructor: (@name) -> greet: -> Action.say -> "My name is #{@name}!" Action.say => "My name is #{@name}!" new Person('Alex').greet()
112558
class Action @say: (sentence) -> console.log sentence() class Person constructor: (@name) -> greet: -> Action.say -> "My name is<NAME> #{@name}!" Action.say => "My name is<NAME> #{@name}!" new Person('<NAME>').greet()
true
class Action @say: (sentence) -> console.log sentence() class Person constructor: (@name) -> greet: -> Action.say -> "My name isPI:NAME:<NAME>END_PI #{@name}!" Action.say => "My name isPI:NAME:<NAME>END_PI #{@name}!" new Person('PI:NAME:<NAME>END_PI').greet()
[ { "context": "# Author: Vishnu Raghav B\n# apps@vishnuraghav.com\n\n# NativeScript-Vue snipp", "end": 25, "score": 0.9998897910118103, "start": 10, "tag": "NAME", "value": "Vishnu Raghav B" }, { "context": "# Author: Vishnu Raghav B\n# apps@vishnuraghav.com\n\n# NativeScript-Vue snippets\n\n\n'.text.html.vue':\n", "end": 49, "score": 0.9999295473098755, "start": 28, "tag": "EMAIL", "value": "apps@vishnuraghav.com" }, { "context": "our Cancel button text\",\n userName: \"Username field value\",\n password: \"Password field value\"\n", "end": 17677, "score": 0.9315641522407532, "start": 17657, "tag": "USERNAME", "value": "Username field value" }, { "context": " \"Username field value\",\n password: \"Password field value\"\n }).then(result => {\n co", "end": 17725, "score": 0.9993574619293213, "start": 17705, "tag": "PASSWORD", "value": "Password field value" } ]
snippets/nativescript-vue-atom-snippets.cson
vishnuraghavb/nativescript-vue-atom-snippets
0
# Author: Vishnu Raghav B # apps@vishnuraghav.com # NativeScript-Vue snippets '.text.html.vue': # Layouts '{N}-vue AbsoluteLayout': 'prefix': 'nsabsolute' 'body': """ <AbsoluteLayout> $1 </AbsoluteLayout> """ '{N}-vue DockLayout': 'prefix': 'nsdock' 'body': """ <DockLayout stretchLastChild="true"> $1 </DockLayout> """ '{N}-vue FlexboxLayout': 'prefix': 'nsflex' 'body': """ <FlexboxLayout flexDirection="row" flexWrap="nowrap" justifyContent="flex-start" alignItems="stretch" alignContent="stretch"> $1 </FlexboxLayout> """ '{N}-vue GridLayout': 'prefix': 'nsgrid' 'body': """ <GridLayout columns="$1" rows="$2"> $3 </GridLayout> """ '{N}-vue StackLayout': 'prefix': 'nsstack' 'body': """ <StackLayout orientation="vertical"> $1 </StackLayout> """ '{N}-vue WrapLayout': 'prefix': 'nswrap' 'body': """ <WrapLayout orientation="horizontal" itemWidth="$1" itemHeight="$2"> $2 </WrapLayout> """ # Action-Bar '{N}-vue ActionBar': 'prefix': 'nsactionbar' 'body': """ <ActionBar title="$1" android.icon="" flat="false" > <NavigationButton text="Back" android.systemIcon="ic_menu_back" @tap="$2" /> <ActionItem icon="" text="Left" ios.position="left" @tap="" /> <ActionItem icon="" text="Right" ios.position="right" @tap="" /> </ActionBar> """ # Components '{N}-vue ActivityIndicator': 'prefix': 'nsloading' 'body': """ <ActivityIndicator busy="true" @busyChange="onBusyChanged" /> """ '{N}-vue Button': 'prefix': 'nsbutton' 'body': """ <Button text="$1" @tap="onButtonTap" /> """ '{N}-vue DatePicker': 'prefix': 'nsdate' 'body': """ <DatePicker date="$1" /> """ '{N}-vue Frame': 'prefix': 'nsframe' 'body': """ <Frame> <Page> <ActionBar title="Default Page Title" /> <GridLayout> <Label text="Default Page Content" /> </GridLayout> </Page> </Frame> """ '{N}-vue HtmlView': 'prefix': 'nshtml' 'body': """ <HtmlView html="<div><h1>HtmlView</h1></div>" /> """ '{N}-vue Image': 'prefix': 'nsimg' 'body': """ <Image src="$1" stretch="none" /> """ '{N}-vue Label': 'prefix': 'nslabel' 'body': """ <Label text="$1" textWrap="false"/> """ '{N}-vue ListPicker': 'prefix': 'nslistpicker' 'body': """ <ListPicker :items="listOfItems" selectedIndex="0" @selectedIndexChange="selectedIndexChanged" /> """ '{N}-vue ListView': 'prefix': 'nslistview' 'body': """ <ListView for="item in listOfItems" @itemTap="onItemTap"> <v-template> <Label :text="item.text" /> </v-template> </ListView> """ '{N}-vue Page': 'prefix': 'nspage' 'body': """ <Page actionBarHidden="false"> <ActionBar title="My App" /> <GridLayout> <Label text="My Content"/> </GridLayout> </Page> """ '{N}-vue Placeholder': 'prefix': 'nsplaceholder' 'body': """ <Placeholder @creatingView="creatingView" /> """ '{N}-vue Progress': 'prefix': 'nsprogress' 'body': """ <Progress :value="currentProgress" /> """ '{N}-vue ScrollView': 'prefix': 'nsscrollview' 'body': """ <ScrollView orientation="horizontal" scrollBarIndicatorVisible="true"> $1 </ScrollView> """ '{N}-vue SearchBar': 'prefix': 'nssearchbar' 'body': """ <SearchBar hint="$1" :text="searchPhrase" @textChange="onTextChanged" @submit="onSubmit" /> """ '{N}-vue SegmentedBar': 'prefix': 'nssegmentedbar' 'body': """ <SegmentedBar :items="listOfItems" selectedIndex="0" @selectedIndexChange="onSelectedIndexChange" /> """ '{N}-vue Slider': 'prefix': 'nsslider' 'body': """ <Slider value="$1" @valueChange="onValueChanged" /> """ '{N}-vue Switch': 'prefix': 'nsswitch' 'body': """ <Switch checked="true" /> """ '{N}-vue TabView': 'prefix': 'nstabview' 'body': """ <TabView :selectedIndex="selectedIndex" @selectedIndexChange="indexChange"> <TabViewItem title="Tab 1"> <Label text="Content for Tab 1" /> </TabViewItem> <TabViewItem title="Tab 2"> <Label text="Content for Tab 2" /> </TabViewItem> </TabView> """ '{N}-vue Tabs': 'prefix': 'nstabs' 'body': """ <Tabs> <TabStrip> <TabStripItem> <Label text="Tab 1"></Label> <Image src=""></Image> </TabStripItem> <TabStripItem> <Label text="Tab 2"></Label> <Image src=""></Image> </TabStripItem> </TabStrip> <TabContentItem> <GridLayout> <Label text="Content for Tab 1"></Label> </GridLayout> </TabContentItem> <TabContentItem> <GridLayout> <Label text="Content for Tab 2"></Label> </GridLayout> </TabContentItem> </Tabs> """ '{N}-vue BottomNavigation': 'prefix': 'nsbottomnavigation' 'body': """ <BottomNavigation> <TabStrip> <TabStripItem> <Label text="Tab 1"></Label> <Image src=""></Image> </TabStripItem> <TabStripItem> <Label text="Tab 2"></Label> <Image src=""></Image> </TabStripItem> </TabStrip> <TabContentItem> <GridLayout> <Label text="Content for Tab 1"></Label> </GridLayout> </TabContentItem> <TabContentItem> <GridLayout> <Label text="Content for Tab 2"></Label> </GridLayout> </TabContentItem> </BottomNavigation> """ '{N}-vue TextField': 'prefix': 'nstextfield' 'body': """ <TextField text="$1" editable="true" returnKeyType="next" /> """ '{N}-vue TextView': 'prefix': 'nstextview' 'body': """ <TextView text="$1" editable="true" /> """ '{N}-vue TimePicker': 'prefix': 'nstime' 'body': """ <TimePicker :hour="selectedHour" :minute="selectedMinute" /> """ '{N}-vue WebView': 'prefix': 'nswebview' 'body': """ <WebView src="$1" /> """ '{N}-vue FormattedString': 'prefix': 'nsformattedstring' 'body': """ <FormattedString> <Span text="This text has a " /> <Span text="red " style="color: red" /> <Span text="piece of text. " /> <Span text="Also, this bit is italic, " fontStyle="italic" /> <Span text="and this bit is bold." fontWeight="bold" /> </FormattedString> """ # Attributes '{N} Width Attribute': 'prefix': 'width' 'body': 'width="$1"$2' '{N} Height Attribute': 'prefix': 'height' 'body': 'height="$1"$2' '{N} Text Attribute': 'prefix': 'text' 'body': 'text="$1"$2' '{N} Icon Attribute': 'prefix': 'icon' 'body': 'icon="res://$1"$2' '{N} Text Wrap Attribute': 'prefix': 'wrap' 'body': 'textWrap="true"$2' '{N} Horizontal Alignment Attribute': 'prefix': 'halign' 'body': 'horizontalAlignment="center$1"$2' '{N} Vertical Alignment Attribute': 'prefix': 'valign' 'body': 'verticalAlignment="center$1"$2' '{N} Visibility Attribute': 'prefix': 'visibility' 'body': 'visibility="collapsed$1"$2' '{N} Stretch Attribute': 'prefix': 'stretch' 'body': 'stretch="fill$1"$2' '{N} Keyboard Type Attribute': 'prefix': 'kbtype' 'body': 'keyboardType="email$1"$2' '{N} Row Attribute': 'prefix': 'row' 'body': 'row="$1"$2' '{N} Column Attribute': 'prefix': 'col' 'body': 'col="$1"$2' '{N} Rows Attribute': 'prefix': 'rows' 'body': 'rows="$1"$2' '{N} Columns Attribute': 'prefix': 'columns' 'body': 'columns="$1"$2' '{N} Rowspan Attribute': 'prefix': 'rowSpan' 'body': 'rowSpan="$1"$2' '{N} Colspan Attribute': 'prefix': 'colSpan' 'body': 'colSpan="$1" $2' '{N} stretchLastChild Attribute': 'prefix': 'stretchLastChild' 'body': 'stretchLastChild="true$1"$2' '{N} flexDirection Attribute': 'prefix': 'flexDirection' 'body': 'flexDirection="column$1"$2' '{N} flexWrap Attribute': 'prefix': 'flexWrap' 'body': 'flexWrap="wrap$1"$2' '{N} justifyContent Attribute': 'prefix': 'justifyContent' 'body': 'justifyContent="center$1"$2' '{N} alignItems Attribute': 'prefix': 'alignItems' 'body': 'alignItems="center$1"$2' '{N} alignContent Attribute': 'prefix': 'alignContent' 'body': 'alignContent="center$1"$2' '{N} order Attribute': 'prefix': 'order' 'body': 'order="$1"$2' '{N} flexGrow Attribute': 'prefix': 'flexGrow' 'body': 'flexGrow="$1"$2' '{N} flexShrink Attribute': 'prefix': 'flexShrink' 'body': 'flexShrink="$1"$2' '{N} alignSelf Attribute': 'prefix': 'alignSelf' 'body': 'alignSelf="center$1"$2' '{N} flexWrapBefore Attribute': 'prefix': 'flexWrapBefore' 'body': 'flexWrapBefore="center$1"$2' '{N} dock Attribute': 'prefix': 'dock' 'body': 'dock="top$1"$2' '{N} orientation Attribute': 'prefix': 'orientation' 'body': 'orientation="horizontal$1"$2' '{N} itemWidth Attribute': 'prefix': 'itemWidth' 'body': 'itemWidth="$1"$2' '{N} itemHeight Attribute': 'prefix': 'itemHeight' 'body': 'itemHeight="$1"$2' '{N} flat Attribute': 'prefix': 'flat' 'body': 'flat="true$1"$2' '{N} busy Attribute': 'prefix': 'busy' 'body': 'busy="true$1"$2' '{N} isEnabled Attribute': 'prefix': 'isEnabled' 'body': 'isEnabled="false$1"$2' '{N} minDate Attribute': 'prefix': 'minDate' 'body': 'minDate="$1"$2' '{N} maxDate Attribute': 'prefix': 'maxDate' 'body': 'maxDate="$1"$2' '{N} src Attribute': 'prefix': 'src' 'body': 'src="$1"$2' '{N} imageSource Attribute': 'prefix': 'imageSource' 'body': 'imageSource="$1"$2' '{N} tintColor Attribute': 'prefix': 'tintColor' 'body': 'tintColor="$1"$2' '{N} loadMode Attribute': 'prefix': 'loadMode' 'body': 'loadMode="sync$1"$2' '{N} items Attribute': 'prefix': 'items' 'body': ':items="listOfItems$1"$2' '{N} selectedIndex Attribute': 'prefix': 'selectedIndex' 'body': 'selectedIndex="0$1"$2' '{N} for Attribute': 'prefix': 'for' 'body': 'for="item in listOfItems$1"$2' '{N} separatorColor Attribute': 'prefix': 'separatorColor' 'body': 'separatorColor="transparent$1"$2' '{N} actionBarHidden Attribute': 'prefix': 'actionBarHidden' 'body': 'actionBarHidden="true$1"$2' '{N} backgroundSpanUnderStatusBar Attribute': 'prefix': 'backgroundSpanUnderStatusBar' 'body': 'backgroundSpanUnderStatusBar="true$1"$2' '{N} androidStatusBarBackground Attribute': 'prefix': 'androidStatusBarBackground' 'body': 'androidStatusBarBackground="$1"$2' '{N} enableSwipeBackNavigation Attribute': 'prefix': 'enableSwipeBackNavigation' 'body': 'enableSwipeBackNavigation="false$1"$2' '{N} statusBarStyle Attribute': 'prefix': 'statusBarStyle' 'body': 'statusBarStyle="dark$1"$2' '{N} Value Attribute': 'prefix': 'value' 'body': 'value="$1"$2' '{N} Scroll Bar Indicator Visible Attribute': 'prefix': 'scrollBarIndicatorVisible' 'body': 'scrollBarIndicatorVisible="false$1"$2' '{N} textFieldBackgroundColor Attribute': 'prefix': 'textFieldBackgroundColor' 'body': 'textFieldBackgroundColor="$1"$2' '{N} textFieldHintColor Attribute': 'prefix': 'textFieldHintColor' 'body': 'textFieldHintColor="$1"$2' '{N} Hint Attribute': 'prefix': 'hint' 'body': 'hint="$1"$2' '{N} selectedBackgroundColor Attribute': 'prefix': 'selectedBackgroundColor' 'body': 'selectedBackgroundColor="$1"$2' '{N} minValue Attribute': 'prefix': 'minValue' 'body': 'minValue="0$1"$2' '{N} maxValue Attribute': 'prefix': 'maxValue' 'body': 'maxValue="100$1"$2' '{N} Checked Attribute': 'prefix': 'checked' 'body': 'checked="true$1"$2' '{N} Tab Text Color Attribute': 'prefix': 'tabTextColor' 'body': 'tabTextColor="$1"$2' '{N} Tab Background Color Attribute': 'prefix': 'tabBackgroundColor' 'body': 'tabBackgroundColor="$1"$2' '{N} Selected Tab Text Color Attribute': 'prefix': 'selectedTabTextColor' 'body': 'selectedTabTextColor="$1"$2' '{N} Android Tabs Position Attribute': 'prefix': 'androidTabsPosition' 'body': 'androidTabsPosition="bottom$1"$2' '{N} Secure Attribute': 'prefix': 'secure' 'body': 'secure="true$1"$2' '{N} Editable Attribute': 'prefix': 'editable' 'body': 'editable="false$1"$2' '{N} maxLength Attribute': 'prefix': 'maxLength' 'body': 'maxLength="$1"$2' '{N} returnKeyType Attribute': 'prefix': 'returnKeyType' 'body': 'returnKeyType="next$1"$2' '{N} autocorrect Attribute': 'prefix': 'autocorrect' 'body': 'autocorrect="true$1"$2' # Events '{N} tap Event': 'prefix': 'tap' 'body': '@tap="$1"$2' '{N} busyChange Event': 'prefix': 'busyChange' 'body': '@busyChange="$1"$2' '{N} dateChange Event': 'prefix': 'dateChange' 'body': '@dateChange="$1"$2' '{N} selectedIndexChange Event': 'prefix': 'selectedIndexChange' 'body': '@selectedIndexChange="$1"$2' '{N} itemTap Event': 'prefix': 'itemTap' 'body': '@itemTap="$1"$2' '{N} loaded Event': 'prefix': 'loaded' 'body': '@loaded="$1"$2' '{N} navigatedFrom Event': 'prefix': 'navigatedFrom' 'body': '@navigatedFrom="$1"$2' '{N} navigatedTo Event': 'prefix': 'navigatedTo' 'body': '@navigatedTo="$1"$2' '{N} navigatingFrom Event': 'prefix': 'navigatingFrom' 'body': '@navigatingFrom="$1"$2' '{N} navigatingTo Event': 'prefix': 'navigatingTo' 'body': '@navigatingTo="$1"$2' '{N} valueChange Event': 'prefix': 'valueChange' 'body': '@valueChange="$1"$2' '{N} scroll Event': 'prefix': 'scroll' 'body': '@scroll="$1"$2' '{N} textChange Event': 'prefix': 'textChange' 'body': '@textChange="$1"$2' '{N} submit Event': 'prefix': 'submit' 'body': '@submit="$1"$2' '{N} clear Event': 'prefix': 'clear' 'body': '@clear="$1"$2' '{N} checkedChange Event': 'prefix': 'checkedChange' 'body': '@checkedChange="$1"$2' '{N} returnPress Event': 'prefix': 'returnPress' 'body': '@returnPress="$1"$2' '{N} focus Event': 'prefix': 'focus' 'body': '@focus="$1"$2' '{N} blur Event': 'prefix': 'blur' 'body': '@blur="$1"$2' '{N} timeChange Event': 'prefix': 'timeChange' 'body': '@timeChange="$1"$2' '{N} loadStarted Event': 'prefix': 'loadStarted' 'body': '@loadStarted="$1"$2' '{N} loadFinished Event': 'prefix': 'loadFinished' 'body': '@loadFinished="$1"$2' '.text.html.vue .source.embedded.html': # Dialogs '{N}-vue ActionDialog': 'prefix': 'actiondialog' 'body': """ action("Your message", "Cancel button text", ["Option1", "Option2"]) .then(result => { console.log(result) }) """ '{N}-vue AlertDialog': 'prefix': 'alertdialog' 'body': """ alert({ title: "Your title", message: "Your message", okButtonText: "Your OK button text" }).then(() => { console.log("Alert dialog closed"); }) """ '{N}-vue ConfirmDialog': 'prefix': 'confirmdialog' 'body': """ confirm({ title: "Your title", message: "Your message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel text" }).then(result => { console.log(result); }) """ '{N}-vue LoginDialog': 'prefix': 'logindialog' 'body': """ login({ title: "Your login title", message: "Your login message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel button text", userName: "Username field value", password: "Password field value" }).then(result => { console.log(`Dialog result: ${result.result}, user: ${result.userName}, pwd: ${result.password}`); }) """ '{N}-vue PromptDialog': 'prefix': 'promptdialog' 'body': """ prompt({ title: "Your dialog title", message: "Your message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel button text", defaultText: "Suggested user input", }).then(result => { console.log(`Dialog result: ${result.result}, text: ${result.text}`) }) """
113634
# Author: <NAME> # <EMAIL> # NativeScript-Vue snippets '.text.html.vue': # Layouts '{N}-vue AbsoluteLayout': 'prefix': 'nsabsolute' 'body': """ <AbsoluteLayout> $1 </AbsoluteLayout> """ '{N}-vue DockLayout': 'prefix': 'nsdock' 'body': """ <DockLayout stretchLastChild="true"> $1 </DockLayout> """ '{N}-vue FlexboxLayout': 'prefix': 'nsflex' 'body': """ <FlexboxLayout flexDirection="row" flexWrap="nowrap" justifyContent="flex-start" alignItems="stretch" alignContent="stretch"> $1 </FlexboxLayout> """ '{N}-vue GridLayout': 'prefix': 'nsgrid' 'body': """ <GridLayout columns="$1" rows="$2"> $3 </GridLayout> """ '{N}-vue StackLayout': 'prefix': 'nsstack' 'body': """ <StackLayout orientation="vertical"> $1 </StackLayout> """ '{N}-vue WrapLayout': 'prefix': 'nswrap' 'body': """ <WrapLayout orientation="horizontal" itemWidth="$1" itemHeight="$2"> $2 </WrapLayout> """ # Action-Bar '{N}-vue ActionBar': 'prefix': 'nsactionbar' 'body': """ <ActionBar title="$1" android.icon="" flat="false" > <NavigationButton text="Back" android.systemIcon="ic_menu_back" @tap="$2" /> <ActionItem icon="" text="Left" ios.position="left" @tap="" /> <ActionItem icon="" text="Right" ios.position="right" @tap="" /> </ActionBar> """ # Components '{N}-vue ActivityIndicator': 'prefix': 'nsloading' 'body': """ <ActivityIndicator busy="true" @busyChange="onBusyChanged" /> """ '{N}-vue Button': 'prefix': 'nsbutton' 'body': """ <Button text="$1" @tap="onButtonTap" /> """ '{N}-vue DatePicker': 'prefix': 'nsdate' 'body': """ <DatePicker date="$1" /> """ '{N}-vue Frame': 'prefix': 'nsframe' 'body': """ <Frame> <Page> <ActionBar title="Default Page Title" /> <GridLayout> <Label text="Default Page Content" /> </GridLayout> </Page> </Frame> """ '{N}-vue HtmlView': 'prefix': 'nshtml' 'body': """ <HtmlView html="<div><h1>HtmlView</h1></div>" /> """ '{N}-vue Image': 'prefix': 'nsimg' 'body': """ <Image src="$1" stretch="none" /> """ '{N}-vue Label': 'prefix': 'nslabel' 'body': """ <Label text="$1" textWrap="false"/> """ '{N}-vue ListPicker': 'prefix': 'nslistpicker' 'body': """ <ListPicker :items="listOfItems" selectedIndex="0" @selectedIndexChange="selectedIndexChanged" /> """ '{N}-vue ListView': 'prefix': 'nslistview' 'body': """ <ListView for="item in listOfItems" @itemTap="onItemTap"> <v-template> <Label :text="item.text" /> </v-template> </ListView> """ '{N}-vue Page': 'prefix': 'nspage' 'body': """ <Page actionBarHidden="false"> <ActionBar title="My App" /> <GridLayout> <Label text="My Content"/> </GridLayout> </Page> """ '{N}-vue Placeholder': 'prefix': 'nsplaceholder' 'body': """ <Placeholder @creatingView="creatingView" /> """ '{N}-vue Progress': 'prefix': 'nsprogress' 'body': """ <Progress :value="currentProgress" /> """ '{N}-vue ScrollView': 'prefix': 'nsscrollview' 'body': """ <ScrollView orientation="horizontal" scrollBarIndicatorVisible="true"> $1 </ScrollView> """ '{N}-vue SearchBar': 'prefix': 'nssearchbar' 'body': """ <SearchBar hint="$1" :text="searchPhrase" @textChange="onTextChanged" @submit="onSubmit" /> """ '{N}-vue SegmentedBar': 'prefix': 'nssegmentedbar' 'body': """ <SegmentedBar :items="listOfItems" selectedIndex="0" @selectedIndexChange="onSelectedIndexChange" /> """ '{N}-vue Slider': 'prefix': 'nsslider' 'body': """ <Slider value="$1" @valueChange="onValueChanged" /> """ '{N}-vue Switch': 'prefix': 'nsswitch' 'body': """ <Switch checked="true" /> """ '{N}-vue TabView': 'prefix': 'nstabview' 'body': """ <TabView :selectedIndex="selectedIndex" @selectedIndexChange="indexChange"> <TabViewItem title="Tab 1"> <Label text="Content for Tab 1" /> </TabViewItem> <TabViewItem title="Tab 2"> <Label text="Content for Tab 2" /> </TabViewItem> </TabView> """ '{N}-vue Tabs': 'prefix': 'nstabs' 'body': """ <Tabs> <TabStrip> <TabStripItem> <Label text="Tab 1"></Label> <Image src=""></Image> </TabStripItem> <TabStripItem> <Label text="Tab 2"></Label> <Image src=""></Image> </TabStripItem> </TabStrip> <TabContentItem> <GridLayout> <Label text="Content for Tab 1"></Label> </GridLayout> </TabContentItem> <TabContentItem> <GridLayout> <Label text="Content for Tab 2"></Label> </GridLayout> </TabContentItem> </Tabs> """ '{N}-vue BottomNavigation': 'prefix': 'nsbottomnavigation' 'body': """ <BottomNavigation> <TabStrip> <TabStripItem> <Label text="Tab 1"></Label> <Image src=""></Image> </TabStripItem> <TabStripItem> <Label text="Tab 2"></Label> <Image src=""></Image> </TabStripItem> </TabStrip> <TabContentItem> <GridLayout> <Label text="Content for Tab 1"></Label> </GridLayout> </TabContentItem> <TabContentItem> <GridLayout> <Label text="Content for Tab 2"></Label> </GridLayout> </TabContentItem> </BottomNavigation> """ '{N}-vue TextField': 'prefix': 'nstextfield' 'body': """ <TextField text="$1" editable="true" returnKeyType="next" /> """ '{N}-vue TextView': 'prefix': 'nstextview' 'body': """ <TextView text="$1" editable="true" /> """ '{N}-vue TimePicker': 'prefix': 'nstime' 'body': """ <TimePicker :hour="selectedHour" :minute="selectedMinute" /> """ '{N}-vue WebView': 'prefix': 'nswebview' 'body': """ <WebView src="$1" /> """ '{N}-vue FormattedString': 'prefix': 'nsformattedstring' 'body': """ <FormattedString> <Span text="This text has a " /> <Span text="red " style="color: red" /> <Span text="piece of text. " /> <Span text="Also, this bit is italic, " fontStyle="italic" /> <Span text="and this bit is bold." fontWeight="bold" /> </FormattedString> """ # Attributes '{N} Width Attribute': 'prefix': 'width' 'body': 'width="$1"$2' '{N} Height Attribute': 'prefix': 'height' 'body': 'height="$1"$2' '{N} Text Attribute': 'prefix': 'text' 'body': 'text="$1"$2' '{N} Icon Attribute': 'prefix': 'icon' 'body': 'icon="res://$1"$2' '{N} Text Wrap Attribute': 'prefix': 'wrap' 'body': 'textWrap="true"$2' '{N} Horizontal Alignment Attribute': 'prefix': 'halign' 'body': 'horizontalAlignment="center$1"$2' '{N} Vertical Alignment Attribute': 'prefix': 'valign' 'body': 'verticalAlignment="center$1"$2' '{N} Visibility Attribute': 'prefix': 'visibility' 'body': 'visibility="collapsed$1"$2' '{N} Stretch Attribute': 'prefix': 'stretch' 'body': 'stretch="fill$1"$2' '{N} Keyboard Type Attribute': 'prefix': 'kbtype' 'body': 'keyboardType="email$1"$2' '{N} Row Attribute': 'prefix': 'row' 'body': 'row="$1"$2' '{N} Column Attribute': 'prefix': 'col' 'body': 'col="$1"$2' '{N} Rows Attribute': 'prefix': 'rows' 'body': 'rows="$1"$2' '{N} Columns Attribute': 'prefix': 'columns' 'body': 'columns="$1"$2' '{N} Rowspan Attribute': 'prefix': 'rowSpan' 'body': 'rowSpan="$1"$2' '{N} Colspan Attribute': 'prefix': 'colSpan' 'body': 'colSpan="$1" $2' '{N} stretchLastChild Attribute': 'prefix': 'stretchLastChild' 'body': 'stretchLastChild="true$1"$2' '{N} flexDirection Attribute': 'prefix': 'flexDirection' 'body': 'flexDirection="column$1"$2' '{N} flexWrap Attribute': 'prefix': 'flexWrap' 'body': 'flexWrap="wrap$1"$2' '{N} justifyContent Attribute': 'prefix': 'justifyContent' 'body': 'justifyContent="center$1"$2' '{N} alignItems Attribute': 'prefix': 'alignItems' 'body': 'alignItems="center$1"$2' '{N} alignContent Attribute': 'prefix': 'alignContent' 'body': 'alignContent="center$1"$2' '{N} order Attribute': 'prefix': 'order' 'body': 'order="$1"$2' '{N} flexGrow Attribute': 'prefix': 'flexGrow' 'body': 'flexGrow="$1"$2' '{N} flexShrink Attribute': 'prefix': 'flexShrink' 'body': 'flexShrink="$1"$2' '{N} alignSelf Attribute': 'prefix': 'alignSelf' 'body': 'alignSelf="center$1"$2' '{N} flexWrapBefore Attribute': 'prefix': 'flexWrapBefore' 'body': 'flexWrapBefore="center$1"$2' '{N} dock Attribute': 'prefix': 'dock' 'body': 'dock="top$1"$2' '{N} orientation Attribute': 'prefix': 'orientation' 'body': 'orientation="horizontal$1"$2' '{N} itemWidth Attribute': 'prefix': 'itemWidth' 'body': 'itemWidth="$1"$2' '{N} itemHeight Attribute': 'prefix': 'itemHeight' 'body': 'itemHeight="$1"$2' '{N} flat Attribute': 'prefix': 'flat' 'body': 'flat="true$1"$2' '{N} busy Attribute': 'prefix': 'busy' 'body': 'busy="true$1"$2' '{N} isEnabled Attribute': 'prefix': 'isEnabled' 'body': 'isEnabled="false$1"$2' '{N} minDate Attribute': 'prefix': 'minDate' 'body': 'minDate="$1"$2' '{N} maxDate Attribute': 'prefix': 'maxDate' 'body': 'maxDate="$1"$2' '{N} src Attribute': 'prefix': 'src' 'body': 'src="$1"$2' '{N} imageSource Attribute': 'prefix': 'imageSource' 'body': 'imageSource="$1"$2' '{N} tintColor Attribute': 'prefix': 'tintColor' 'body': 'tintColor="$1"$2' '{N} loadMode Attribute': 'prefix': 'loadMode' 'body': 'loadMode="sync$1"$2' '{N} items Attribute': 'prefix': 'items' 'body': ':items="listOfItems$1"$2' '{N} selectedIndex Attribute': 'prefix': 'selectedIndex' 'body': 'selectedIndex="0$1"$2' '{N} for Attribute': 'prefix': 'for' 'body': 'for="item in listOfItems$1"$2' '{N} separatorColor Attribute': 'prefix': 'separatorColor' 'body': 'separatorColor="transparent$1"$2' '{N} actionBarHidden Attribute': 'prefix': 'actionBarHidden' 'body': 'actionBarHidden="true$1"$2' '{N} backgroundSpanUnderStatusBar Attribute': 'prefix': 'backgroundSpanUnderStatusBar' 'body': 'backgroundSpanUnderStatusBar="true$1"$2' '{N} androidStatusBarBackground Attribute': 'prefix': 'androidStatusBarBackground' 'body': 'androidStatusBarBackground="$1"$2' '{N} enableSwipeBackNavigation Attribute': 'prefix': 'enableSwipeBackNavigation' 'body': 'enableSwipeBackNavigation="false$1"$2' '{N} statusBarStyle Attribute': 'prefix': 'statusBarStyle' 'body': 'statusBarStyle="dark$1"$2' '{N} Value Attribute': 'prefix': 'value' 'body': 'value="$1"$2' '{N} Scroll Bar Indicator Visible Attribute': 'prefix': 'scrollBarIndicatorVisible' 'body': 'scrollBarIndicatorVisible="false$1"$2' '{N} textFieldBackgroundColor Attribute': 'prefix': 'textFieldBackgroundColor' 'body': 'textFieldBackgroundColor="$1"$2' '{N} textFieldHintColor Attribute': 'prefix': 'textFieldHintColor' 'body': 'textFieldHintColor="$1"$2' '{N} Hint Attribute': 'prefix': 'hint' 'body': 'hint="$1"$2' '{N} selectedBackgroundColor Attribute': 'prefix': 'selectedBackgroundColor' 'body': 'selectedBackgroundColor="$1"$2' '{N} minValue Attribute': 'prefix': 'minValue' 'body': 'minValue="0$1"$2' '{N} maxValue Attribute': 'prefix': 'maxValue' 'body': 'maxValue="100$1"$2' '{N} Checked Attribute': 'prefix': 'checked' 'body': 'checked="true$1"$2' '{N} Tab Text Color Attribute': 'prefix': 'tabTextColor' 'body': 'tabTextColor="$1"$2' '{N} Tab Background Color Attribute': 'prefix': 'tabBackgroundColor' 'body': 'tabBackgroundColor="$1"$2' '{N} Selected Tab Text Color Attribute': 'prefix': 'selectedTabTextColor' 'body': 'selectedTabTextColor="$1"$2' '{N} Android Tabs Position Attribute': 'prefix': 'androidTabsPosition' 'body': 'androidTabsPosition="bottom$1"$2' '{N} Secure Attribute': 'prefix': 'secure' 'body': 'secure="true$1"$2' '{N} Editable Attribute': 'prefix': 'editable' 'body': 'editable="false$1"$2' '{N} maxLength Attribute': 'prefix': 'maxLength' 'body': 'maxLength="$1"$2' '{N} returnKeyType Attribute': 'prefix': 'returnKeyType' 'body': 'returnKeyType="next$1"$2' '{N} autocorrect Attribute': 'prefix': 'autocorrect' 'body': 'autocorrect="true$1"$2' # Events '{N} tap Event': 'prefix': 'tap' 'body': '@tap="$1"$2' '{N} busyChange Event': 'prefix': 'busyChange' 'body': '@busyChange="$1"$2' '{N} dateChange Event': 'prefix': 'dateChange' 'body': '@dateChange="$1"$2' '{N} selectedIndexChange Event': 'prefix': 'selectedIndexChange' 'body': '@selectedIndexChange="$1"$2' '{N} itemTap Event': 'prefix': 'itemTap' 'body': '@itemTap="$1"$2' '{N} loaded Event': 'prefix': 'loaded' 'body': '@loaded="$1"$2' '{N} navigatedFrom Event': 'prefix': 'navigatedFrom' 'body': '@navigatedFrom="$1"$2' '{N} navigatedTo Event': 'prefix': 'navigatedTo' 'body': '@navigatedTo="$1"$2' '{N} navigatingFrom Event': 'prefix': 'navigatingFrom' 'body': '@navigatingFrom="$1"$2' '{N} navigatingTo Event': 'prefix': 'navigatingTo' 'body': '@navigatingTo="$1"$2' '{N} valueChange Event': 'prefix': 'valueChange' 'body': '@valueChange="$1"$2' '{N} scroll Event': 'prefix': 'scroll' 'body': '@scroll="$1"$2' '{N} textChange Event': 'prefix': 'textChange' 'body': '@textChange="$1"$2' '{N} submit Event': 'prefix': 'submit' 'body': '@submit="$1"$2' '{N} clear Event': 'prefix': 'clear' 'body': '@clear="$1"$2' '{N} checkedChange Event': 'prefix': 'checkedChange' 'body': '@checkedChange="$1"$2' '{N} returnPress Event': 'prefix': 'returnPress' 'body': '@returnPress="$1"$2' '{N} focus Event': 'prefix': 'focus' 'body': '@focus="$1"$2' '{N} blur Event': 'prefix': 'blur' 'body': '@blur="$1"$2' '{N} timeChange Event': 'prefix': 'timeChange' 'body': '@timeChange="$1"$2' '{N} loadStarted Event': 'prefix': 'loadStarted' 'body': '@loadStarted="$1"$2' '{N} loadFinished Event': 'prefix': 'loadFinished' 'body': '@loadFinished="$1"$2' '.text.html.vue .source.embedded.html': # Dialogs '{N}-vue ActionDialog': 'prefix': 'actiondialog' 'body': """ action("Your message", "Cancel button text", ["Option1", "Option2"]) .then(result => { console.log(result) }) """ '{N}-vue AlertDialog': 'prefix': 'alertdialog' 'body': """ alert({ title: "Your title", message: "Your message", okButtonText: "Your OK button text" }).then(() => { console.log("Alert dialog closed"); }) """ '{N}-vue ConfirmDialog': 'prefix': 'confirmdialog' 'body': """ confirm({ title: "Your title", message: "Your message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel text" }).then(result => { console.log(result); }) """ '{N}-vue LoginDialog': 'prefix': 'logindialog' 'body': """ login({ title: "Your login title", message: "Your login message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel button text", userName: "Username field value", password: "<PASSWORD>" }).then(result => { console.log(`Dialog result: ${result.result}, user: ${result.userName}, pwd: ${result.password}`); }) """ '{N}-vue PromptDialog': 'prefix': 'promptdialog' 'body': """ prompt({ title: "Your dialog title", message: "Your message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel button text", defaultText: "Suggested user input", }).then(result => { console.log(`Dialog result: ${result.result}, text: ${result.text}`) }) """
true
# Author: PI:NAME:<NAME>END_PI # PI:EMAIL:<EMAIL>END_PI # NativeScript-Vue snippets '.text.html.vue': # Layouts '{N}-vue AbsoluteLayout': 'prefix': 'nsabsolute' 'body': """ <AbsoluteLayout> $1 </AbsoluteLayout> """ '{N}-vue DockLayout': 'prefix': 'nsdock' 'body': """ <DockLayout stretchLastChild="true"> $1 </DockLayout> """ '{N}-vue FlexboxLayout': 'prefix': 'nsflex' 'body': """ <FlexboxLayout flexDirection="row" flexWrap="nowrap" justifyContent="flex-start" alignItems="stretch" alignContent="stretch"> $1 </FlexboxLayout> """ '{N}-vue GridLayout': 'prefix': 'nsgrid' 'body': """ <GridLayout columns="$1" rows="$2"> $3 </GridLayout> """ '{N}-vue StackLayout': 'prefix': 'nsstack' 'body': """ <StackLayout orientation="vertical"> $1 </StackLayout> """ '{N}-vue WrapLayout': 'prefix': 'nswrap' 'body': """ <WrapLayout orientation="horizontal" itemWidth="$1" itemHeight="$2"> $2 </WrapLayout> """ # Action-Bar '{N}-vue ActionBar': 'prefix': 'nsactionbar' 'body': """ <ActionBar title="$1" android.icon="" flat="false" > <NavigationButton text="Back" android.systemIcon="ic_menu_back" @tap="$2" /> <ActionItem icon="" text="Left" ios.position="left" @tap="" /> <ActionItem icon="" text="Right" ios.position="right" @tap="" /> </ActionBar> """ # Components '{N}-vue ActivityIndicator': 'prefix': 'nsloading' 'body': """ <ActivityIndicator busy="true" @busyChange="onBusyChanged" /> """ '{N}-vue Button': 'prefix': 'nsbutton' 'body': """ <Button text="$1" @tap="onButtonTap" /> """ '{N}-vue DatePicker': 'prefix': 'nsdate' 'body': """ <DatePicker date="$1" /> """ '{N}-vue Frame': 'prefix': 'nsframe' 'body': """ <Frame> <Page> <ActionBar title="Default Page Title" /> <GridLayout> <Label text="Default Page Content" /> </GridLayout> </Page> </Frame> """ '{N}-vue HtmlView': 'prefix': 'nshtml' 'body': """ <HtmlView html="<div><h1>HtmlView</h1></div>" /> """ '{N}-vue Image': 'prefix': 'nsimg' 'body': """ <Image src="$1" stretch="none" /> """ '{N}-vue Label': 'prefix': 'nslabel' 'body': """ <Label text="$1" textWrap="false"/> """ '{N}-vue ListPicker': 'prefix': 'nslistpicker' 'body': """ <ListPicker :items="listOfItems" selectedIndex="0" @selectedIndexChange="selectedIndexChanged" /> """ '{N}-vue ListView': 'prefix': 'nslistview' 'body': """ <ListView for="item in listOfItems" @itemTap="onItemTap"> <v-template> <Label :text="item.text" /> </v-template> </ListView> """ '{N}-vue Page': 'prefix': 'nspage' 'body': """ <Page actionBarHidden="false"> <ActionBar title="My App" /> <GridLayout> <Label text="My Content"/> </GridLayout> </Page> """ '{N}-vue Placeholder': 'prefix': 'nsplaceholder' 'body': """ <Placeholder @creatingView="creatingView" /> """ '{N}-vue Progress': 'prefix': 'nsprogress' 'body': """ <Progress :value="currentProgress" /> """ '{N}-vue ScrollView': 'prefix': 'nsscrollview' 'body': """ <ScrollView orientation="horizontal" scrollBarIndicatorVisible="true"> $1 </ScrollView> """ '{N}-vue SearchBar': 'prefix': 'nssearchbar' 'body': """ <SearchBar hint="$1" :text="searchPhrase" @textChange="onTextChanged" @submit="onSubmit" /> """ '{N}-vue SegmentedBar': 'prefix': 'nssegmentedbar' 'body': """ <SegmentedBar :items="listOfItems" selectedIndex="0" @selectedIndexChange="onSelectedIndexChange" /> """ '{N}-vue Slider': 'prefix': 'nsslider' 'body': """ <Slider value="$1" @valueChange="onValueChanged" /> """ '{N}-vue Switch': 'prefix': 'nsswitch' 'body': """ <Switch checked="true" /> """ '{N}-vue TabView': 'prefix': 'nstabview' 'body': """ <TabView :selectedIndex="selectedIndex" @selectedIndexChange="indexChange"> <TabViewItem title="Tab 1"> <Label text="Content for Tab 1" /> </TabViewItem> <TabViewItem title="Tab 2"> <Label text="Content for Tab 2" /> </TabViewItem> </TabView> """ '{N}-vue Tabs': 'prefix': 'nstabs' 'body': """ <Tabs> <TabStrip> <TabStripItem> <Label text="Tab 1"></Label> <Image src=""></Image> </TabStripItem> <TabStripItem> <Label text="Tab 2"></Label> <Image src=""></Image> </TabStripItem> </TabStrip> <TabContentItem> <GridLayout> <Label text="Content for Tab 1"></Label> </GridLayout> </TabContentItem> <TabContentItem> <GridLayout> <Label text="Content for Tab 2"></Label> </GridLayout> </TabContentItem> </Tabs> """ '{N}-vue BottomNavigation': 'prefix': 'nsbottomnavigation' 'body': """ <BottomNavigation> <TabStrip> <TabStripItem> <Label text="Tab 1"></Label> <Image src=""></Image> </TabStripItem> <TabStripItem> <Label text="Tab 2"></Label> <Image src=""></Image> </TabStripItem> </TabStrip> <TabContentItem> <GridLayout> <Label text="Content for Tab 1"></Label> </GridLayout> </TabContentItem> <TabContentItem> <GridLayout> <Label text="Content for Tab 2"></Label> </GridLayout> </TabContentItem> </BottomNavigation> """ '{N}-vue TextField': 'prefix': 'nstextfield' 'body': """ <TextField text="$1" editable="true" returnKeyType="next" /> """ '{N}-vue TextView': 'prefix': 'nstextview' 'body': """ <TextView text="$1" editable="true" /> """ '{N}-vue TimePicker': 'prefix': 'nstime' 'body': """ <TimePicker :hour="selectedHour" :minute="selectedMinute" /> """ '{N}-vue WebView': 'prefix': 'nswebview' 'body': """ <WebView src="$1" /> """ '{N}-vue FormattedString': 'prefix': 'nsformattedstring' 'body': """ <FormattedString> <Span text="This text has a " /> <Span text="red " style="color: red" /> <Span text="piece of text. " /> <Span text="Also, this bit is italic, " fontStyle="italic" /> <Span text="and this bit is bold." fontWeight="bold" /> </FormattedString> """ # Attributes '{N} Width Attribute': 'prefix': 'width' 'body': 'width="$1"$2' '{N} Height Attribute': 'prefix': 'height' 'body': 'height="$1"$2' '{N} Text Attribute': 'prefix': 'text' 'body': 'text="$1"$2' '{N} Icon Attribute': 'prefix': 'icon' 'body': 'icon="res://$1"$2' '{N} Text Wrap Attribute': 'prefix': 'wrap' 'body': 'textWrap="true"$2' '{N} Horizontal Alignment Attribute': 'prefix': 'halign' 'body': 'horizontalAlignment="center$1"$2' '{N} Vertical Alignment Attribute': 'prefix': 'valign' 'body': 'verticalAlignment="center$1"$2' '{N} Visibility Attribute': 'prefix': 'visibility' 'body': 'visibility="collapsed$1"$2' '{N} Stretch Attribute': 'prefix': 'stretch' 'body': 'stretch="fill$1"$2' '{N} Keyboard Type Attribute': 'prefix': 'kbtype' 'body': 'keyboardType="email$1"$2' '{N} Row Attribute': 'prefix': 'row' 'body': 'row="$1"$2' '{N} Column Attribute': 'prefix': 'col' 'body': 'col="$1"$2' '{N} Rows Attribute': 'prefix': 'rows' 'body': 'rows="$1"$2' '{N} Columns Attribute': 'prefix': 'columns' 'body': 'columns="$1"$2' '{N} Rowspan Attribute': 'prefix': 'rowSpan' 'body': 'rowSpan="$1"$2' '{N} Colspan Attribute': 'prefix': 'colSpan' 'body': 'colSpan="$1" $2' '{N} stretchLastChild Attribute': 'prefix': 'stretchLastChild' 'body': 'stretchLastChild="true$1"$2' '{N} flexDirection Attribute': 'prefix': 'flexDirection' 'body': 'flexDirection="column$1"$2' '{N} flexWrap Attribute': 'prefix': 'flexWrap' 'body': 'flexWrap="wrap$1"$2' '{N} justifyContent Attribute': 'prefix': 'justifyContent' 'body': 'justifyContent="center$1"$2' '{N} alignItems Attribute': 'prefix': 'alignItems' 'body': 'alignItems="center$1"$2' '{N} alignContent Attribute': 'prefix': 'alignContent' 'body': 'alignContent="center$1"$2' '{N} order Attribute': 'prefix': 'order' 'body': 'order="$1"$2' '{N} flexGrow Attribute': 'prefix': 'flexGrow' 'body': 'flexGrow="$1"$2' '{N} flexShrink Attribute': 'prefix': 'flexShrink' 'body': 'flexShrink="$1"$2' '{N} alignSelf Attribute': 'prefix': 'alignSelf' 'body': 'alignSelf="center$1"$2' '{N} flexWrapBefore Attribute': 'prefix': 'flexWrapBefore' 'body': 'flexWrapBefore="center$1"$2' '{N} dock Attribute': 'prefix': 'dock' 'body': 'dock="top$1"$2' '{N} orientation Attribute': 'prefix': 'orientation' 'body': 'orientation="horizontal$1"$2' '{N} itemWidth Attribute': 'prefix': 'itemWidth' 'body': 'itemWidth="$1"$2' '{N} itemHeight Attribute': 'prefix': 'itemHeight' 'body': 'itemHeight="$1"$2' '{N} flat Attribute': 'prefix': 'flat' 'body': 'flat="true$1"$2' '{N} busy Attribute': 'prefix': 'busy' 'body': 'busy="true$1"$2' '{N} isEnabled Attribute': 'prefix': 'isEnabled' 'body': 'isEnabled="false$1"$2' '{N} minDate Attribute': 'prefix': 'minDate' 'body': 'minDate="$1"$2' '{N} maxDate Attribute': 'prefix': 'maxDate' 'body': 'maxDate="$1"$2' '{N} src Attribute': 'prefix': 'src' 'body': 'src="$1"$2' '{N} imageSource Attribute': 'prefix': 'imageSource' 'body': 'imageSource="$1"$2' '{N} tintColor Attribute': 'prefix': 'tintColor' 'body': 'tintColor="$1"$2' '{N} loadMode Attribute': 'prefix': 'loadMode' 'body': 'loadMode="sync$1"$2' '{N} items Attribute': 'prefix': 'items' 'body': ':items="listOfItems$1"$2' '{N} selectedIndex Attribute': 'prefix': 'selectedIndex' 'body': 'selectedIndex="0$1"$2' '{N} for Attribute': 'prefix': 'for' 'body': 'for="item in listOfItems$1"$2' '{N} separatorColor Attribute': 'prefix': 'separatorColor' 'body': 'separatorColor="transparent$1"$2' '{N} actionBarHidden Attribute': 'prefix': 'actionBarHidden' 'body': 'actionBarHidden="true$1"$2' '{N} backgroundSpanUnderStatusBar Attribute': 'prefix': 'backgroundSpanUnderStatusBar' 'body': 'backgroundSpanUnderStatusBar="true$1"$2' '{N} androidStatusBarBackground Attribute': 'prefix': 'androidStatusBarBackground' 'body': 'androidStatusBarBackground="$1"$2' '{N} enableSwipeBackNavigation Attribute': 'prefix': 'enableSwipeBackNavigation' 'body': 'enableSwipeBackNavigation="false$1"$2' '{N} statusBarStyle Attribute': 'prefix': 'statusBarStyle' 'body': 'statusBarStyle="dark$1"$2' '{N} Value Attribute': 'prefix': 'value' 'body': 'value="$1"$2' '{N} Scroll Bar Indicator Visible Attribute': 'prefix': 'scrollBarIndicatorVisible' 'body': 'scrollBarIndicatorVisible="false$1"$2' '{N} textFieldBackgroundColor Attribute': 'prefix': 'textFieldBackgroundColor' 'body': 'textFieldBackgroundColor="$1"$2' '{N} textFieldHintColor Attribute': 'prefix': 'textFieldHintColor' 'body': 'textFieldHintColor="$1"$2' '{N} Hint Attribute': 'prefix': 'hint' 'body': 'hint="$1"$2' '{N} selectedBackgroundColor Attribute': 'prefix': 'selectedBackgroundColor' 'body': 'selectedBackgroundColor="$1"$2' '{N} minValue Attribute': 'prefix': 'minValue' 'body': 'minValue="0$1"$2' '{N} maxValue Attribute': 'prefix': 'maxValue' 'body': 'maxValue="100$1"$2' '{N} Checked Attribute': 'prefix': 'checked' 'body': 'checked="true$1"$2' '{N} Tab Text Color Attribute': 'prefix': 'tabTextColor' 'body': 'tabTextColor="$1"$2' '{N} Tab Background Color Attribute': 'prefix': 'tabBackgroundColor' 'body': 'tabBackgroundColor="$1"$2' '{N} Selected Tab Text Color Attribute': 'prefix': 'selectedTabTextColor' 'body': 'selectedTabTextColor="$1"$2' '{N} Android Tabs Position Attribute': 'prefix': 'androidTabsPosition' 'body': 'androidTabsPosition="bottom$1"$2' '{N} Secure Attribute': 'prefix': 'secure' 'body': 'secure="true$1"$2' '{N} Editable Attribute': 'prefix': 'editable' 'body': 'editable="false$1"$2' '{N} maxLength Attribute': 'prefix': 'maxLength' 'body': 'maxLength="$1"$2' '{N} returnKeyType Attribute': 'prefix': 'returnKeyType' 'body': 'returnKeyType="next$1"$2' '{N} autocorrect Attribute': 'prefix': 'autocorrect' 'body': 'autocorrect="true$1"$2' # Events '{N} tap Event': 'prefix': 'tap' 'body': '@tap="$1"$2' '{N} busyChange Event': 'prefix': 'busyChange' 'body': '@busyChange="$1"$2' '{N} dateChange Event': 'prefix': 'dateChange' 'body': '@dateChange="$1"$2' '{N} selectedIndexChange Event': 'prefix': 'selectedIndexChange' 'body': '@selectedIndexChange="$1"$2' '{N} itemTap Event': 'prefix': 'itemTap' 'body': '@itemTap="$1"$2' '{N} loaded Event': 'prefix': 'loaded' 'body': '@loaded="$1"$2' '{N} navigatedFrom Event': 'prefix': 'navigatedFrom' 'body': '@navigatedFrom="$1"$2' '{N} navigatedTo Event': 'prefix': 'navigatedTo' 'body': '@navigatedTo="$1"$2' '{N} navigatingFrom Event': 'prefix': 'navigatingFrom' 'body': '@navigatingFrom="$1"$2' '{N} navigatingTo Event': 'prefix': 'navigatingTo' 'body': '@navigatingTo="$1"$2' '{N} valueChange Event': 'prefix': 'valueChange' 'body': '@valueChange="$1"$2' '{N} scroll Event': 'prefix': 'scroll' 'body': '@scroll="$1"$2' '{N} textChange Event': 'prefix': 'textChange' 'body': '@textChange="$1"$2' '{N} submit Event': 'prefix': 'submit' 'body': '@submit="$1"$2' '{N} clear Event': 'prefix': 'clear' 'body': '@clear="$1"$2' '{N} checkedChange Event': 'prefix': 'checkedChange' 'body': '@checkedChange="$1"$2' '{N} returnPress Event': 'prefix': 'returnPress' 'body': '@returnPress="$1"$2' '{N} focus Event': 'prefix': 'focus' 'body': '@focus="$1"$2' '{N} blur Event': 'prefix': 'blur' 'body': '@blur="$1"$2' '{N} timeChange Event': 'prefix': 'timeChange' 'body': '@timeChange="$1"$2' '{N} loadStarted Event': 'prefix': 'loadStarted' 'body': '@loadStarted="$1"$2' '{N} loadFinished Event': 'prefix': 'loadFinished' 'body': '@loadFinished="$1"$2' '.text.html.vue .source.embedded.html': # Dialogs '{N}-vue ActionDialog': 'prefix': 'actiondialog' 'body': """ action("Your message", "Cancel button text", ["Option1", "Option2"]) .then(result => { console.log(result) }) """ '{N}-vue AlertDialog': 'prefix': 'alertdialog' 'body': """ alert({ title: "Your title", message: "Your message", okButtonText: "Your OK button text" }).then(() => { console.log("Alert dialog closed"); }) """ '{N}-vue ConfirmDialog': 'prefix': 'confirmdialog' 'body': """ confirm({ title: "Your title", message: "Your message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel text" }).then(result => { console.log(result); }) """ '{N}-vue LoginDialog': 'prefix': 'logindialog' 'body': """ login({ title: "Your login title", message: "Your login message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel button text", userName: "Username field value", password: "PI:PASSWORD:<PASSWORD>END_PI" }).then(result => { console.log(`Dialog result: ${result.result}, user: ${result.userName}, pwd: ${result.password}`); }) """ '{N}-vue PromptDialog': 'prefix': 'promptdialog' 'body': """ prompt({ title: "Your dialog title", message: "Your message", okButtonText: "Your OK button text", cancelButtonText: "Your Cancel button text", defaultText: "Suggested user input", }).then(result => { console.log(`Dialog result: ${result.result}, text: ${result.text}`) }) """
[ { "context": "Validate closing bracket location in JSX\n# @author Yannick Croissant\n###\n'use strict'\n\n# -----------------------------", "end": 89, "score": 0.9998583197593689, "start": 72, "tag": "NAME", "value": "Yannick Croissant" } ]
src/tests/rules/jsx-closing-bracket-location.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Validate closing bracket location in JSX # @author Yannick Croissant ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-closing-bracket-location' {RuleTester} = require 'eslint' path = require 'path' MESSAGE_AFTER_PROPS = [ message: 'The closing bracket must be placed after the last prop' ] MESSAGE_AFTER_TAG = [ message: 'The closing bracket must be placed after the opening tag' ] MESSAGE_PROPS_ALIGNED = 'The closing bracket must be aligned with the last prop' # MESSAGE_TAG_ALIGNED = 'The closing bracket must be aligned with the opening tag' MESSAGE_LINE_ALIGNED = 'The closing bracket must be aligned with the line containing the opening tag' messageWithDetails = (message, expectedColumn, expectedNextLine) -> details = " (expected column #{expectedColumn}#{ if expectedNextLine then ' on the next line)' else ')' }" message + details # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-closing-bracket-location', rule, valid: [ code: ['<App />'].join '\n' , code: ['<App foo />'].join '\n' , code: ['<App ', ' foo', '/>'].join '\n' , code: ['<App foo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App foo />'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo />'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', ' foo />'].join '\n' options: ['after-props'] , code: ['<App ', ' foo', ' />'].join '\n' options: ['props-aligned'] , code: ['<App ', ' foo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] , code: ['<App foo></App>'].join '\n' , # , # code: ['<App', ' foo', '></App>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App', ' foo', '></App>'].join '\n' options: [location: 'line-aligned'] , code: ['<App', ' foo', ' ></App>'].join '\n' options: [location: 'props-aligned'] , code: ['<App', ' foo={->', " console.log('bar')", ' } />'].join '\n' options: [location: 'after-props'] , code: ['<App', ' foo={->', " console.log('bar')", ' }', ' />'].join( '\n' ) options: [location: 'props-aligned'] , # , # code: ['<App', ' foo={->', " console.log('bar')", ' }', '/>'].join( # '\n' # ) # options: [location: 'tag-aligned'] code: ['<App', ' foo={->', " console.log('bar')", ' }', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App foo={->', " console.log('bar')", '}/>'].join '\n' options: [location: 'after-props'] , code: ''' <App foo={-> console.log('bar') } /> ''' options: [location: 'props-aligned'] , # , # code: ['<App foo={->', " console.log('bar')", '}', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo={->', " console.log('bar')", '}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<Provider store>', ' <App', ' foo />', '</Provider>'].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' ' store' '>' ' <App' ' foo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] , code: [ '<Provider store>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] , code: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] , code: [ 'x = ->' ' return <App' ' foo={->' " console.log('bar')" ' }' ' />' ].join '\n' options: [location: 'line-aligned'] , code: ['x = <App', ' foo={->', " console.log('bar')", ' }', '/>'].join( '\n' ) options: [location: 'line-aligned'] , code: [ '<Provider' ' store' '>' ' <App' ' foo={->' " console.log('bar')" ' }' ' />' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<Provider' ' store' '>' ' {baz && <App' ' foo={->' " console.log('bar')" ' }' ' />}' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<App>' ' <Foo' ' bar' ' >' ' </Foo>' ' <Foo' ' bar />' '</App>' ].join '\n' options: [ nonEmpty: no selfClosing: 'after-props' ] , code: [ '<App>' ' <Foo' ' bar>' ' </Foo>' ' <Foo' ' bar' ' />' '</App>' ].join '\n' options: [ nonEmpty: 'after-props' selfClosing: no ] , # , # code: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}' # '>' # ' Some text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] code: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}' '>' ' Some text' '</div>' ].join '\n' options: [location: 'line-aligned'] , code: ['<App ', '\tfoo', '/>'].join '\n' , code: ['<App ', '\tfoo />'].join '\n' options: ['after-props'] , code: ['<App ', '\tfoo', '\t/>'].join '\n' options: ['props-aligned'] , code: ['<App ', '\tfoo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] , # , # code: ['<App', '\tfoo', '></App>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App', '\tfoo', '></App>'].join '\n' options: [location: 'line-aligned'] , code: ['<App', '\tfoo', '\t></App>'].join '\n' options: [location: 'props-aligned'] , code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t} />'].join '\n' options: [location: 'after-props'] , code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '\t/>'].join( '\n' ) options: [location: 'props-aligned'] , # , # code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join( # '\n' # ) # options: [location: 'tag-aligned'] code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App foo={->', "\tconsole.log('bar')", '}/>'].join '\n' options: [location: 'after-props'] , # , # code: ['<App foo={->', "\tconsole.log('bar')", '}', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo={->', "\tconsole.log('bar')", '}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<Provider store>', '\t<App', '\t\tfoo />', '</Provider>'].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' '\tstore' '>' '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] , code: [ '<Provider store>' '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] , code: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] , # , # code: ['x = <App', ' foo', ' />'].join '\n' # options: [location: 'tag-aligned'] code: [ 'x = ->' '\treturn <App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>' ].join '\n' options: [location: 'line-aligned'] , code: ['x = <App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join( '\n' ) options: [location: 'line-aligned'] , code: [ '<Provider' '\tstore' '>' '\t<App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<Provider' '\tstore' '>' '\t{baz && <App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>}' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<App>' '\t<Foo' '\t\tbar' '\t>' '\t</Foo>' '\t<Foo' '\t\tbar />' '</App>' ].join '\n' options: [ nonEmpty: no selfClosing: 'after-props' ] , code: [ '<App>' '\t<Foo' '\t\tbar>' '\t</Foo>' '\t<Foo' '\t\tbar' '\t/>' '</App>' ].join '\n' options: [ nonEmpty: 'after-props' selfClosing: no ] , # , # code: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}' # '>' # '\tSome text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] code: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}' '>' '\tSome text' '</div>' ].join '\n' options: [location: 'line-aligned'] ] invalid: [ code: ['<App ', '/>'].join '\n' output: ['<App />'].join '\n' errors: MESSAGE_AFTER_TAG , code: ['<App foo ', '/>'].join '\n' output: ['<App foo/>'].join '\n' errors: MESSAGE_AFTER_PROPS , code: ['<App foo', '></App>'].join '\n' output: ['<App foo></App>'].join '\n' errors: MESSAGE_AFTER_PROPS , code: ['<App ', ' foo />'].join '\n' output: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, yes line: 2 column: 7 ] , # , # code: ['<App ', ' foo />'].join '\n' # output: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 2 # column: 7 # ] code: ['<App ', ' foo />'].join '\n' output: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , code: ['<App ', ' foo', '/>'].join '\n' output: ['<App ', ' foo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App ', ' foo', '/>'].join '\n' output: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, no line: 3 column: 1 ] , code: ['<App ', ' foo', ' />'].join '\n' output: ['<App ', ' foo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App ', ' foo', ' />'].join '\n' # output: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 3 # ] code: ['<App ', ' foo', ' />'].join '\n' output: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: ['<App', ' foo', '></App>'].join '\n' output: ['<App', ' foo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App', ' foo', '></App>'].join '\n' output: ['<App', ' foo', ' ></App>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, no line: 3 column: 1 ] , code: ['<App', ' foo', ' ></App>'].join '\n' output: ['<App', ' foo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App', ' foo', ' ></App>'].join '\n' # output: ['<App', ' foo', '></App>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 3 # ] code: ['<App', ' foo', ' ></App>'].join '\n' output: ['<App', ' foo', '></App>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: [ '<Provider ' ' store>' # <-- ' <App ' ' foo' ' />' '</Provider>' ].join '\n' output: [ '<Provider ' ' store' '>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 8 ] , code: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' output: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' options: ['props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 7, no line: 6 column: 5 ] , # , # code: [ # 'Button = (props) ->' # ' return (' # ' <Button' # ' size={size}' # ' onClick={onClick}' # ' >' # ' Button Text' # ' </Button>' # ' )' # ].join '\n' # output: [ # 'Button = (props) ->' # ' return (' # ' <Button' # ' size={size}' # ' onClick={onClick}' # ' >' # ' Button Text' # ' </Button>' # ' )' # ].join '\n' # options: ['tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 5, no # line: 6 # column: 6 # ] code: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' output: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' options: ['line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 5, no line: 6 column: 7 ] , code: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' output: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 6 column: 5 ] , code: [ '<Provider ' ' store>' # <-- ' <App' ' foo />' '</Provider>' ].join '\n' output: [ '<Provider ' ' store' '>' ' <App' ' foo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 8 ] , code: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' output: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 5 column: 5 ] , code: ['x = ->', ' return <App', ' foo', ' />'].join '\n' output: ['x = ->', ' return <App', ' foo', ' />'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 4 column: 5 ] , code: ['x = <App', ' foo', ' />'].join '\n' output: ['x = <App', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: [ 'x = (' ' <div' ' className="MyComponent"' ' {...props} />' ')' ].join '\n' output: [ 'x = (' ' <div' ' className="MyComponent"' ' {...props}' ' />' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, yes line: 4 column: 16 ] , code: ['x = (', ' <Something', ' content={<Foo />} />', ')'].join '\n' output: [ 'x = (' ' <Something' ' content={<Foo />}' ' />' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, yes line: 3 column: 23 ] , code: ['x = (', ' <Something ', ' />', ')'].join '\n' output: ['x = (', ' <Something />', ')'].join '\n' options: [location: 'line-aligned'] errors: [MESSAGE_AFTER_TAG] , # , # code: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}>' # ' Some text' # '</div>' # ].join '\n' # output: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}' # '>' # ' Some text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 4 # column: 7 # ] code: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}>' ' Some text' '</div>' ].join '\n' output: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}' '>' ' Some text' '</div>' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 4 column: 7 ] , code: ['<App ', '\tfoo />'].join '\n' output: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, yes line: 2 column: 6 ] , # , # code: ['<App ', '\tfoo />'].join '\n' # output: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 2 # column: 6 # ] code: ['<App ', '\tfoo />'].join '\n' output: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 6 ] , code: ['<App ', '\tfoo', '/>'].join '\n' output: ['<App ', '\tfoo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App ', '\tfoo', '/>'].join '\n' output: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, no line: 3 column: 1 ] , code: ['<App ', '\tfoo', '\t/>'].join '\n' output: ['<App ', '\tfoo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App ', '\tfoo', '\t/>'].join '\n' # output: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 2 # ] code: ['<App ', '\tfoo', '\t/>'].join '\n' output: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 2 ] , code: ['<App', '\tfoo', '></App>'].join '\n' output: ['<App', '\tfoo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App', '\tfoo', '></App>'].join '\n' output: ['<App', '\tfoo', '\t></App>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, no line: 3 column: 1 ] , code: ['<App', '\tfoo', '\t></App>'].join '\n' output: ['<App', '\tfoo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App', '\tfoo', '\t></App>'].join '\n' # output: ['<App', '\tfoo', '></App>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 2 # ] code: ['<App', '\tfoo', '\t></App>'].join '\n' output: ['<App', '\tfoo', '></App>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 2 ] , code: [ '<Provider ' '\tstore>' # <-- '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore' '>' '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , # , # code: [ # 'Button = (props) ->' # '\treturn (' # '\t\t<Button' # '\t\t\tsize={size}' # '\t\t\tonClick={onClick}' # '\t\t\t>' # '\t\t\tButton Text' # '\t\t</Button>' # '\t)' # ].join '\n' # output: [ # 'Button = (props) ->' # '\treturn (' # '\t\t<Button' # '\t\t\tsize={size}' # '\t\t\tonClick={onClick}' # '\t\t>' # '\t\t\tButton Text' # '\t\t</Button>' # '\t)' # ].join '\n' # options: ['tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 3, no # line: 6 # column: 4 # ] code: [ 'Button = (props) ->' '\treturn (' '\t\t<Button' '\t\t\tsize={size}' '\t\t\tonClick={onClick}' '\t\t\t>' '\t\t\tButton Text' '\t\t</Button>' '\t)' ].join '\n' output: [ 'Button = (props) ->' '\treturn (' '\t\t<Button' '\t\t\tsize={size}' '\t\t\tonClick={onClick}' '\t\t>' '\t\t\tButton Text' '\t\t</Button>' '\t)' ].join '\n' options: ['line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 6 column: 4 ] , code: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t\t/>' # <-- '</Provider>' ].join '\n' output: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 6 column: 3 ] , code: [ '<Provider ' '\tstore>' # <-- '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore' '>' '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , code: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t\t/>' # <-- '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t/>' # <-- '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 5 column: 3 ] , code: ['x = ->', '\treturn <App', '\t\tfoo', '\t\t/>'].join '\n' output: ['x = ->', '\treturn <App', '\t\tfoo', '\t/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 4 column: 3 ] , code: [ 'x = (' '\t<div' '\t\tclassName="MyComponent"' '\t\t{...props} />' ')' ].join '\n' output: [ 'x = (' '\t<div' '\t\tclassName="MyComponent"' '\t\t{...props}' '\t/>' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, yes line: 4 column: 14 ] , code: ['x = (', '\t<Something', '\t\tcontent={<Foo />} />', ')'].join '\n' output: [ 'x = (' '\t<Something' '\t\tcontent={<Foo />}' '\t/>' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, yes line: 3 column: 21 ] , code: ['x = (', '\t<Something ', '\t/>', ')'].join '\n' output: ['x = (', '\t<Something />', ')'].join '\n' options: [location: 'line-aligned'] errors: [MESSAGE_AFTER_TAG] , # , # code: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}>' # '\tSome text' # '</div>' # ].join '\n' # output: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}' # '>' # '\tSome text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 4 # column: 6 # ] code: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}>' '\tSome text' '</div>' ].join '\n' output: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}' '>' '\tSome text' '</div>' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 4 column: 6 ] ]
108629
###* # @fileoverview Validate closing bracket location in JSX # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-closing-bracket-location' {RuleTester} = require 'eslint' path = require 'path' MESSAGE_AFTER_PROPS = [ message: 'The closing bracket must be placed after the last prop' ] MESSAGE_AFTER_TAG = [ message: 'The closing bracket must be placed after the opening tag' ] MESSAGE_PROPS_ALIGNED = 'The closing bracket must be aligned with the last prop' # MESSAGE_TAG_ALIGNED = 'The closing bracket must be aligned with the opening tag' MESSAGE_LINE_ALIGNED = 'The closing bracket must be aligned with the line containing the opening tag' messageWithDetails = (message, expectedColumn, expectedNextLine) -> details = " (expected column #{expectedColumn}#{ if expectedNextLine then ' on the next line)' else ')' }" message + details # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-closing-bracket-location', rule, valid: [ code: ['<App />'].join '\n' , code: ['<App foo />'].join '\n' , code: ['<App ', ' foo', '/>'].join '\n' , code: ['<App foo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App foo />'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo />'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', ' foo />'].join '\n' options: ['after-props'] , code: ['<App ', ' foo', ' />'].join '\n' options: ['props-aligned'] , code: ['<App ', ' foo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] , code: ['<App foo></App>'].join '\n' , # , # code: ['<App', ' foo', '></App>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App', ' foo', '></App>'].join '\n' options: [location: 'line-aligned'] , code: ['<App', ' foo', ' ></App>'].join '\n' options: [location: 'props-aligned'] , code: ['<App', ' foo={->', " console.log('bar')", ' } />'].join '\n' options: [location: 'after-props'] , code: ['<App', ' foo={->', " console.log('bar')", ' }', ' />'].join( '\n' ) options: [location: 'props-aligned'] , # , # code: ['<App', ' foo={->', " console.log('bar')", ' }', '/>'].join( # '\n' # ) # options: [location: 'tag-aligned'] code: ['<App', ' foo={->', " console.log('bar')", ' }', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App foo={->', " console.log('bar')", '}/>'].join '\n' options: [location: 'after-props'] , code: ''' <App foo={-> console.log('bar') } /> ''' options: [location: 'props-aligned'] , # , # code: ['<App foo={->', " console.log('bar')", '}', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo={->', " console.log('bar')", '}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<Provider store>', ' <App', ' foo />', '</Provider>'].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' ' store' '>' ' <App' ' foo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] , code: [ '<Provider store>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] , code: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] , code: [ 'x = ->' ' return <App' ' foo={->' " console.log('bar')" ' }' ' />' ].join '\n' options: [location: 'line-aligned'] , code: ['x = <App', ' foo={->', " console.log('bar')", ' }', '/>'].join( '\n' ) options: [location: 'line-aligned'] , code: [ '<Provider' ' store' '>' ' <App' ' foo={->' " console.log('bar')" ' }' ' />' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<Provider' ' store' '>' ' {baz && <App' ' foo={->' " console.log('bar')" ' }' ' />}' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<App>' ' <Foo' ' bar' ' >' ' </Foo>' ' <Foo' ' bar />' '</App>' ].join '\n' options: [ nonEmpty: no selfClosing: 'after-props' ] , code: [ '<App>' ' <Foo' ' bar>' ' </Foo>' ' <Foo' ' bar' ' />' '</App>' ].join '\n' options: [ nonEmpty: 'after-props' selfClosing: no ] , # , # code: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}' # '>' # ' Some text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] code: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}' '>' ' Some text' '</div>' ].join '\n' options: [location: 'line-aligned'] , code: ['<App ', '\tfoo', '/>'].join '\n' , code: ['<App ', '\tfoo />'].join '\n' options: ['after-props'] , code: ['<App ', '\tfoo', '\t/>'].join '\n' options: ['props-aligned'] , code: ['<App ', '\tfoo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] , # , # code: ['<App', '\tfoo', '></App>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App', '\tfoo', '></App>'].join '\n' options: [location: 'line-aligned'] , code: ['<App', '\tfoo', '\t></App>'].join '\n' options: [location: 'props-aligned'] , code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t} />'].join '\n' options: [location: 'after-props'] , code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '\t/>'].join( '\n' ) options: [location: 'props-aligned'] , # , # code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join( # '\n' # ) # options: [location: 'tag-aligned'] code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App foo={->', "\tconsole.log('bar')", '}/>'].join '\n' options: [location: 'after-props'] , # , # code: ['<App foo={->', "\tconsole.log('bar')", '}', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo={->', "\tconsole.log('bar')", '}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<Provider store>', '\t<App', '\t\tfoo />', '</Provider>'].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' '\tstore' '>' '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] , code: [ '<Provider store>' '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] , code: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] , # , # code: ['x = <App', ' foo', ' />'].join '\n' # options: [location: 'tag-aligned'] code: [ 'x = ->' '\treturn <App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>' ].join '\n' options: [location: 'line-aligned'] , code: ['x = <App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join( '\n' ) options: [location: 'line-aligned'] , code: [ '<Provider' '\tstore' '>' '\t<App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<Provider' '\tstore' '>' '\t{baz && <App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>}' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<App>' '\t<Foo' '\t\tbar' '\t>' '\t</Foo>' '\t<Foo' '\t\tbar />' '</App>' ].join '\n' options: [ nonEmpty: no selfClosing: 'after-props' ] , code: [ '<App>' '\t<Foo' '\t\tbar>' '\t</Foo>' '\t<Foo' '\t\tbar' '\t/>' '</App>' ].join '\n' options: [ nonEmpty: 'after-props' selfClosing: no ] , # , # code: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}' # '>' # '\tSome text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] code: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}' '>' '\tSome text' '</div>' ].join '\n' options: [location: 'line-aligned'] ] invalid: [ code: ['<App ', '/>'].join '\n' output: ['<App />'].join '\n' errors: MESSAGE_AFTER_TAG , code: ['<App foo ', '/>'].join '\n' output: ['<App foo/>'].join '\n' errors: MESSAGE_AFTER_PROPS , code: ['<App foo', '></App>'].join '\n' output: ['<App foo></App>'].join '\n' errors: MESSAGE_AFTER_PROPS , code: ['<App ', ' foo />'].join '\n' output: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, yes line: 2 column: 7 ] , # , # code: ['<App ', ' foo />'].join '\n' # output: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 2 # column: 7 # ] code: ['<App ', ' foo />'].join '\n' output: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , code: ['<App ', ' foo', '/>'].join '\n' output: ['<App ', ' foo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App ', ' foo', '/>'].join '\n' output: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, no line: 3 column: 1 ] , code: ['<App ', ' foo', ' />'].join '\n' output: ['<App ', ' foo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App ', ' foo', ' />'].join '\n' # output: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 3 # ] code: ['<App ', ' foo', ' />'].join '\n' output: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: ['<App', ' foo', '></App>'].join '\n' output: ['<App', ' foo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App', ' foo', '></App>'].join '\n' output: ['<App', ' foo', ' ></App>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, no line: 3 column: 1 ] , code: ['<App', ' foo', ' ></App>'].join '\n' output: ['<App', ' foo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App', ' foo', ' ></App>'].join '\n' # output: ['<App', ' foo', '></App>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 3 # ] code: ['<App', ' foo', ' ></App>'].join '\n' output: ['<App', ' foo', '></App>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: [ '<Provider ' ' store>' # <-- ' <App ' ' foo' ' />' '</Provider>' ].join '\n' output: [ '<Provider ' ' store' '>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 8 ] , code: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' output: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' options: ['props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 7, no line: 6 column: 5 ] , # , # code: [ # 'Button = (props) ->' # ' return (' # ' <Button' # ' size={size}' # ' onClick={onClick}' # ' >' # ' Button Text' # ' </Button>' # ' )' # ].join '\n' # output: [ # 'Button = (props) ->' # ' return (' # ' <Button' # ' size={size}' # ' onClick={onClick}' # ' >' # ' Button Text' # ' </Button>' # ' )' # ].join '\n' # options: ['tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 5, no # line: 6 # column: 6 # ] code: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' output: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' options: ['line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 5, no line: 6 column: 7 ] , code: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' output: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 6 column: 5 ] , code: [ '<Provider ' ' store>' # <-- ' <App' ' foo />' '</Provider>' ].join '\n' output: [ '<Provider ' ' store' '>' ' <App' ' foo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 8 ] , code: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' output: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 5 column: 5 ] , code: ['x = ->', ' return <App', ' foo', ' />'].join '\n' output: ['x = ->', ' return <App', ' foo', ' />'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 4 column: 5 ] , code: ['x = <App', ' foo', ' />'].join '\n' output: ['x = <App', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: [ 'x = (' ' <div' ' className="MyComponent"' ' {...props} />' ')' ].join '\n' output: [ 'x = (' ' <div' ' className="MyComponent"' ' {...props}' ' />' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, yes line: 4 column: 16 ] , code: ['x = (', ' <Something', ' content={<Foo />} />', ')'].join '\n' output: [ 'x = (' ' <Something' ' content={<Foo />}' ' />' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, yes line: 3 column: 23 ] , code: ['x = (', ' <Something ', ' />', ')'].join '\n' output: ['x = (', ' <Something />', ')'].join '\n' options: [location: 'line-aligned'] errors: [MESSAGE_AFTER_TAG] , # , # code: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}>' # ' Some text' # '</div>' # ].join '\n' # output: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}' # '>' # ' Some text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 4 # column: 7 # ] code: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}>' ' Some text' '</div>' ].join '\n' output: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}' '>' ' Some text' '</div>' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 4 column: 7 ] , code: ['<App ', '\tfoo />'].join '\n' output: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, yes line: 2 column: 6 ] , # , # code: ['<App ', '\tfoo />'].join '\n' # output: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 2 # column: 6 # ] code: ['<App ', '\tfoo />'].join '\n' output: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 6 ] , code: ['<App ', '\tfoo', '/>'].join '\n' output: ['<App ', '\tfoo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App ', '\tfoo', '/>'].join '\n' output: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, no line: 3 column: 1 ] , code: ['<App ', '\tfoo', '\t/>'].join '\n' output: ['<App ', '\tfoo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App ', '\tfoo', '\t/>'].join '\n' # output: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 2 # ] code: ['<App ', '\tfoo', '\t/>'].join '\n' output: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 2 ] , code: ['<App', '\tfoo', '></App>'].join '\n' output: ['<App', '\tfoo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App', '\tfoo', '></App>'].join '\n' output: ['<App', '\tfoo', '\t></App>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, no line: 3 column: 1 ] , code: ['<App', '\tfoo', '\t></App>'].join '\n' output: ['<App', '\tfoo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App', '\tfoo', '\t></App>'].join '\n' # output: ['<App', '\tfoo', '></App>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 2 # ] code: ['<App', '\tfoo', '\t></App>'].join '\n' output: ['<App', '\tfoo', '></App>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 2 ] , code: [ '<Provider ' '\tstore>' # <-- '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore' '>' '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , # , # code: [ # 'Button = (props) ->' # '\treturn (' # '\t\t<Button' # '\t\t\tsize={size}' # '\t\t\tonClick={onClick}' # '\t\t\t>' # '\t\t\tButton Text' # '\t\t</Button>' # '\t)' # ].join '\n' # output: [ # 'Button = (props) ->' # '\treturn (' # '\t\t<Button' # '\t\t\tsize={size}' # '\t\t\tonClick={onClick}' # '\t\t>' # '\t\t\tButton Text' # '\t\t</Button>' # '\t)' # ].join '\n' # options: ['tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 3, no # line: 6 # column: 4 # ] code: [ 'Button = (props) ->' '\treturn (' '\t\t<Button' '\t\t\tsize={size}' '\t\t\tonClick={onClick}' '\t\t\t>' '\t\t\tButton Text' '\t\t</Button>' '\t)' ].join '\n' output: [ 'Button = (props) ->' '\treturn (' '\t\t<Button' '\t\t\tsize={size}' '\t\t\tonClick={onClick}' '\t\t>' '\t\t\tButton Text' '\t\t</Button>' '\t)' ].join '\n' options: ['line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 6 column: 4 ] , code: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t\t/>' # <-- '</Provider>' ].join '\n' output: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 6 column: 3 ] , code: [ '<Provider ' '\tstore>' # <-- '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore' '>' '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , code: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t\t/>' # <-- '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t/>' # <-- '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 5 column: 3 ] , code: ['x = ->', '\treturn <App', '\t\tfoo', '\t\t/>'].join '\n' output: ['x = ->', '\treturn <App', '\t\tfoo', '\t/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 4 column: 3 ] , code: [ 'x = (' '\t<div' '\t\tclassName="MyComponent"' '\t\t{...props} />' ')' ].join '\n' output: [ 'x = (' '\t<div' '\t\tclassName="MyComponent"' '\t\t{...props}' '\t/>' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, yes line: 4 column: 14 ] , code: ['x = (', '\t<Something', '\t\tcontent={<Foo />} />', ')'].join '\n' output: [ 'x = (' '\t<Something' '\t\tcontent={<Foo />}' '\t/>' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, yes line: 3 column: 21 ] , code: ['x = (', '\t<Something ', '\t/>', ')'].join '\n' output: ['x = (', '\t<Something />', ')'].join '\n' options: [location: 'line-aligned'] errors: [MESSAGE_AFTER_TAG] , # , # code: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}>' # '\tSome text' # '</div>' # ].join '\n' # output: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}' # '>' # '\tSome text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 4 # column: 6 # ] code: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}>' '\tSome text' '</div>' ].join '\n' output: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}' '>' '\tSome text' '</div>' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 4 column: 6 ] ]
true
###* # @fileoverview Validate closing bracket location in JSX # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/jsx-closing-bracket-location' {RuleTester} = require 'eslint' path = require 'path' MESSAGE_AFTER_PROPS = [ message: 'The closing bracket must be placed after the last prop' ] MESSAGE_AFTER_TAG = [ message: 'The closing bracket must be placed after the opening tag' ] MESSAGE_PROPS_ALIGNED = 'The closing bracket must be aligned with the last prop' # MESSAGE_TAG_ALIGNED = 'The closing bracket must be aligned with the opening tag' MESSAGE_LINE_ALIGNED = 'The closing bracket must be aligned with the line containing the opening tag' messageWithDetails = (message, expectedColumn, expectedNextLine) -> details = " (expected column #{expectedColumn}#{ if expectedNextLine then ' on the next line)' else ')' }" message + details # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-closing-bracket-location', rule, valid: [ code: ['<App />'].join '\n' , code: ['<App foo />'].join '\n' , code: ['<App ', ' foo', '/>'].join '\n' , code: ['<App foo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App foo />'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo />'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', ' foo />'].join '\n' options: ['after-props'] , code: ['<App ', ' foo', ' />'].join '\n' options: ['props-aligned'] , code: ['<App ', ' foo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] , code: ['<App foo></App>'].join '\n' , # , # code: ['<App', ' foo', '></App>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App', ' foo', '></App>'].join '\n' options: [location: 'line-aligned'] , code: ['<App', ' foo', ' ></App>'].join '\n' options: [location: 'props-aligned'] , code: ['<App', ' foo={->', " console.log('bar')", ' } />'].join '\n' options: [location: 'after-props'] , code: ['<App', ' foo={->', " console.log('bar')", ' }', ' />'].join( '\n' ) options: [location: 'props-aligned'] , # , # code: ['<App', ' foo={->', " console.log('bar')", ' }', '/>'].join( # '\n' # ) # options: [location: 'tag-aligned'] code: ['<App', ' foo={->', " console.log('bar')", ' }', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App foo={->', " console.log('bar')", '}/>'].join '\n' options: [location: 'after-props'] , code: ''' <App foo={-> console.log('bar') } /> ''' options: [location: 'props-aligned'] , # , # code: ['<App foo={->', " console.log('bar')", '}', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo={->', " console.log('bar')", '}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<Provider store>', ' <App', ' foo />', '</Provider>'].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' ' store' '>' ' <App' ' foo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] , code: [ '<Provider store>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] , code: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] , code: [ 'x = ->' ' return <App' ' foo={->' " console.log('bar')" ' }' ' />' ].join '\n' options: [location: 'line-aligned'] , code: ['x = <App', ' foo={->', " console.log('bar')", ' }', '/>'].join( '\n' ) options: [location: 'line-aligned'] , code: [ '<Provider' ' store' '>' ' <App' ' foo={->' " console.log('bar')" ' }' ' />' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<Provider' ' store' '>' ' {baz && <App' ' foo={->' " console.log('bar')" ' }' ' />}' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<App>' ' <Foo' ' bar' ' >' ' </Foo>' ' <Foo' ' bar />' '</App>' ].join '\n' options: [ nonEmpty: no selfClosing: 'after-props' ] , code: [ '<App>' ' <Foo' ' bar>' ' </Foo>' ' <Foo' ' bar' ' />' '</App>' ].join '\n' options: [ nonEmpty: 'after-props' selfClosing: no ] , # , # code: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}' # '>' # ' Some text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] code: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}' '>' ' Some text' '</div>' ].join '\n' options: [location: 'line-aligned'] , code: ['<App ', '\tfoo', '/>'].join '\n' , code: ['<App ', '\tfoo />'].join '\n' options: ['after-props'] , code: ['<App ', '\tfoo', '\t/>'].join '\n' options: ['props-aligned'] , code: ['<App ', '\tfoo />'].join '\n' options: [location: 'after-props'] , # , # code: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] , # , # code: ['<App', '\tfoo', '></App>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App', '\tfoo', '></App>'].join '\n' options: [location: 'line-aligned'] , code: ['<App', '\tfoo', '\t></App>'].join '\n' options: [location: 'props-aligned'] , code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t} />'].join '\n' options: [location: 'after-props'] , code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '\t/>'].join( '\n' ) options: [location: 'props-aligned'] , # , # code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join( # '\n' # ) # options: [location: 'tag-aligned'] code: ['<App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<App foo={->', "\tconsole.log('bar')", '}/>'].join '\n' options: [location: 'after-props'] , # , # code: ['<App foo={->', "\tconsole.log('bar')", '}', '/>'].join '\n' # options: [location: 'tag-aligned'] code: ['<App foo={->', "\tconsole.log('bar')", '}', '/>'].join '\n' options: [location: 'line-aligned'] , code: ['<Provider store>', '\t<App', '\t\tfoo />', '</Provider>'].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' '\tstore' '>' '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] , code: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] , code: [ '<Provider store>' '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] , code: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] , # , # code: ['x = <App', ' foo', ' />'].join '\n' # options: [location: 'tag-aligned'] code: [ 'x = ->' '\treturn <App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>' ].join '\n' options: [location: 'line-aligned'] , code: ['x = <App', '\tfoo={->', "\t\tconsole.log('bar')", '\t}', '/>'].join( '\n' ) options: [location: 'line-aligned'] , code: [ '<Provider' '\tstore' '>' '\t<App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<Provider' '\tstore' '>' '\t{baz && <App' '\t\tfoo={->' "\t\t\tconsole.log('bar')" '\t\t}' '\t/>}' '</Provider>' ].join '\n' options: [location: 'line-aligned'] , code: [ '<App>' '\t<Foo' '\t\tbar' '\t>' '\t</Foo>' '\t<Foo' '\t\tbar />' '</App>' ].join '\n' options: [ nonEmpty: no selfClosing: 'after-props' ] , code: [ '<App>' '\t<Foo' '\t\tbar>' '\t</Foo>' '\t<Foo' '\t\tbar' '\t/>' '</App>' ].join '\n' options: [ nonEmpty: 'after-props' selfClosing: no ] , # , # code: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}' # '>' # '\tSome text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] code: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}' '>' '\tSome text' '</div>' ].join '\n' options: [location: 'line-aligned'] ] invalid: [ code: ['<App ', '/>'].join '\n' output: ['<App />'].join '\n' errors: MESSAGE_AFTER_TAG , code: ['<App foo ', '/>'].join '\n' output: ['<App foo/>'].join '\n' errors: MESSAGE_AFTER_PROPS , code: ['<App foo', '></App>'].join '\n' output: ['<App foo></App>'].join '\n' errors: MESSAGE_AFTER_PROPS , code: ['<App ', ' foo />'].join '\n' output: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, yes line: 2 column: 7 ] , # , # code: ['<App ', ' foo />'].join '\n' # output: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 2 # column: 7 # ] code: ['<App ', ' foo />'].join '\n' output: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , code: ['<App ', ' foo', '/>'].join '\n' output: ['<App ', ' foo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App ', ' foo', '/>'].join '\n' output: ['<App ', ' foo', ' />'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, no line: 3 column: 1 ] , code: ['<App ', ' foo', ' />'].join '\n' output: ['<App ', ' foo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App ', ' foo', ' />'].join '\n' # output: ['<App ', ' foo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 3 # ] code: ['<App ', ' foo', ' />'].join '\n' output: ['<App ', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: ['<App', ' foo', '></App>'].join '\n' output: ['<App', ' foo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App', ' foo', '></App>'].join '\n' output: ['<App', ' foo', ' ></App>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 3, no line: 3 column: 1 ] , code: ['<App', ' foo', ' ></App>'].join '\n' output: ['<App', ' foo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App', ' foo', ' ></App>'].join '\n' # output: ['<App', ' foo', '></App>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 3 # ] code: ['<App', ' foo', ' ></App>'].join '\n' output: ['<App', ' foo', '></App>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: [ '<Provider ' ' store>' # <-- ' <App ' ' foo' ' />' '</Provider>' ].join '\n' output: [ '<Provider ' ' store' '>' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 8 ] , code: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' output: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' options: ['props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 7, no line: 6 column: 5 ] , # , # code: [ # 'Button = (props) ->' # ' return (' # ' <Button' # ' size={size}' # ' onClick={onClick}' # ' >' # ' Button Text' # ' </Button>' # ' )' # ].join '\n' # output: [ # 'Button = (props) ->' # ' return (' # ' <Button' # ' size={size}' # ' onClick={onClick}' # ' >' # ' Button Text' # ' </Button>' # ' )' # ].join '\n' # options: ['tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 5, no # line: 6 # column: 6 # ] code: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' output: [ 'Button = (props) ->' ' return (' ' <Button' ' size={size}' ' onClick={onClick}' ' >' ' Button Text' ' </Button>' ' )' ].join '\n' options: ['line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 5, no line: 6 column: 7 ] , code: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' output: [ '<Provider' ' store' ' >' ' <App ' ' foo' ' />' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 6 column: 5 ] , code: [ '<Provider ' ' store>' # <-- ' <App' ' foo />' '</Provider>' ].join '\n' output: [ '<Provider ' ' store' '>' ' <App' ' foo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 8 ] , code: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' output: [ '<Provider ' ' store>' ' <App ' ' foo' ' />' # <-- '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 5 column: 5 ] , code: ['x = ->', ' return <App', ' foo', ' />'].join '\n' output: ['x = ->', ' return <App', ' foo', ' />'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 4 column: 5 ] , code: ['x = <App', ' foo', ' />'].join '\n' output: ['x = <App', ' foo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 3 ] , code: [ 'x = (' ' <div' ' className="MyComponent"' ' {...props} />' ')' ].join '\n' output: [ 'x = (' ' <div' ' className="MyComponent"' ' {...props}' ' />' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, yes line: 4 column: 16 ] , code: ['x = (', ' <Something', ' content={<Foo />} />', ')'].join '\n' output: [ 'x = (' ' <Something' ' content={<Foo />}' ' />' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, yes line: 3 column: 23 ] , code: ['x = (', ' <Something ', ' />', ')'].join '\n' output: ['x = (', ' <Something />', ')'].join '\n' options: [location: 'line-aligned'] errors: [MESSAGE_AFTER_TAG] , # , # code: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}>' # ' Some text' # '</div>' # ].join '\n' # output: [ # '<div className={[' # ' "some",' # ' "stuff",' # ' 2 ]}' # '>' # ' Some text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 4 # column: 7 # ] code: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}>' ' Some text' '</div>' ].join '\n' output: [ '<div className={[' ' "some",' ' "stuff",' ' 2 ]}' '>' ' Some text' '</div>' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 4 column: 7 ] , code: ['<App ', '\tfoo />'].join '\n' output: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, yes line: 2 column: 6 ] , # , # code: ['<App ', '\tfoo />'].join '\n' # output: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 2 # column: 6 # ] code: ['<App ', '\tfoo />'].join '\n' output: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 6 ] , code: ['<App ', '\tfoo', '/>'].join '\n' output: ['<App ', '\tfoo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App ', '\tfoo', '/>'].join '\n' output: ['<App ', '\tfoo', '\t/>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, no line: 3 column: 1 ] , code: ['<App ', '\tfoo', '\t/>'].join '\n' output: ['<App ', '\tfoo/>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App ', '\tfoo', '\t/>'].join '\n' # output: ['<App ', '\tfoo', '/>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 2 # ] code: ['<App ', '\tfoo', '\t/>'].join '\n' output: ['<App ', '\tfoo', '/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 2 ] , code: ['<App', '\tfoo', '></App>'].join '\n' output: ['<App', '\tfoo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , code: ['<App', '\tfoo', '></App>'].join '\n' output: ['<App', '\tfoo', '\t></App>'].join '\n' options: [location: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_PROPS_ALIGNED, 2, no line: 3 column: 1 ] , code: ['<App', '\tfoo', '\t></App>'].join '\n' output: ['<App', '\tfoo></App>'].join '\n' options: [location: 'after-props'] errors: MESSAGE_AFTER_PROPS , # , # code: ['<App', '\tfoo', '\t></App>'].join '\n' # output: ['<App', '\tfoo', '></App>'].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, no # line: 3 # column: 2 # ] code: ['<App', '\tfoo', '\t></App>'].join '\n' output: ['<App', '\tfoo', '></App>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, no line: 3 column: 2 ] , code: [ '<Provider ' '\tstore>' # <-- '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore' '>' '\t<App ' '\t\tfoo' '\t\t/>' '</Provider>' ].join '\n' options: [selfClosing: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , # , # code: [ # 'Button = (props) ->' # '\treturn (' # '\t\t<Button' # '\t\t\tsize={size}' # '\t\t\tonClick={onClick}' # '\t\t\t>' # '\t\t\tButton Text' # '\t\t</Button>' # '\t)' # ].join '\n' # output: [ # 'Button = (props) ->' # '\treturn (' # '\t\t<Button' # '\t\t\tsize={size}' # '\t\t\tonClick={onClick}' # '\t\t>' # '\t\t\tButton Text' # '\t\t</Button>' # '\t)' # ].join '\n' # options: ['tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 3, no # line: 6 # column: 4 # ] code: [ 'Button = (props) ->' '\treturn (' '\t\t<Button' '\t\t\tsize={size}' '\t\t\tonClick={onClick}' '\t\t\t>' '\t\t\tButton Text' '\t\t</Button>' '\t)' ].join '\n' output: [ 'Button = (props) ->' '\treturn (' '\t\t<Button' '\t\t\tsize={size}' '\t\t\tonClick={onClick}' '\t\t>' '\t\t\tButton Text' '\t\t</Button>' '\t)' ].join '\n' options: ['line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 3, no line: 6 column: 4 ] , code: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t\t/>' # <-- '</Provider>' ].join '\n' output: [ '<Provider' '\tstore' '\t>' '\t<App ' '\t\tfoo' '\t/>' '</Provider>' ].join '\n' options: [nonEmpty: 'props-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 6 column: 3 ] , code: [ '<Provider ' '\tstore>' # <-- '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore' '>' '\t<App' '\t\tfoo />' '</Provider>' ].join '\n' options: [selfClosing: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 2 column: 7 ] , code: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t\t/>' # <-- '</Provider>' ].join '\n' output: [ '<Provider ' '\tstore>' '\t<App ' '\t\tfoo' '\t/>' # <-- '</Provider>' ].join '\n' options: [nonEmpty: 'after-props'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 5 column: 3 ] , code: ['x = ->', '\treturn <App', '\t\tfoo', '\t\t/>'].join '\n' output: ['x = ->', '\treturn <App', '\t\tfoo', '\t/>'].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, no line: 4 column: 3 ] , code: [ 'x = (' '\t<div' '\t\tclassName="MyComponent"' '\t\t{...props} />' ')' ].join '\n' output: [ 'x = (' '\t<div' '\t\tclassName="MyComponent"' '\t\t{...props}' '\t/>' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, yes line: 4 column: 14 ] , code: ['x = (', '\t<Something', '\t\tcontent={<Foo />} />', ')'].join '\n' output: [ 'x = (' '\t<Something' '\t\tcontent={<Foo />}' '\t/>' ')' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 2, yes line: 3 column: 21 ] , code: ['x = (', '\t<Something ', '\t/>', ')'].join '\n' output: ['x = (', '\t<Something />', ')'].join '\n' options: [location: 'line-aligned'] errors: [MESSAGE_AFTER_TAG] , # , # code: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}>' # '\tSome text' # '</div>' # ].join '\n' # output: [ # '<div className={[' # '\t"some",' # '\t"stuff",' # '\t2 ]}' # '>' # '\tSome text' # '</div>' # ].join '\n' # options: [location: 'tag-aligned'] # errors: [ # message: messageWithDetails MESSAGE_TAG_ALIGNED, 1, yes # line: 4 # column: 6 # ] code: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}>' '\tSome text' '</div>' ].join '\n' output: [ '<div className={[' '\t"some",' '\t"stuff",' '\t2 ]}' '>' '\tSome text' '</div>' ].join '\n' options: [location: 'line-aligned'] errors: [ message: messageWithDetails MESSAGE_LINE_ALIGNED, 1, yes line: 4 column: 6 ] ]
[ { "context": "uin\": process.env.HUBOT_ICQ_UIN,\n \"password\": process.env.HUBOT_ICQ_PASSWORD,\n \"token\": \"ic1rtwz1s1Hj1O0r\"\n )\n im.o", "end": 629, "score": 0.9534376263618469, "start": 599, "tag": "PASSWORD", "value": "process.env.HUBOT_ICQ_PASSWORD" }, { "context": ": process.env.HUBOT_ICQ_PASSWORD,\n \"token\": \"ic1rtwz1s1Hj1O0r\"\n )\n im.on('session:start', =>\n consol", "end": 663, "score": 0.9773111939430237, "start": 647, "tag": "PASSWORD", "value": "ic1rtwz1s1Hj1O0r" } ]
src/hubot-icq.coffee
sclown/hubot-icq
0
try {Robot,Adapter,TextMessage,User} = require 'hubot' catch prequire = require('parent-require') {Robot,Adapter,TextMessage,User} = prequire 'hubot' ICQ = require('node-icq') class Icq extends Adapter constructor: -> super @robot.logger.info "Constructor" send: (user, strings...) -> @robot.logger.info "Send" for str in strings @im.send user.user.id, str reply: (user, strings...) -> console.log 'reply' @robot.logger.info "Reply" run: -> @robot.logger.info "Run" im = new ICQ( "uin": process.env.HUBOT_ICQ_UIN, "password": process.env.HUBOT_ICQ_PASSWORD, "token": "ic1rtwz1s1Hj1O0r" ) im.on('session:start', => console.log 'session:start' im.setState('online') @emit "connected" ) im.on('session:end', (endCode) => @robot.logger.info('session ended: ' + endCode); ); im.on('session:authn_required', => @robot.logger.error('session fail') @im.reconnect(5000) ) im.on('session:bad_request', => @robot.logger.error('session fail') @im.reconnect(5000) ) im.on('session:rate_limit', => @robot.logger.error('session fail - rate limit'); im.disconnect(); setTimeout((-> im.connect()) , 30*60*1000); ); im.on('im:auth_request', (auth_request) => im.usersAdd(auth_request.uin, -> im.emit('im:message', auth_request) ) ) im.on('im:message', (message) => user = @robot.brain.userForId message.uin @receive new TextMessage(user, message.text, 'messageId') ) im.connect(); @im = im exports.use = (robot) -> new Icq robot
205280
try {Robot,Adapter,TextMessage,User} = require 'hubot' catch prequire = require('parent-require') {Robot,Adapter,TextMessage,User} = prequire 'hubot' ICQ = require('node-icq') class Icq extends Adapter constructor: -> super @robot.logger.info "Constructor" send: (user, strings...) -> @robot.logger.info "Send" for str in strings @im.send user.user.id, str reply: (user, strings...) -> console.log 'reply' @robot.logger.info "Reply" run: -> @robot.logger.info "Run" im = new ICQ( "uin": process.env.HUBOT_ICQ_UIN, "password": <PASSWORD>, "token": "<PASSWORD>" ) im.on('session:start', => console.log 'session:start' im.setState('online') @emit "connected" ) im.on('session:end', (endCode) => @robot.logger.info('session ended: ' + endCode); ); im.on('session:authn_required', => @robot.logger.error('session fail') @im.reconnect(5000) ) im.on('session:bad_request', => @robot.logger.error('session fail') @im.reconnect(5000) ) im.on('session:rate_limit', => @robot.logger.error('session fail - rate limit'); im.disconnect(); setTimeout((-> im.connect()) , 30*60*1000); ); im.on('im:auth_request', (auth_request) => im.usersAdd(auth_request.uin, -> im.emit('im:message', auth_request) ) ) im.on('im:message', (message) => user = @robot.brain.userForId message.uin @receive new TextMessage(user, message.text, 'messageId') ) im.connect(); @im = im exports.use = (robot) -> new Icq robot
true
try {Robot,Adapter,TextMessage,User} = require 'hubot' catch prequire = require('parent-require') {Robot,Adapter,TextMessage,User} = prequire 'hubot' ICQ = require('node-icq') class Icq extends Adapter constructor: -> super @robot.logger.info "Constructor" send: (user, strings...) -> @robot.logger.info "Send" for str in strings @im.send user.user.id, str reply: (user, strings...) -> console.log 'reply' @robot.logger.info "Reply" run: -> @robot.logger.info "Run" im = new ICQ( "uin": process.env.HUBOT_ICQ_UIN, "password": PI:PASSWORD:<PASSWORD>END_PI, "token": "PI:PASSWORD:<PASSWORD>END_PI" ) im.on('session:start', => console.log 'session:start' im.setState('online') @emit "connected" ) im.on('session:end', (endCode) => @robot.logger.info('session ended: ' + endCode); ); im.on('session:authn_required', => @robot.logger.error('session fail') @im.reconnect(5000) ) im.on('session:bad_request', => @robot.logger.error('session fail') @im.reconnect(5000) ) im.on('session:rate_limit', => @robot.logger.error('session fail - rate limit'); im.disconnect(); setTimeout((-> im.connect()) , 30*60*1000); ); im.on('im:auth_request', (auth_request) => im.usersAdd(auth_request.uin, -> im.emit('im:message', auth_request) ) ) im.on('im:message', (message) => user = @robot.brain.userForId message.uin @receive new TextMessage(user, message.text, 'messageId') ) im.connect(); @im = im exports.use = (robot) -> new Icq robot
[ { "context": "s['caron'] =\n\tglyphName: \"caron\"\n\tcharacterName: \"CARON\"\n\tanchors:\n\t\t0:\n\t\t\tx: parentAnchors[0].x\n\t\t\ty: pa", "end": 68, "score": 0.9778661727905273, "start": 63, "tag": "NAME", "value": "CARON" } ]
src/glyphs/components/caron.coffee
byte-foundry/venus.ptf
3
exports.glyphs['caron'] = glyphName: "caron" characterName: "CARON" anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y tags: [ 'component', 'diacritic' ] components: 0: base: 'circumflex' parentAnchors: 0: x: anchors[0].x y: anchors[0].y transformOrigin: Array( anchors[0].x, anchors[0].y + 150 / 2 ) transforms: Array( [ 'scaleY', -1 ] )
161701
exports.glyphs['caron'] = glyphName: "caron" characterName: "<NAME>" anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y tags: [ 'component', 'diacritic' ] components: 0: base: 'circumflex' parentAnchors: 0: x: anchors[0].x y: anchors[0].y transformOrigin: Array( anchors[0].x, anchors[0].y + 150 / 2 ) transforms: Array( [ 'scaleY', -1 ] )
true
exports.glyphs['caron'] = glyphName: "caron" characterName: "PI:NAME:<NAME>END_PI" anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y tags: [ 'component', 'diacritic' ] components: 0: base: 'circumflex' parentAnchors: 0: x: anchors[0].x y: anchors[0].y transformOrigin: Array( anchors[0].x, anchors[0].y + 150 / 2 ) transforms: Array( [ 'scaleY', -1 ] )
[ { "context": "= uuid()\n user = \n 'userName': userName\n 'password': hash\n 'uuid': ", "end": 1110, "score": 0.9980335831642151, "start": 1102, "tag": "USERNAME", "value": "userName" }, { "context": " 'userName': userName\n 'password': hash\n 'uuid': id\n 'id' : id\n ", "end": 1139, "score": 0.9991791844367981, "start": 1135, "tag": "PASSWORD", "value": "hash" } ]
helper.coffee
EveryoneHacks/express-coffee
0
bcrypt = require('bcryptjs') whenjs = require('when') express = require('express') uuid = require('uuid4') app = express() # config = require('./config.js') # config file should contain all tokens and other private info #used in local-signup strategy exports.localReg = (app) -> (userName, password) -> db = app.locals.db # TODO: Verify that Passport accepts promises. return whenjs.promise (resolve, reject, notify) -> entries = [] # TODO: Example of a range query # Convert searches to stream searches. # db.createReadStream({ start: userName + '\x00', end: userName + '\x00\xff' }) # .on 'data', (entry) -> entries.push(entry) # .on 'close', () -> console.log(entries) db.get 'userName\x00' + userName, (err, result) -> # userName exists console.log ":helper-reg: ", err, user if result console.log 'User Name ALREADY EXISTS:', result.userName resolve false else hash = bcrypt.hashSync(password, 8) id = uuid() user = 'userName': userName 'password': hash 'uuid': id 'id' : id 'avatar': 'http://placekitten/200/300' console.log 'CREATING USER:', userName # TODO: Add replacer to json.Stringify / but change LevelDB options # TODO: Include UUID in key db.put 'userName\x00' + userName, JSON.stringify(user), () -> resolve user # check if user exists # if user exists check if passwords match (use bcrypt.compareSync(password, hash) # true where 'hash' is password in DB) # if password matches take into website # if user doesn't exist or password doesn't match tell them it failed exports.localAuth = (app) -> return (userName, password) -> return whenjs.promise (resolve, reject, notify) -> db = app.locals.db db.get 'userName\x00' + userName, (err, result) -> unless result console.log 'userName NOT FOUND:', userName resolve false else # TODO: CHANGE if we change storage types result = JSON.parse(result) hash = result.password console.log 'FOUND USER: ' + result.userName if bcrypt.compareSync(password, hash) resolve result else console.log 'AUTHENTICATION FAILED' resolve false
127821
bcrypt = require('bcryptjs') whenjs = require('when') express = require('express') uuid = require('uuid4') app = express() # config = require('./config.js') # config file should contain all tokens and other private info #used in local-signup strategy exports.localReg = (app) -> (userName, password) -> db = app.locals.db # TODO: Verify that Passport accepts promises. return whenjs.promise (resolve, reject, notify) -> entries = [] # TODO: Example of a range query # Convert searches to stream searches. # db.createReadStream({ start: userName + '\x00', end: userName + '\x00\xff' }) # .on 'data', (entry) -> entries.push(entry) # .on 'close', () -> console.log(entries) db.get 'userName\x00' + userName, (err, result) -> # userName exists console.log ":helper-reg: ", err, user if result console.log 'User Name ALREADY EXISTS:', result.userName resolve false else hash = bcrypt.hashSync(password, 8) id = uuid() user = 'userName': userName 'password': <PASSWORD> 'uuid': id 'id' : id 'avatar': 'http://placekitten/200/300' console.log 'CREATING USER:', userName # TODO: Add replacer to json.Stringify / but change LevelDB options # TODO: Include UUID in key db.put 'userName\x00' + userName, JSON.stringify(user), () -> resolve user # check if user exists # if user exists check if passwords match (use bcrypt.compareSync(password, hash) # true where 'hash' is password in DB) # if password matches take into website # if user doesn't exist or password doesn't match tell them it failed exports.localAuth = (app) -> return (userName, password) -> return whenjs.promise (resolve, reject, notify) -> db = app.locals.db db.get 'userName\x00' + userName, (err, result) -> unless result console.log 'userName NOT FOUND:', userName resolve false else # TODO: CHANGE if we change storage types result = JSON.parse(result) hash = result.password console.log 'FOUND USER: ' + result.userName if bcrypt.compareSync(password, hash) resolve result else console.log 'AUTHENTICATION FAILED' resolve false
true
bcrypt = require('bcryptjs') whenjs = require('when') express = require('express') uuid = require('uuid4') app = express() # config = require('./config.js') # config file should contain all tokens and other private info #used in local-signup strategy exports.localReg = (app) -> (userName, password) -> db = app.locals.db # TODO: Verify that Passport accepts promises. return whenjs.promise (resolve, reject, notify) -> entries = [] # TODO: Example of a range query # Convert searches to stream searches. # db.createReadStream({ start: userName + '\x00', end: userName + '\x00\xff' }) # .on 'data', (entry) -> entries.push(entry) # .on 'close', () -> console.log(entries) db.get 'userName\x00' + userName, (err, result) -> # userName exists console.log ":helper-reg: ", err, user if result console.log 'User Name ALREADY EXISTS:', result.userName resolve false else hash = bcrypt.hashSync(password, 8) id = uuid() user = 'userName': userName 'password': PI:PASSWORD:<PASSWORD>END_PI 'uuid': id 'id' : id 'avatar': 'http://placekitten/200/300' console.log 'CREATING USER:', userName # TODO: Add replacer to json.Stringify / but change LevelDB options # TODO: Include UUID in key db.put 'userName\x00' + userName, JSON.stringify(user), () -> resolve user # check if user exists # if user exists check if passwords match (use bcrypt.compareSync(password, hash) # true where 'hash' is password in DB) # if password matches take into website # if user doesn't exist or password doesn't match tell them it failed exports.localAuth = (app) -> return (userName, password) -> return whenjs.promise (resolve, reject, notify) -> db = app.locals.db db.get 'userName\x00' + userName, (err, result) -> unless result console.log 'userName NOT FOUND:', userName resolve false else # TODO: CHANGE if we change storage types result = JSON.parse(result) hash = result.password console.log 'FOUND USER: ' + result.userName if bcrypt.compareSync(password, hash) resolve result else console.log 'AUTHENTICATION FAILED' resolve false
[ { "context": " 'ns:Key': @key\n 'ns:Password': @password\n 'ns:ClientDetail':\n 'ns:AccountN", "end": 823, "score": 0.9764343500137329, "start": 814, "tag": "PASSWORD", "value": "@password" } ]
src/fedex.coffee
lyxsus/shipit
0
{Builder, Parser} = require 'xml2js' {find} = require 'underscore' moment = require 'moment-timezone' {titleCase} = require 'change-case' {ShipperClient} = require './shipper' class FedexClient extends ShipperClient constructor: ({@key, @password, @account, @meter}, @options) -> super() @parser = new Parser() @builder = new Builder(renderOpts: pretty: false) generateRequest: (trk, reference = 'n/a') -> @builder.buildObject 'ns:TrackRequest': '$': 'xmlns:ns': 'http://fedex.com/ws/track/v5' 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance' 'xsi:schemaLocation': 'http://fedex.com/ws/track/v4 TrackService_v4.xsd' 'ns:WebAuthenticationDetail': 'ns:UserCredential': 'ns:Key': @key 'ns:Password': @password 'ns:ClientDetail': 'ns:AccountNumber': @account 'ns:MeterNumber': @meter 'ns:TransactionDetail': 'ns:CustomerTransactionId': reference 'ns:Version': 'ns:ServiceId': 'trck' 'ns:Major': 5 'ns:Intermediate': 0 'ns:Minor': 0 'ns:PackageIdentifier': 'ns:Value': trk 'ns:Type': 'TRACKING_NUMBER_OR_DOORTAG' 'ns:IncludeDetailedScans': true validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? notifications = trackResult['TrackReply']?['Notifications'] success = find notifications, (notice) -> notice?['Code']?[0] is '0' return cb(notifications or 'invalid reply') unless success cb null, trackResult['TrackReply']?['TrackDetails']?[0] @parser.reset() @parser.parseString response, handleResponse presentAddress: (address) -> return unless address? city = address['City']?[0] city = city.replace('FEDEX SMARTPOST ', '') if city? stateCode = address['StateOrProvinceCode']?[0] countryCode = address['CountryCode']?[0] postalCode = address['PostalCode']?[0] @presentLocation {city, stateCode, countryCode, postalCode} STATUS_MAP = 'AA': ShipperClient.STATUS_TYPES.EN_ROUTE 'AD': ShipperClient.STATUS_TYPES.EN_ROUTE 'AF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AP': ShipperClient.STATUS_TYPES.SHIPPING 'EO': ShipperClient.STATUS_TYPES.EN_ROUTE 'EP': ShipperClient.STATUS_TYPES.SHIPPING 'FD': ShipperClient.STATUS_TYPES.EN_ROUTE 'HL': ShipperClient.STATUS_TYPES.DELIVERED 'IT': ShipperClient.STATUS_TYPES.EN_ROUTE 'LO': ShipperClient.STATUS_TYPES.EN_ROUTE 'OC': ShipperClient.STATUS_TYPES.SHIPPING 'DL': ShipperClient.STATUS_TYPES.DELIVERED 'DP': ShipperClient.STATUS_TYPES.EN_ROUTE 'DS': ShipperClient.STATUS_TYPES.EN_ROUTE 'ED': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'OD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'PF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PL': ShipperClient.STATUS_TYPES.EN_ROUTE 'PU': ShipperClient.STATUS_TYPES.EN_ROUTE 'SF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AR': ShipperClient.STATUS_TYPES.EN_ROUTE 'CD': ShipperClient.STATUS_TYPES.EN_ROUTE 'CC': ShipperClient.STATUS_TYPES.EN_ROUTE 'DE': ShipperClient.STATUS_TYPES.DELAYED 'CA': ShipperClient.STATUS_TYPES.DELAYED 'CH': ShipperClient.STATUS_TYPES.DELAYED 'DY': ShipperClient.STATUS_TYPES.DELAYED 'SE': ShipperClient.STATUS_TYPES.DELAYED 'AX': ShipperClient.STATUS_TYPES.EN_ROUTE 'OF': ShipperClient.STATUS_TYPES.EN_ROUTE 'RR': ShipperClient.STATUS_TYPES.EN_ROUTE 'OX': ShipperClient.STATUS_TYPES.EN_ROUTE 'CP': ShipperClient.STATUS_TYPES.EN_ROUTE getStatus: (shipment) -> statusCode = shipment?['StatusCode']?[0] return unless statusCode? if STATUS_MAP[statusCode]? then STATUS_MAP[statusCode] else ShipperClient.STATUS_TYPES.UNKNOWN getActivitiesAndStatus: (shipment) -> activities = [] status = null for rawActivity in shipment['Events'] or [] location = @presentAddress rawActivity['Address']?[0] raw_timestamp = rawActivity['Timestamp']?[0] if raw_timestamp? event_time = moment(raw_timestamp) timestamp = event_time.toDate() datetime = raw_timestamp[..18] details = rawActivity['EventDescription']?[0] if details? and timestamp? activity = {timestamp, datetime, location, details} activities.push activity activities: activities, status: @getStatus shipment getEta: (shipment) -> ts = shipment?['EstimatedDeliveryTimestamp']?[0] return unless ts? moment("#{ts[..18]}Z").toDate() getService: (shipment) -> shipment?['ServiceInfo']?[0] getWeight: (shipment) -> weightData = shipment?['PackageWeight']?[0] return unless weightData? units = weightData['Units']?[0] value = weightData['Value']?[0] if units? and value? then "#{value} #{units}" getDestination: (shipment) -> @presentAddress shipment['DestinationAddress']?[0] requestOptions: ({trackingNumber, reference}) -> method: 'POST' uri: @options?['endpoint'] || 'https://ws.fedex.com/xml' body: @generateRequest trackingNumber, reference module.exports = {FedexClient}
117393
{Builder, Parser} = require 'xml2js' {find} = require 'underscore' moment = require 'moment-timezone' {titleCase} = require 'change-case' {ShipperClient} = require './shipper' class FedexClient extends ShipperClient constructor: ({@key, @password, @account, @meter}, @options) -> super() @parser = new Parser() @builder = new Builder(renderOpts: pretty: false) generateRequest: (trk, reference = 'n/a') -> @builder.buildObject 'ns:TrackRequest': '$': 'xmlns:ns': 'http://fedex.com/ws/track/v5' 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance' 'xsi:schemaLocation': 'http://fedex.com/ws/track/v4 TrackService_v4.xsd' 'ns:WebAuthenticationDetail': 'ns:UserCredential': 'ns:Key': @key 'ns:Password': <PASSWORD> 'ns:ClientDetail': 'ns:AccountNumber': @account 'ns:MeterNumber': @meter 'ns:TransactionDetail': 'ns:CustomerTransactionId': reference 'ns:Version': 'ns:ServiceId': 'trck' 'ns:Major': 5 'ns:Intermediate': 0 'ns:Minor': 0 'ns:PackageIdentifier': 'ns:Value': trk 'ns:Type': 'TRACKING_NUMBER_OR_DOORTAG' 'ns:IncludeDetailedScans': true validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? notifications = trackResult['TrackReply']?['Notifications'] success = find notifications, (notice) -> notice?['Code']?[0] is '0' return cb(notifications or 'invalid reply') unless success cb null, trackResult['TrackReply']?['TrackDetails']?[0] @parser.reset() @parser.parseString response, handleResponse presentAddress: (address) -> return unless address? city = address['City']?[0] city = city.replace('FEDEX SMARTPOST ', '') if city? stateCode = address['StateOrProvinceCode']?[0] countryCode = address['CountryCode']?[0] postalCode = address['PostalCode']?[0] @presentLocation {city, stateCode, countryCode, postalCode} STATUS_MAP = 'AA': ShipperClient.STATUS_TYPES.EN_ROUTE 'AD': ShipperClient.STATUS_TYPES.EN_ROUTE 'AF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AP': ShipperClient.STATUS_TYPES.SHIPPING 'EO': ShipperClient.STATUS_TYPES.EN_ROUTE 'EP': ShipperClient.STATUS_TYPES.SHIPPING 'FD': ShipperClient.STATUS_TYPES.EN_ROUTE 'HL': ShipperClient.STATUS_TYPES.DELIVERED 'IT': ShipperClient.STATUS_TYPES.EN_ROUTE 'LO': ShipperClient.STATUS_TYPES.EN_ROUTE 'OC': ShipperClient.STATUS_TYPES.SHIPPING 'DL': ShipperClient.STATUS_TYPES.DELIVERED 'DP': ShipperClient.STATUS_TYPES.EN_ROUTE 'DS': ShipperClient.STATUS_TYPES.EN_ROUTE 'ED': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'OD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'PF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PL': ShipperClient.STATUS_TYPES.EN_ROUTE 'PU': ShipperClient.STATUS_TYPES.EN_ROUTE 'SF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AR': ShipperClient.STATUS_TYPES.EN_ROUTE 'CD': ShipperClient.STATUS_TYPES.EN_ROUTE 'CC': ShipperClient.STATUS_TYPES.EN_ROUTE 'DE': ShipperClient.STATUS_TYPES.DELAYED 'CA': ShipperClient.STATUS_TYPES.DELAYED 'CH': ShipperClient.STATUS_TYPES.DELAYED 'DY': ShipperClient.STATUS_TYPES.DELAYED 'SE': ShipperClient.STATUS_TYPES.DELAYED 'AX': ShipperClient.STATUS_TYPES.EN_ROUTE 'OF': ShipperClient.STATUS_TYPES.EN_ROUTE 'RR': ShipperClient.STATUS_TYPES.EN_ROUTE 'OX': ShipperClient.STATUS_TYPES.EN_ROUTE 'CP': ShipperClient.STATUS_TYPES.EN_ROUTE getStatus: (shipment) -> statusCode = shipment?['StatusCode']?[0] return unless statusCode? if STATUS_MAP[statusCode]? then STATUS_MAP[statusCode] else ShipperClient.STATUS_TYPES.UNKNOWN getActivitiesAndStatus: (shipment) -> activities = [] status = null for rawActivity in shipment['Events'] or [] location = @presentAddress rawActivity['Address']?[0] raw_timestamp = rawActivity['Timestamp']?[0] if raw_timestamp? event_time = moment(raw_timestamp) timestamp = event_time.toDate() datetime = raw_timestamp[..18] details = rawActivity['EventDescription']?[0] if details? and timestamp? activity = {timestamp, datetime, location, details} activities.push activity activities: activities, status: @getStatus shipment getEta: (shipment) -> ts = shipment?['EstimatedDeliveryTimestamp']?[0] return unless ts? moment("#{ts[..18]}Z").toDate() getService: (shipment) -> shipment?['ServiceInfo']?[0] getWeight: (shipment) -> weightData = shipment?['PackageWeight']?[0] return unless weightData? units = weightData['Units']?[0] value = weightData['Value']?[0] if units? and value? then "#{value} #{units}" getDestination: (shipment) -> @presentAddress shipment['DestinationAddress']?[0] requestOptions: ({trackingNumber, reference}) -> method: 'POST' uri: @options?['endpoint'] || 'https://ws.fedex.com/xml' body: @generateRequest trackingNumber, reference module.exports = {FedexClient}
true
{Builder, Parser} = require 'xml2js' {find} = require 'underscore' moment = require 'moment-timezone' {titleCase} = require 'change-case' {ShipperClient} = require './shipper' class FedexClient extends ShipperClient constructor: ({@key, @password, @account, @meter}, @options) -> super() @parser = new Parser() @builder = new Builder(renderOpts: pretty: false) generateRequest: (trk, reference = 'n/a') -> @builder.buildObject 'ns:TrackRequest': '$': 'xmlns:ns': 'http://fedex.com/ws/track/v5' 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance' 'xsi:schemaLocation': 'http://fedex.com/ws/track/v4 TrackService_v4.xsd' 'ns:WebAuthenticationDetail': 'ns:UserCredential': 'ns:Key': @key 'ns:Password': PI:PASSWORD:<PASSWORD>END_PI 'ns:ClientDetail': 'ns:AccountNumber': @account 'ns:MeterNumber': @meter 'ns:TransactionDetail': 'ns:CustomerTransactionId': reference 'ns:Version': 'ns:ServiceId': 'trck' 'ns:Major': 5 'ns:Intermediate': 0 'ns:Minor': 0 'ns:PackageIdentifier': 'ns:Value': trk 'ns:Type': 'TRACKING_NUMBER_OR_DOORTAG' 'ns:IncludeDetailedScans': true validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? notifications = trackResult['TrackReply']?['Notifications'] success = find notifications, (notice) -> notice?['Code']?[0] is '0' return cb(notifications or 'invalid reply') unless success cb null, trackResult['TrackReply']?['TrackDetails']?[0] @parser.reset() @parser.parseString response, handleResponse presentAddress: (address) -> return unless address? city = address['City']?[0] city = city.replace('FEDEX SMARTPOST ', '') if city? stateCode = address['StateOrProvinceCode']?[0] countryCode = address['CountryCode']?[0] postalCode = address['PostalCode']?[0] @presentLocation {city, stateCode, countryCode, postalCode} STATUS_MAP = 'AA': ShipperClient.STATUS_TYPES.EN_ROUTE 'AD': ShipperClient.STATUS_TYPES.EN_ROUTE 'AF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AP': ShipperClient.STATUS_TYPES.SHIPPING 'EO': ShipperClient.STATUS_TYPES.EN_ROUTE 'EP': ShipperClient.STATUS_TYPES.SHIPPING 'FD': ShipperClient.STATUS_TYPES.EN_ROUTE 'HL': ShipperClient.STATUS_TYPES.DELIVERED 'IT': ShipperClient.STATUS_TYPES.EN_ROUTE 'LO': ShipperClient.STATUS_TYPES.EN_ROUTE 'OC': ShipperClient.STATUS_TYPES.SHIPPING 'DL': ShipperClient.STATUS_TYPES.DELIVERED 'DP': ShipperClient.STATUS_TYPES.EN_ROUTE 'DS': ShipperClient.STATUS_TYPES.EN_ROUTE 'ED': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'OD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'PF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PL': ShipperClient.STATUS_TYPES.EN_ROUTE 'PU': ShipperClient.STATUS_TYPES.EN_ROUTE 'SF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AR': ShipperClient.STATUS_TYPES.EN_ROUTE 'CD': ShipperClient.STATUS_TYPES.EN_ROUTE 'CC': ShipperClient.STATUS_TYPES.EN_ROUTE 'DE': ShipperClient.STATUS_TYPES.DELAYED 'CA': ShipperClient.STATUS_TYPES.DELAYED 'CH': ShipperClient.STATUS_TYPES.DELAYED 'DY': ShipperClient.STATUS_TYPES.DELAYED 'SE': ShipperClient.STATUS_TYPES.DELAYED 'AX': ShipperClient.STATUS_TYPES.EN_ROUTE 'OF': ShipperClient.STATUS_TYPES.EN_ROUTE 'RR': ShipperClient.STATUS_TYPES.EN_ROUTE 'OX': ShipperClient.STATUS_TYPES.EN_ROUTE 'CP': ShipperClient.STATUS_TYPES.EN_ROUTE getStatus: (shipment) -> statusCode = shipment?['StatusCode']?[0] return unless statusCode? if STATUS_MAP[statusCode]? then STATUS_MAP[statusCode] else ShipperClient.STATUS_TYPES.UNKNOWN getActivitiesAndStatus: (shipment) -> activities = [] status = null for rawActivity in shipment['Events'] or [] location = @presentAddress rawActivity['Address']?[0] raw_timestamp = rawActivity['Timestamp']?[0] if raw_timestamp? event_time = moment(raw_timestamp) timestamp = event_time.toDate() datetime = raw_timestamp[..18] details = rawActivity['EventDescription']?[0] if details? and timestamp? activity = {timestamp, datetime, location, details} activities.push activity activities: activities, status: @getStatus shipment getEta: (shipment) -> ts = shipment?['EstimatedDeliveryTimestamp']?[0] return unless ts? moment("#{ts[..18]}Z").toDate() getService: (shipment) -> shipment?['ServiceInfo']?[0] getWeight: (shipment) -> weightData = shipment?['PackageWeight']?[0] return unless weightData? units = weightData['Units']?[0] value = weightData['Value']?[0] if units? and value? then "#{value} #{units}" getDestination: (shipment) -> @presentAddress shipment['DestinationAddress']?[0] requestOptions: ({trackingNumber, reference}) -> method: 'POST' uri: @options?['endpoint'] || 'https://ws.fedex.com/xml' body: @generateRequest trackingNumber, reference module.exports = {FedexClient}
[ { "context": "ation helpers\n#\n# Nodize CMS\n# https://github.com/hypee/nodize\n#\n# Copyright 2012, Hypee\n# http://hypee.c", "end": 73, "score": 0.9994912147521973, "start": 68, "tag": "USERNAME", "value": "hypee" }, { "context": "ttps://github.com/hypee/nodize\n#\n# Copyright 2012, Hypee\n# http://hypee.com\n#\n# Licensed under the MIT lic", "end": 106, "score": 0.9320551753044128, "start": 101, "tag": "NAME", "value": "Hypee" }, { "context": ", menu\n WHERE\n page_lang.lang = '#{@lang}' AND \n menu.id_menu = #{id_menu} AN", "end": 9988, "score": 0.7043197154998779, "start": 9988, "tag": "USERNAME", "value": "" } ]
modules/ionize/helpers/helper_navigation.coffee
nodize/nodizecms
32
# # Nodize - navigation helpers # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2012, Hypee # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> jade = require "jade" #***** #* Displaying navigation #* use @navigation.fieldName in nested content, #* ie: @navigation.url, @navigation.title... (@navigation contains fields of the page_lang record) #* #* TODO: We should be able to cache the response in memory #* TODO: Attributes lastClass, firstClass #* TODO: filter by menu / page / subpage / type #* #** @helpers['ion_navigation'] = (args...) -> tagName = 'ion_navigation' # default class when displaying current/active page activeClass = 'active' # default menu menu_id = 1 # default level page_level = 0 # # Parsing attributes if they do exist # if args.length>1 attrs = args[0] # # Class to be used for current/active page # activeClass = attrs.activeClass if attrs.activeClass # # Menu to use # menu_id = attrs.menu_id if attrs.menu_id # # Page level # page_level = attrs.level if attrs.level # # We are launching an asynchronous request, # we need to register it, to be able to wait for it to be finished # and insert the content in the response sent to browser # requestId = @registerRequest( tagName ) # # Finished callback # finished = (response) => @requestCompleted requestId, response displayedInNav = "page.appears = 1 AND " # # # Retrieve pages # DB.query( "SELECT page_lang.title, page_lang.subtitle, page_lang.url, page.home, page_lang.nav_title, page.link "+ "FROM page_lang, page "+ "WHERE page_lang.id_page = page.id_page AND "+ "page_lang.lang = '#{@lang}' AND "+ "page.id_menu = #{menu_id} AND "+ displayedInNav + "page.level = #{page_level} "+ "ORDER BY page.ordering", Page) .on 'success', (pages) => # # Content that will be built # htmlResponse = "" # # Looping though all pages # for page in pages #console.log page.title, page.url # # For home page, url becomes / (we hide the real url) # page.url = "/" if page.home # # Set variables that will be used in the rendered view # @navigation = page @navigation.title = @navigation.nav_title if @navigation.nav_title isnt '' @navigation.class = if @navigation.id_page is @page.id_page then activeClass else '' # # If a link is declared, we replace url by the link # if page.link then @navigation.url = page.link # # Render nested tags, # last args is the nested content to render # if args.length>=1 template = args[args.length-1] # For Jade engine if @template_engine is "jade" fn = jade.compile( template, @ ) htmlResponse += fn( @ ) # Compile the nested content to html # For Eco and CoffeeCup else htmlResponse += cede template # Compile the nested content to html #args[args.length-1]() finished( htmlResponse ) .on 'failure', (err) -> console.log "database error : ", err finished() # # Inserting placeholder in the html for replacement once async request are finished # text "{**#{requestId.name}**}" #***** #* Displaying navigation tree #* use @navigation.fieldName in nested content, #* ie: @navigation.url, @navigation.title... (@navigation contains fields of the page_lang record) #* #* TODO: Menu selection by name, default to id = 1 #* TODO: We should be able to cache the response in memory #* TODO: Attributes lastClass, firstClass #* TODO: Active class #* #** @helpers['ion_navigationTree'] = (args...) -> tagName = 'ion_navigationTree' # default class when displaying current/active page activeClass = 'active' # default menu menu_id = 1 # default level page_level = 100 level_open = "<ul>" # HTML inserted before each level change level_close = "</ul>" # HTML inserted after each level change item_open = "<li>" # HTML inserted before each menu item item_close = "</li>" # HTML inserted after each menu item # # Parsing attributes if they do exist # if args.length>1 attrs = args[0] # # Class to be used for current/active page # activeClass = attrs.activeClass if attrs.activeClass # # Menu to use # menu_id = attrs.menu_id if attrs.menu_id # # Page level # page_level = attrs.level if attrs.level? # # Items & level HTML tags # level_open = attrs.level_open if attrs.level_open level_close = attrs.level_close if attrs.level_close item_open = attrs.item_open if attrs.item_open item_close = attrs.item_close if attrs.item_close # # We are launching an asynchronous request, # we need to register it, to be able to wait for it to be finished # and insert the content in the response sent to browser # requestId = @registerRequest( tagName ) # # Finished callback # finished = (response) => @requestCompleted requestId, response # # Getting a list of pages, with child pages # # We're doing recursive calls to build the tree. # Recursion is a bit painful in async programming, so we use some tricks : # - request_counter is used to know when all request are finished, so we can build and sent the response # - we gather all responses and build a "path" value to be able to use it to sort results, in an order that matches the tree structure # # # # Retrieve pages in menu # responses = [] # # Request counter is used to define when all async requests are finished # (+1 when launching a request, -1 once finishing, 0 everything is done) # request_counter = 1 # # Building the response path # path = "" # # Send response once async requests are done # displayResponse = => request_counter-- # # Requests are finished, building & sending the response # if request_counter==0 # # Sorting responses, using the path value # responses.sort( (a,b) -> return 1 if a.path > b.path return -1 if a.path < b.path return 0 ) # # Building the response message # htmlResponse = "" currentLevel = 0 firstResult = true for line in responses # # For home page, url becomes / (we hide the real url) # line.url = "/" if line.home # # Set variables that will be used in the rendered view # @navigation = line @navigation.title = @navigation.nav_title if @navigation.nav_title isnt '' @navigation.class = if @navigation.id_page is @page.id_page then activeClass else '' levelChanged = false if @navigation.level > currentLevel htmlResponse += level_open currentLevel = @navigation.level levelChanged = true else if @navigation.level < currentLevel for index in [1..currentLevel-@navigation.level] htmlResponse += level_close currentLevel = @navigation.level levelChanged = true else htmlResponse += item_close unless firstResult firstResult = false # # Render nested tags, # last args is the nested content to render # if args.length>=1 template = args[args.length-1] htmlResponse += item_open # For Jade engine if @template_engine is "jade" fn = jade.compile( template, @ ) htmlResponse += fn( @ ) # Compile the nested content to html # For Eco and CoffeeCup else htmlResponse += cede template # Compile the nested content to html # response += "<option value='#{line.value}'>" # response += "&#160;&#187;&#160;" for level in [1..line.level] unless line.level<1 # response += "#{line.title}</option>" # # Send response # finished( htmlResponse ) # # Recursive function to retrieve pages # getParents = (path, id_menu, id_parent, callback) => # # Launch query # Sorry, not using Sequelize yet there, but should be used for compatibility with all supported DB engines # DB.query( """ SELECT page_lang.title, page_lang.subtitle, page_lang.nav_title, page_lang.url, page.level, page.id_menu, page.id_page, page.home, page.online, page.appears, page.has_url, page.link FROM page_lang, page, menu WHERE page_lang.lang = '#{@lang}' AND menu.id_menu = #{id_menu} AND page.id_parent = #{id_parent} AND page_lang.id_page = page.id_page AND page.id_menu = menu.id_menu ORDER BY page.ordering """, Page ) # # On success, store results + launch additional recursive queries # .on 'success', (results) => index = 0 for page in results index++ newPath = path + index + "/" # # Storing results in the responses array # currentResponse = {} currentResponse["path"] = newPath currentResponse["value"] = page.id_page currentResponse["title"] = page.title currentResponse["subtitle"] = page.subtitle currentResponse["nav_title"] = page.nav_title currentResponse["level"] = page.level currentResponse["url"] = page.url currentResponse["has_url"] = page.has_url currentResponse["home"] = page.home currentResponse["id_page"] = page.id_page currentResponse["online"] = page.online currentResponse["link"] = page.link # # If a link is declared, we replace url by the link # if page.link then currentResponse["url"] = page.link if (page.appears is 1) and (page.online or @req.session.usergroup_level >= 1000 ) responses.push( currentResponse ) # # Use to watch async queries termination # request_counter++ # # Search for child pages of the current page # getParents( newPath, id_menu, page.id_page, callback ) callback() .on 'failure', (err) -> console.log "GetParents error ", err # # Launch the first request # getParents( path, 1, 0, displayResponse ) # # Inserting placeholder in the html for replacement once async request are finished # text "{**#{requestId.name}**}"
49788
# # Nodize - navigation helpers # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2012, <NAME> # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> jade = require "jade" #***** #* Displaying navigation #* use @navigation.fieldName in nested content, #* ie: @navigation.url, @navigation.title... (@navigation contains fields of the page_lang record) #* #* TODO: We should be able to cache the response in memory #* TODO: Attributes lastClass, firstClass #* TODO: filter by menu / page / subpage / type #* #** @helpers['ion_navigation'] = (args...) -> tagName = 'ion_navigation' # default class when displaying current/active page activeClass = 'active' # default menu menu_id = 1 # default level page_level = 0 # # Parsing attributes if they do exist # if args.length>1 attrs = args[0] # # Class to be used for current/active page # activeClass = attrs.activeClass if attrs.activeClass # # Menu to use # menu_id = attrs.menu_id if attrs.menu_id # # Page level # page_level = attrs.level if attrs.level # # We are launching an asynchronous request, # we need to register it, to be able to wait for it to be finished # and insert the content in the response sent to browser # requestId = @registerRequest( tagName ) # # Finished callback # finished = (response) => @requestCompleted requestId, response displayedInNav = "page.appears = 1 AND " # # # Retrieve pages # DB.query( "SELECT page_lang.title, page_lang.subtitle, page_lang.url, page.home, page_lang.nav_title, page.link "+ "FROM page_lang, page "+ "WHERE page_lang.id_page = page.id_page AND "+ "page_lang.lang = '#{@lang}' AND "+ "page.id_menu = #{menu_id} AND "+ displayedInNav + "page.level = #{page_level} "+ "ORDER BY page.ordering", Page) .on 'success', (pages) => # # Content that will be built # htmlResponse = "" # # Looping though all pages # for page in pages #console.log page.title, page.url # # For home page, url becomes / (we hide the real url) # page.url = "/" if page.home # # Set variables that will be used in the rendered view # @navigation = page @navigation.title = @navigation.nav_title if @navigation.nav_title isnt '' @navigation.class = if @navigation.id_page is @page.id_page then activeClass else '' # # If a link is declared, we replace url by the link # if page.link then @navigation.url = page.link # # Render nested tags, # last args is the nested content to render # if args.length>=1 template = args[args.length-1] # For Jade engine if @template_engine is "jade" fn = jade.compile( template, @ ) htmlResponse += fn( @ ) # Compile the nested content to html # For Eco and CoffeeCup else htmlResponse += cede template # Compile the nested content to html #args[args.length-1]() finished( htmlResponse ) .on 'failure', (err) -> console.log "database error : ", err finished() # # Inserting placeholder in the html for replacement once async request are finished # text "{**#{requestId.name}**}" #***** #* Displaying navigation tree #* use @navigation.fieldName in nested content, #* ie: @navigation.url, @navigation.title... (@navigation contains fields of the page_lang record) #* #* TODO: Menu selection by name, default to id = 1 #* TODO: We should be able to cache the response in memory #* TODO: Attributes lastClass, firstClass #* TODO: Active class #* #** @helpers['ion_navigationTree'] = (args...) -> tagName = 'ion_navigationTree' # default class when displaying current/active page activeClass = 'active' # default menu menu_id = 1 # default level page_level = 100 level_open = "<ul>" # HTML inserted before each level change level_close = "</ul>" # HTML inserted after each level change item_open = "<li>" # HTML inserted before each menu item item_close = "</li>" # HTML inserted after each menu item # # Parsing attributes if they do exist # if args.length>1 attrs = args[0] # # Class to be used for current/active page # activeClass = attrs.activeClass if attrs.activeClass # # Menu to use # menu_id = attrs.menu_id if attrs.menu_id # # Page level # page_level = attrs.level if attrs.level? # # Items & level HTML tags # level_open = attrs.level_open if attrs.level_open level_close = attrs.level_close if attrs.level_close item_open = attrs.item_open if attrs.item_open item_close = attrs.item_close if attrs.item_close # # We are launching an asynchronous request, # we need to register it, to be able to wait for it to be finished # and insert the content in the response sent to browser # requestId = @registerRequest( tagName ) # # Finished callback # finished = (response) => @requestCompleted requestId, response # # Getting a list of pages, with child pages # # We're doing recursive calls to build the tree. # Recursion is a bit painful in async programming, so we use some tricks : # - request_counter is used to know when all request are finished, so we can build and sent the response # - we gather all responses and build a "path" value to be able to use it to sort results, in an order that matches the tree structure # # # # Retrieve pages in menu # responses = [] # # Request counter is used to define when all async requests are finished # (+1 when launching a request, -1 once finishing, 0 everything is done) # request_counter = 1 # # Building the response path # path = "" # # Send response once async requests are done # displayResponse = => request_counter-- # # Requests are finished, building & sending the response # if request_counter==0 # # Sorting responses, using the path value # responses.sort( (a,b) -> return 1 if a.path > b.path return -1 if a.path < b.path return 0 ) # # Building the response message # htmlResponse = "" currentLevel = 0 firstResult = true for line in responses # # For home page, url becomes / (we hide the real url) # line.url = "/" if line.home # # Set variables that will be used in the rendered view # @navigation = line @navigation.title = @navigation.nav_title if @navigation.nav_title isnt '' @navigation.class = if @navigation.id_page is @page.id_page then activeClass else '' levelChanged = false if @navigation.level > currentLevel htmlResponse += level_open currentLevel = @navigation.level levelChanged = true else if @navigation.level < currentLevel for index in [1..currentLevel-@navigation.level] htmlResponse += level_close currentLevel = @navigation.level levelChanged = true else htmlResponse += item_close unless firstResult firstResult = false # # Render nested tags, # last args is the nested content to render # if args.length>=1 template = args[args.length-1] htmlResponse += item_open # For Jade engine if @template_engine is "jade" fn = jade.compile( template, @ ) htmlResponse += fn( @ ) # Compile the nested content to html # For Eco and CoffeeCup else htmlResponse += cede template # Compile the nested content to html # response += "<option value='#{line.value}'>" # response += "&#160;&#187;&#160;" for level in [1..line.level] unless line.level<1 # response += "#{line.title}</option>" # # Send response # finished( htmlResponse ) # # Recursive function to retrieve pages # getParents = (path, id_menu, id_parent, callback) => # # Launch query # Sorry, not using Sequelize yet there, but should be used for compatibility with all supported DB engines # DB.query( """ SELECT page_lang.title, page_lang.subtitle, page_lang.nav_title, page_lang.url, page.level, page.id_menu, page.id_page, page.home, page.online, page.appears, page.has_url, page.link FROM page_lang, page, menu WHERE page_lang.lang = '#{@lang}' AND menu.id_menu = #{id_menu} AND page.id_parent = #{id_parent} AND page_lang.id_page = page.id_page AND page.id_menu = menu.id_menu ORDER BY page.ordering """, Page ) # # On success, store results + launch additional recursive queries # .on 'success', (results) => index = 0 for page in results index++ newPath = path + index + "/" # # Storing results in the responses array # currentResponse = {} currentResponse["path"] = newPath currentResponse["value"] = page.id_page currentResponse["title"] = page.title currentResponse["subtitle"] = page.subtitle currentResponse["nav_title"] = page.nav_title currentResponse["level"] = page.level currentResponse["url"] = page.url currentResponse["has_url"] = page.has_url currentResponse["home"] = page.home currentResponse["id_page"] = page.id_page currentResponse["online"] = page.online currentResponse["link"] = page.link # # If a link is declared, we replace url by the link # if page.link then currentResponse["url"] = page.link if (page.appears is 1) and (page.online or @req.session.usergroup_level >= 1000 ) responses.push( currentResponse ) # # Use to watch async queries termination # request_counter++ # # Search for child pages of the current page # getParents( newPath, id_menu, page.id_page, callback ) callback() .on 'failure', (err) -> console.log "GetParents error ", err # # Launch the first request # getParents( path, 1, 0, displayResponse ) # # Inserting placeholder in the html for replacement once async request are finished # text "{**#{requestId.name}**}"
true
# # Nodize - navigation helpers # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2012, PI:NAME:<NAME>END_PI # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> jade = require "jade" #***** #* Displaying navigation #* use @navigation.fieldName in nested content, #* ie: @navigation.url, @navigation.title... (@navigation contains fields of the page_lang record) #* #* TODO: We should be able to cache the response in memory #* TODO: Attributes lastClass, firstClass #* TODO: filter by menu / page / subpage / type #* #** @helpers['ion_navigation'] = (args...) -> tagName = 'ion_navigation' # default class when displaying current/active page activeClass = 'active' # default menu menu_id = 1 # default level page_level = 0 # # Parsing attributes if they do exist # if args.length>1 attrs = args[0] # # Class to be used for current/active page # activeClass = attrs.activeClass if attrs.activeClass # # Menu to use # menu_id = attrs.menu_id if attrs.menu_id # # Page level # page_level = attrs.level if attrs.level # # We are launching an asynchronous request, # we need to register it, to be able to wait for it to be finished # and insert the content in the response sent to browser # requestId = @registerRequest( tagName ) # # Finished callback # finished = (response) => @requestCompleted requestId, response displayedInNav = "page.appears = 1 AND " # # # Retrieve pages # DB.query( "SELECT page_lang.title, page_lang.subtitle, page_lang.url, page.home, page_lang.nav_title, page.link "+ "FROM page_lang, page "+ "WHERE page_lang.id_page = page.id_page AND "+ "page_lang.lang = '#{@lang}' AND "+ "page.id_menu = #{menu_id} AND "+ displayedInNav + "page.level = #{page_level} "+ "ORDER BY page.ordering", Page) .on 'success', (pages) => # # Content that will be built # htmlResponse = "" # # Looping though all pages # for page in pages #console.log page.title, page.url # # For home page, url becomes / (we hide the real url) # page.url = "/" if page.home # # Set variables that will be used in the rendered view # @navigation = page @navigation.title = @navigation.nav_title if @navigation.nav_title isnt '' @navigation.class = if @navigation.id_page is @page.id_page then activeClass else '' # # If a link is declared, we replace url by the link # if page.link then @navigation.url = page.link # # Render nested tags, # last args is the nested content to render # if args.length>=1 template = args[args.length-1] # For Jade engine if @template_engine is "jade" fn = jade.compile( template, @ ) htmlResponse += fn( @ ) # Compile the nested content to html # For Eco and CoffeeCup else htmlResponse += cede template # Compile the nested content to html #args[args.length-1]() finished( htmlResponse ) .on 'failure', (err) -> console.log "database error : ", err finished() # # Inserting placeholder in the html for replacement once async request are finished # text "{**#{requestId.name}**}" #***** #* Displaying navigation tree #* use @navigation.fieldName in nested content, #* ie: @navigation.url, @navigation.title... (@navigation contains fields of the page_lang record) #* #* TODO: Menu selection by name, default to id = 1 #* TODO: We should be able to cache the response in memory #* TODO: Attributes lastClass, firstClass #* TODO: Active class #* #** @helpers['ion_navigationTree'] = (args...) -> tagName = 'ion_navigationTree' # default class when displaying current/active page activeClass = 'active' # default menu menu_id = 1 # default level page_level = 100 level_open = "<ul>" # HTML inserted before each level change level_close = "</ul>" # HTML inserted after each level change item_open = "<li>" # HTML inserted before each menu item item_close = "</li>" # HTML inserted after each menu item # # Parsing attributes if they do exist # if args.length>1 attrs = args[0] # # Class to be used for current/active page # activeClass = attrs.activeClass if attrs.activeClass # # Menu to use # menu_id = attrs.menu_id if attrs.menu_id # # Page level # page_level = attrs.level if attrs.level? # # Items & level HTML tags # level_open = attrs.level_open if attrs.level_open level_close = attrs.level_close if attrs.level_close item_open = attrs.item_open if attrs.item_open item_close = attrs.item_close if attrs.item_close # # We are launching an asynchronous request, # we need to register it, to be able to wait for it to be finished # and insert the content in the response sent to browser # requestId = @registerRequest( tagName ) # # Finished callback # finished = (response) => @requestCompleted requestId, response # # Getting a list of pages, with child pages # # We're doing recursive calls to build the tree. # Recursion is a bit painful in async programming, so we use some tricks : # - request_counter is used to know when all request are finished, so we can build and sent the response # - we gather all responses and build a "path" value to be able to use it to sort results, in an order that matches the tree structure # # # # Retrieve pages in menu # responses = [] # # Request counter is used to define when all async requests are finished # (+1 when launching a request, -1 once finishing, 0 everything is done) # request_counter = 1 # # Building the response path # path = "" # # Send response once async requests are done # displayResponse = => request_counter-- # # Requests are finished, building & sending the response # if request_counter==0 # # Sorting responses, using the path value # responses.sort( (a,b) -> return 1 if a.path > b.path return -1 if a.path < b.path return 0 ) # # Building the response message # htmlResponse = "" currentLevel = 0 firstResult = true for line in responses # # For home page, url becomes / (we hide the real url) # line.url = "/" if line.home # # Set variables that will be used in the rendered view # @navigation = line @navigation.title = @navigation.nav_title if @navigation.nav_title isnt '' @navigation.class = if @navigation.id_page is @page.id_page then activeClass else '' levelChanged = false if @navigation.level > currentLevel htmlResponse += level_open currentLevel = @navigation.level levelChanged = true else if @navigation.level < currentLevel for index in [1..currentLevel-@navigation.level] htmlResponse += level_close currentLevel = @navigation.level levelChanged = true else htmlResponse += item_close unless firstResult firstResult = false # # Render nested tags, # last args is the nested content to render # if args.length>=1 template = args[args.length-1] htmlResponse += item_open # For Jade engine if @template_engine is "jade" fn = jade.compile( template, @ ) htmlResponse += fn( @ ) # Compile the nested content to html # For Eco and CoffeeCup else htmlResponse += cede template # Compile the nested content to html # response += "<option value='#{line.value}'>" # response += "&#160;&#187;&#160;" for level in [1..line.level] unless line.level<1 # response += "#{line.title}</option>" # # Send response # finished( htmlResponse ) # # Recursive function to retrieve pages # getParents = (path, id_menu, id_parent, callback) => # # Launch query # Sorry, not using Sequelize yet there, but should be used for compatibility with all supported DB engines # DB.query( """ SELECT page_lang.title, page_lang.subtitle, page_lang.nav_title, page_lang.url, page.level, page.id_menu, page.id_page, page.home, page.online, page.appears, page.has_url, page.link FROM page_lang, page, menu WHERE page_lang.lang = '#{@lang}' AND menu.id_menu = #{id_menu} AND page.id_parent = #{id_parent} AND page_lang.id_page = page.id_page AND page.id_menu = menu.id_menu ORDER BY page.ordering """, Page ) # # On success, store results + launch additional recursive queries # .on 'success', (results) => index = 0 for page in results index++ newPath = path + index + "/" # # Storing results in the responses array # currentResponse = {} currentResponse["path"] = newPath currentResponse["value"] = page.id_page currentResponse["title"] = page.title currentResponse["subtitle"] = page.subtitle currentResponse["nav_title"] = page.nav_title currentResponse["level"] = page.level currentResponse["url"] = page.url currentResponse["has_url"] = page.has_url currentResponse["home"] = page.home currentResponse["id_page"] = page.id_page currentResponse["online"] = page.online currentResponse["link"] = page.link # # If a link is declared, we replace url by the link # if page.link then currentResponse["url"] = page.link if (page.appears is 1) and (page.online or @req.session.usergroup_level >= 1000 ) responses.push( currentResponse ) # # Use to watch async queries termination # request_counter++ # # Search for child pages of the current page # getParents( newPath, id_menu, page.id_page, callback ) callback() .on 'failure', (err) -> console.log "GetParents error ", err # # Launch the first request # getParents( path, 1, 0, displayResponse ) # # Inserting placeholder in the html for replacement once async request are finished # text "{**#{requestId.name}**}"
[ { "context": "should.equal(1)\n compareVer.lt(\"1.7.0.2\", \"1.7.0.10\").should.equal(1)\n\n it 'compare 5', ->\n ", "end": 1085, "score": 0.9755693674087524, "start": 1077, "tag": "IP_ADDRESS", "value": "1.7.0.10" } ]
node_modules/compare-ver/tests/lt.coffee
gthememarket/ghost_local_themesxxx
3
if typeof require == 'function' should = require('should') compareVer = require('../index') describe 'compareVer #lt', -> it 'compare 0', -> compareVer.lt("1.7.2","1.7.1").should.equal(-1) compareVer.lt("1.7.10","1.7.1").should.equal(-1) compareVer.lt("1.8.0", "1.7.10").should.equal(-1) it 'compare 1', -> compareVer.lt("1.7.0", "1.7").should.equal(-1) compareVer.lt("1.8.0", "1.7").should.equal(-1) it 'compare 2', -> compareVer.lt("1.7", "1.7").should.equal(0) compareVer.lt("1.7.0", "1.7.0").should.equal(0) compareVer.lt("1.7.10", "1.7.10").should.equal(0) it 'compare 3', -> compareVer.lt("1.7.0.0", "1.7.0.0").should.equal(0) compareVer.lt("1.7.00", "1.7.00").should.equal(0) compareVer.lt("1.7.0", "1.7.00").should.equal(0) compareVer.lt("1.7.0", "1.7.000").should.equal(0) it 'compare 4', -> compareVer.lt("1.7.2", "1.7.10").should.equal(1) compareVer.lt("1.7.2", "1.7.10").should.equal(1) compareVer.lt("1.7.0.2", "1.7.0.10").should.equal(1) it 'compare 5', -> compareVer.lt("1.6", "1.6.10").should.equal(1) compareVer.lt("1.6.0", "1.6.10").should.equal(1) compareVer.lt("1.6.10", "1.6.10.0").should.equal(1) it 'fompare 6', -> compareVer.lt("1.7.1", "1.7.10").should.equal(1) compareVer.lt("1.7", "1.7.0").should.equal(1) compareVer.lt("1.7.001", "1.7.01").should.equal(1) it 'compare 7', -> compareVer.lt(1.00001, "1.7").should.equal(-2) compareVer.lt(1.00001, 1.00002).should.equal(-2) compareVer.lt("1.7", 1.00001).should.equal(-2) it 'compare 8', -> compareVer.lt("1.7.a", "1.7").should.equal(-3) compareVer.lt("1.b.0", "1.7").should.equal(-3) compareVer.lt('sdsads', "1.7").should.equal(-3) compareVer.lt("1.7", "1.7.a").should.equal(-3) compareVer.lt("1.7", "1.b").should.equal(-3) compareVer.lt("1.7", 'sdsads').should.equal(-3) it 'compare 9', -> compareVer.lt().should.equal(-100) compareVer.lt("1.7.1").should.equal(-100) compareVer.lt("1.7.1","1.7.1","1.7.1").should.equal(-100) it 'compare 10', -> compareVer.lt("1.07", "1.7").should.equal(1) compareVer.lt("1.007", "1.07").should.equal(1) compareVer.lt("1.0.07", "1.0.7").should.equal(1) it 'compare 11',-> compareVer.lt("01.0.7", "1.0.7").should.equal(0) compareVer.lt("1.0.7", "01.0.7").should.equal(0)
61800
if typeof require == 'function' should = require('should') compareVer = require('../index') describe 'compareVer #lt', -> it 'compare 0', -> compareVer.lt("1.7.2","1.7.1").should.equal(-1) compareVer.lt("1.7.10","1.7.1").should.equal(-1) compareVer.lt("1.8.0", "1.7.10").should.equal(-1) it 'compare 1', -> compareVer.lt("1.7.0", "1.7").should.equal(-1) compareVer.lt("1.8.0", "1.7").should.equal(-1) it 'compare 2', -> compareVer.lt("1.7", "1.7").should.equal(0) compareVer.lt("1.7.0", "1.7.0").should.equal(0) compareVer.lt("1.7.10", "1.7.10").should.equal(0) it 'compare 3', -> compareVer.lt("1.7.0.0", "1.7.0.0").should.equal(0) compareVer.lt("1.7.00", "1.7.00").should.equal(0) compareVer.lt("1.7.0", "1.7.00").should.equal(0) compareVer.lt("1.7.0", "1.7.000").should.equal(0) it 'compare 4', -> compareVer.lt("1.7.2", "1.7.10").should.equal(1) compareVer.lt("1.7.2", "1.7.10").should.equal(1) compareVer.lt("1.7.0.2", "192.168.3.11").should.equal(1) it 'compare 5', -> compareVer.lt("1.6", "1.6.10").should.equal(1) compareVer.lt("1.6.0", "1.6.10").should.equal(1) compareVer.lt("1.6.10", "1.6.10.0").should.equal(1) it 'fompare 6', -> compareVer.lt("1.7.1", "1.7.10").should.equal(1) compareVer.lt("1.7", "1.7.0").should.equal(1) compareVer.lt("1.7.001", "1.7.01").should.equal(1) it 'compare 7', -> compareVer.lt(1.00001, "1.7").should.equal(-2) compareVer.lt(1.00001, 1.00002).should.equal(-2) compareVer.lt("1.7", 1.00001).should.equal(-2) it 'compare 8', -> compareVer.lt("1.7.a", "1.7").should.equal(-3) compareVer.lt("1.b.0", "1.7").should.equal(-3) compareVer.lt('sdsads', "1.7").should.equal(-3) compareVer.lt("1.7", "1.7.a").should.equal(-3) compareVer.lt("1.7", "1.b").should.equal(-3) compareVer.lt("1.7", 'sdsads').should.equal(-3) it 'compare 9', -> compareVer.lt().should.equal(-100) compareVer.lt("1.7.1").should.equal(-100) compareVer.lt("1.7.1","1.7.1","1.7.1").should.equal(-100) it 'compare 10', -> compareVer.lt("1.07", "1.7").should.equal(1) compareVer.lt("1.007", "1.07").should.equal(1) compareVer.lt("1.0.07", "1.0.7").should.equal(1) it 'compare 11',-> compareVer.lt("01.0.7", "1.0.7").should.equal(0) compareVer.lt("1.0.7", "01.0.7").should.equal(0)
true
if typeof require == 'function' should = require('should') compareVer = require('../index') describe 'compareVer #lt', -> it 'compare 0', -> compareVer.lt("1.7.2","1.7.1").should.equal(-1) compareVer.lt("1.7.10","1.7.1").should.equal(-1) compareVer.lt("1.8.0", "1.7.10").should.equal(-1) it 'compare 1', -> compareVer.lt("1.7.0", "1.7").should.equal(-1) compareVer.lt("1.8.0", "1.7").should.equal(-1) it 'compare 2', -> compareVer.lt("1.7", "1.7").should.equal(0) compareVer.lt("1.7.0", "1.7.0").should.equal(0) compareVer.lt("1.7.10", "1.7.10").should.equal(0) it 'compare 3', -> compareVer.lt("1.7.0.0", "1.7.0.0").should.equal(0) compareVer.lt("1.7.00", "1.7.00").should.equal(0) compareVer.lt("1.7.0", "1.7.00").should.equal(0) compareVer.lt("1.7.0", "1.7.000").should.equal(0) it 'compare 4', -> compareVer.lt("1.7.2", "1.7.10").should.equal(1) compareVer.lt("1.7.2", "1.7.10").should.equal(1) compareVer.lt("1.7.0.2", "PI:IP_ADDRESS:192.168.3.11END_PI").should.equal(1) it 'compare 5', -> compareVer.lt("1.6", "1.6.10").should.equal(1) compareVer.lt("1.6.0", "1.6.10").should.equal(1) compareVer.lt("1.6.10", "1.6.10.0").should.equal(1) it 'fompare 6', -> compareVer.lt("1.7.1", "1.7.10").should.equal(1) compareVer.lt("1.7", "1.7.0").should.equal(1) compareVer.lt("1.7.001", "1.7.01").should.equal(1) it 'compare 7', -> compareVer.lt(1.00001, "1.7").should.equal(-2) compareVer.lt(1.00001, 1.00002).should.equal(-2) compareVer.lt("1.7", 1.00001).should.equal(-2) it 'compare 8', -> compareVer.lt("1.7.a", "1.7").should.equal(-3) compareVer.lt("1.b.0", "1.7").should.equal(-3) compareVer.lt('sdsads', "1.7").should.equal(-3) compareVer.lt("1.7", "1.7.a").should.equal(-3) compareVer.lt("1.7", "1.b").should.equal(-3) compareVer.lt("1.7", 'sdsads').should.equal(-3) it 'compare 9', -> compareVer.lt().should.equal(-100) compareVer.lt("1.7.1").should.equal(-100) compareVer.lt("1.7.1","1.7.1","1.7.1").should.equal(-100) it 'compare 10', -> compareVer.lt("1.07", "1.7").should.equal(1) compareVer.lt("1.007", "1.07").should.equal(1) compareVer.lt("1.0.07", "1.0.7").should.equal(1) it 'compare 11',-> compareVer.lt("01.0.7", "1.0.7").should.equal(0) compareVer.lt("1.0.7", "01.0.7").should.equal(0)
[ { "context": "n. Begin eens met je naam, bijvoorbeeld\\nnaam = \\\"Henk\\\"\",\n answer: /naam\\s*=\\s*\\\"[\\w\\s]*\\\"/,\n ", "end": 220, "score": 0.998333752155304, "start": 216, "tag": "NAME", "value": "Henk" }, { "context": "ekje, gevolgd door accolades. Bijvoorbeeld zo:\\n\\\"Hallo, \\#\\{naam\\}\\\"\",\n answer: /^\\s*\\\"[\\w\\s\\,]+\\#\\", "end": 1133, "score": 0.9996665716171265, "start": 1128, "tag": "NAME", "value": "Hallo" }, { "context": "\n default: \"Dat is niet goed. Typte je \\\"Hallo, \\#\\{naam\\}?\\\"\"\n }\n }),\n new Question(\n ", "end": 1433, "score": 0.9995458126068115, "start": 1428, "tag": "NAME", "value": "Hallo" }, { "context": "toewijzen van een variabele (bijvoorbeeld naam = \"Henk\"). Om te kijken of een uitspraak true of false is", "end": 3095, "score": 0.9884248971939087, "start": 3091, "tag": "NAME", "value": "Henk" }, { "context": "an.\\nTyp eens:\\nif naam == \\\"je naam\\\"\\n puts \\\"Hallo, \\#\\{naam\\}!\\\"\\nend\",\n answer: /if\\s*naam\\s*", "end": 3855, "score": 0.6516128778457642, "start": 3850, "tag": "NAME", "value": "Hallo" } ]
_coffeescripts/interactive_lessons/hoofdstuk1.coffee
b1592/b1592.github.io
2
this.lesson = new Lesson([ new Question( { description: "Laten we bij het begin beginnen! In Ruby kun je makkelijk variabelen gebruiken om iets op te slaan. Begin eens met je naam, bijvoorbeeld\nnaam = \"Henk\"", answer: /naam\s*=\s*\"[\w\s]*\"/, possible_errors: { quotes_vergeten: /^naam\s*=\s*\"?[\w\s]+\"?$/, dubbele_is: /^naam\s*==\s*\"?[\w\s]+\"?$/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", dubbele_is: "Gebruik een enkel =-teken bij het toewijzen van variabelen." default: "Dat is niet goed. Typte je naam = \"je naam\"?" } }), new Question( { description: "Ruby onthoudt alles. Typ in: naam", answer: /^naam$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Typte je naam?" } }), new Question( { description: "Zie je? Ruby weet je naam nog. Een stuk tekst tussen aanhalingstekens heet een String. Als je een variabele in een string wilt zetten, gebruik je een hekje, gevolgd door accolades. Bijvoorbeeld zo:\n\"Hallo, \#\{naam\}\"", answer: /^\s*\"[\w\s\,]+\#\{naam\}\!?\"$/, possible_errors: { quotes_vergeten: /^\s*\"?[\w\s\,]+\#\{naam\}\!?\"?$/, }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", default: "Dat is niet goed. Typte je \"Hallo, \#\{naam\}?\"" } }), new Question( { description: "Ruby kan ook rekenen. Typ maar eens 3 + 4.", answer: /^-?\d+\s*\+\s*-?\d+\s*$/, possible_errors: { min: /^\d+\s*-\s*\d+\s*$/ }, error_messages: { min: "Inderdaad, Ruby kan ook getallen van elkaar aftrekken! Typ je toch even 3 + 4?", default: "Dat is niet goed. Tel je twee getallen op?" } }), new Question( { description: "Heel goed. Wat dacht je van 5 * 8?", answer: /^-?\d+\s*\*\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je * (een sterretje)?" } }), new Question( { description: "* (sterretje) betekent 'keer'. Wat denk je dat 2 ** 4 doet?", answer: /^-?\d+\s*\*\*\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je **?" } }), new Question( { description: "** is machtsverheffen. Nu gaan we aan Ruby vragen of een uitspraak 'waar' of 'niet waar' is. Typ eens 3 < 5 (drie is kleiner dan 5.)", answer: /^3\s*<\s*5\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik < ('kleiner dan'.)" } }), new Question( { description: "true! Typ nu eens 1 + 1 == 3.", answer: /^1\s*\+\s*1\s*==\s*3\s*$/, possible_errors: { enkele_is: /^1\s*\+\s*1\s*=\s*3\s*$/ }, error_messages: { enkele_is: 'Gebruik een dubbel is-teken! Een enkel is-teken wordt gebruikt voor het toewijzen van een variabele (bijvoorbeeld naam = "Henk"). Om te kijken of een uitspraak true of false is heb je == nodig. Ruby snapt het niet, zie je? Typ 1 + 1 == 3.' default: "Dat is niet goed. Typ je 1 + 1 == 3?" } }), new Question( { description: "1 + 1 is natuurlijk geen 3, dus Ruby geeft false. Typ nu eens 5 != 10 (vijf is niet gelijk aan tien.)", answer: /^-?\d+\s*!=\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je != (is niet gelijk aan?)" } }), new Question( { description: "Goed gedaan! Nu gaan we logica toevoegen. Een if-statement gebruik je om iets alleen te laten uitvoeren als aan een voorwaarde wordt voldaan.\nTyp eens:\nif naam == \"je naam\"\n puts \"Hallo, \#\{naam\}!\"\nend", answer: /if\s*naam\s*==\s*\"[\w\s]*\"\s*\n\s*puts\s*\"[\w\s\!\,]+\#\{naam\}\!?"\s*\n\s*end/, possible_errors: { quotes_vergeten: /if\s*naam\s*==\s*\"?[\w\s]*\"?\s*\n\s*puts\s*\"?[\w\s\!\,]+\#\{naam\}\!?"?\s*\n\s*end/, enkele_is: /if\s*naam\s*=\s*\"[\w\s]*\"\s*\n\s*puts\s*\"[\w\s\!\,]+\#\{naam\}\!?"\s*\n\s*end/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", enkele_is: "Gebruik in een if-statement altijd een dubbel =-teken. Bij toewijzen van variabelen gebruik je een enkel =-teken." default: "Dat is niet goed. Typte je\nif naam == \"je naam\"\n puts \"Hallo, \#\{naam\}!\"\nend" } }), new Question( { description: "Oke! Bij een if kun je ook een else zetten. Dit gebruik je als je nog een andere mogelijkheid verwacht. Let op dat je alsnog een end krijgt aan het einde.\nTyp eens:\nif 9 \> 10\n puts \"Dit is bijzonder!\"\nelse\n puts \"Gelukkig, het klopt!\"\nend", answer: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*else\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*end\s*$/, possible_errors: { quotes_vergeten: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"?[\w\s\,\!]+\"?\s*\n\s*else\s*\n\s*puts\s*\"?[\w\s\,\!]+\"?\s*\n\s*end\s*$/, end_vergeten: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*else\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*$/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", end_vergeten: "Let op dat je ook bij else afsluit met end!", default: "Dat is niet goed. Typte je\nif 9 \> 10\n puts \"Dit is bijzonder!\"\nelse\n puts \"Gelukkig, het klopt!\"\nend" } }) ])
200632
this.lesson = new Lesson([ new Question( { description: "Laten we bij het begin beginnen! In Ruby kun je makkelijk variabelen gebruiken om iets op te slaan. Begin eens met je naam, bijvoorbeeld\nnaam = \"<NAME>\"", answer: /naam\s*=\s*\"[\w\s]*\"/, possible_errors: { quotes_vergeten: /^naam\s*=\s*\"?[\w\s]+\"?$/, dubbele_is: /^naam\s*==\s*\"?[\w\s]+\"?$/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", dubbele_is: "Gebruik een enkel =-teken bij het toewijzen van variabelen." default: "Dat is niet goed. Typte je naam = \"je naam\"?" } }), new Question( { description: "Ruby onthoudt alles. Typ in: naam", answer: /^naam$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Typte je naam?" } }), new Question( { description: "Zie je? Ruby weet je naam nog. Een stuk tekst tussen aanhalingstekens heet een String. Als je een variabele in een string wilt zetten, gebruik je een hekje, gevolgd door accolades. Bijvoorbeeld zo:\n\"<NAME>, \#\{naam\}\"", answer: /^\s*\"[\w\s\,]+\#\{naam\}\!?\"$/, possible_errors: { quotes_vergeten: /^\s*\"?[\w\s\,]+\#\{naam\}\!?\"?$/, }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", default: "Dat is niet goed. Typte je \"<NAME>, \#\{naam\}?\"" } }), new Question( { description: "Ruby kan ook rekenen. Typ maar eens 3 + 4.", answer: /^-?\d+\s*\+\s*-?\d+\s*$/, possible_errors: { min: /^\d+\s*-\s*\d+\s*$/ }, error_messages: { min: "Inderdaad, Ruby kan ook getallen van elkaar aftrekken! Typ je toch even 3 + 4?", default: "Dat is niet goed. Tel je twee getallen op?" } }), new Question( { description: "Heel goed. Wat dacht je van 5 * 8?", answer: /^-?\d+\s*\*\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je * (een sterretje)?" } }), new Question( { description: "* (sterretje) betekent 'keer'. Wat denk je dat 2 ** 4 doet?", answer: /^-?\d+\s*\*\*\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je **?" } }), new Question( { description: "** is machtsverheffen. Nu gaan we aan Ruby vragen of een uitspraak 'waar' of 'niet waar' is. Typ eens 3 < 5 (drie is kleiner dan 5.)", answer: /^3\s*<\s*5\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik < ('kleiner dan'.)" } }), new Question( { description: "true! Typ nu eens 1 + 1 == 3.", answer: /^1\s*\+\s*1\s*==\s*3\s*$/, possible_errors: { enkele_is: /^1\s*\+\s*1\s*=\s*3\s*$/ }, error_messages: { enkele_is: 'Gebruik een dubbel is-teken! Een enkel is-teken wordt gebruikt voor het toewijzen van een variabele (bijvoorbeeld naam = "<NAME>"). Om te kijken of een uitspraak true of false is heb je == nodig. Ruby snapt het niet, zie je? Typ 1 + 1 == 3.' default: "Dat is niet goed. Typ je 1 + 1 == 3?" } }), new Question( { description: "1 + 1 is natuurlijk geen 3, dus Ruby geeft false. Typ nu eens 5 != 10 (vijf is niet gelijk aan tien.)", answer: /^-?\d+\s*!=\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je != (is niet gelijk aan?)" } }), new Question( { description: "Goed gedaan! Nu gaan we logica toevoegen. Een if-statement gebruik je om iets alleen te laten uitvoeren als aan een voorwaarde wordt voldaan.\nTyp eens:\nif naam == \"je naam\"\n puts \"<NAME>, \#\{naam\}!\"\nend", answer: /if\s*naam\s*==\s*\"[\w\s]*\"\s*\n\s*puts\s*\"[\w\s\!\,]+\#\{naam\}\!?"\s*\n\s*end/, possible_errors: { quotes_vergeten: /if\s*naam\s*==\s*\"?[\w\s]*\"?\s*\n\s*puts\s*\"?[\w\s\!\,]+\#\{naam\}\!?"?\s*\n\s*end/, enkele_is: /if\s*naam\s*=\s*\"[\w\s]*\"\s*\n\s*puts\s*\"[\w\s\!\,]+\#\{naam\}\!?"\s*\n\s*end/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", enkele_is: "Gebruik in een if-statement altijd een dubbel =-teken. Bij toewijzen van variabelen gebruik je een enkel =-teken." default: "Dat is niet goed. Typte je\nif naam == \"je naam\"\n puts \"Hallo, \#\{naam\}!\"\nend" } }), new Question( { description: "Oke! Bij een if kun je ook een else zetten. Dit gebruik je als je nog een andere mogelijkheid verwacht. Let op dat je alsnog een end krijgt aan het einde.\nTyp eens:\nif 9 \> 10\n puts \"Dit is bijzonder!\"\nelse\n puts \"Gelukkig, het klopt!\"\nend", answer: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*else\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*end\s*$/, possible_errors: { quotes_vergeten: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"?[\w\s\,\!]+\"?\s*\n\s*else\s*\n\s*puts\s*\"?[\w\s\,\!]+\"?\s*\n\s*end\s*$/, end_vergeten: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*else\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*$/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", end_vergeten: "Let op dat je ook bij else afsluit met end!", default: "Dat is niet goed. Typte je\nif 9 \> 10\n puts \"Dit is bijzonder!\"\nelse\n puts \"Gelukkig, het klopt!\"\nend" } }) ])
true
this.lesson = new Lesson([ new Question( { description: "Laten we bij het begin beginnen! In Ruby kun je makkelijk variabelen gebruiken om iets op te slaan. Begin eens met je naam, bijvoorbeeld\nnaam = \"PI:NAME:<NAME>END_PI\"", answer: /naam\s*=\s*\"[\w\s]*\"/, possible_errors: { quotes_vergeten: /^naam\s*=\s*\"?[\w\s]+\"?$/, dubbele_is: /^naam\s*==\s*\"?[\w\s]+\"?$/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", dubbele_is: "Gebruik een enkel =-teken bij het toewijzen van variabelen." default: "Dat is niet goed. Typte je naam = \"je naam\"?" } }), new Question( { description: "Ruby onthoudt alles. Typ in: naam", answer: /^naam$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Typte je naam?" } }), new Question( { description: "Zie je? Ruby weet je naam nog. Een stuk tekst tussen aanhalingstekens heet een String. Als je een variabele in een string wilt zetten, gebruik je een hekje, gevolgd door accolades. Bijvoorbeeld zo:\n\"PI:NAME:<NAME>END_PI, \#\{naam\}\"", answer: /^\s*\"[\w\s\,]+\#\{naam\}\!?\"$/, possible_errors: { quotes_vergeten: /^\s*\"?[\w\s\,]+\#\{naam\}\!?\"?$/, }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", default: "Dat is niet goed. Typte je \"PI:NAME:<NAME>END_PI, \#\{naam\}?\"" } }), new Question( { description: "Ruby kan ook rekenen. Typ maar eens 3 + 4.", answer: /^-?\d+\s*\+\s*-?\d+\s*$/, possible_errors: { min: /^\d+\s*-\s*\d+\s*$/ }, error_messages: { min: "Inderdaad, Ruby kan ook getallen van elkaar aftrekken! Typ je toch even 3 + 4?", default: "Dat is niet goed. Tel je twee getallen op?" } }), new Question( { description: "Heel goed. Wat dacht je van 5 * 8?", answer: /^-?\d+\s*\*\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je * (een sterretje)?" } }), new Question( { description: "* (sterretje) betekent 'keer'. Wat denk je dat 2 ** 4 doet?", answer: /^-?\d+\s*\*\*\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je **?" } }), new Question( { description: "** is machtsverheffen. Nu gaan we aan Ruby vragen of een uitspraak 'waar' of 'niet waar' is. Typ eens 3 < 5 (drie is kleiner dan 5.)", answer: /^3\s*<\s*5\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik < ('kleiner dan'.)" } }), new Question( { description: "true! Typ nu eens 1 + 1 == 3.", answer: /^1\s*\+\s*1\s*==\s*3\s*$/, possible_errors: { enkele_is: /^1\s*\+\s*1\s*=\s*3\s*$/ }, error_messages: { enkele_is: 'Gebruik een dubbel is-teken! Een enkel is-teken wordt gebruikt voor het toewijzen van een variabele (bijvoorbeeld naam = "PI:NAME:<NAME>END_PI"). Om te kijken of een uitspraak true of false is heb je == nodig. Ruby snapt het niet, zie je? Typ 1 + 1 == 3.' default: "Dat is niet goed. Typ je 1 + 1 == 3?" } }), new Question( { description: "1 + 1 is natuurlijk geen 3, dus Ruby geeft false. Typ nu eens 5 != 10 (vijf is niet gelijk aan tien.)", answer: /^-?\d+\s*!=\s*-?\d+\s*$/, possible_errors: { }, error_messages: { default: "Dat is niet goed. Gebruik je != (is niet gelijk aan?)" } }), new Question( { description: "Goed gedaan! Nu gaan we logica toevoegen. Een if-statement gebruik je om iets alleen te laten uitvoeren als aan een voorwaarde wordt voldaan.\nTyp eens:\nif naam == \"je naam\"\n puts \"PI:NAME:<NAME>END_PI, \#\{naam\}!\"\nend", answer: /if\s*naam\s*==\s*\"[\w\s]*\"\s*\n\s*puts\s*\"[\w\s\!\,]+\#\{naam\}\!?"\s*\n\s*end/, possible_errors: { quotes_vergeten: /if\s*naam\s*==\s*\"?[\w\s]*\"?\s*\n\s*puts\s*\"?[\w\s\!\,]+\#\{naam\}\!?"?\s*\n\s*end/, enkele_is: /if\s*naam\s*=\s*\"[\w\s]*\"\s*\n\s*puts\s*\"[\w\s\!\,]+\#\{naam\}\!?"\s*\n\s*end/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", enkele_is: "Gebruik in een if-statement altijd een dubbel =-teken. Bij toewijzen van variabelen gebruik je een enkel =-teken." default: "Dat is niet goed. Typte je\nif naam == \"je naam\"\n puts \"Hallo, \#\{naam\}!\"\nend" } }), new Question( { description: "Oke! Bij een if kun je ook een else zetten. Dit gebruik je als je nog een andere mogelijkheid verwacht. Let op dat je alsnog een end krijgt aan het einde.\nTyp eens:\nif 9 \> 10\n puts \"Dit is bijzonder!\"\nelse\n puts \"Gelukkig, het klopt!\"\nend", answer: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*else\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*end\s*$/, possible_errors: { quotes_vergeten: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"?[\w\s\,\!]+\"?\s*\n\s*else\s*\n\s*puts\s*\"?[\w\s\,\!]+\"?\s*\n\s*end\s*$/, end_vergeten: /^if\s*9\s*>\s*10\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*else\s*\n\s*puts\s*\"[\w\s\,\!]+\"\s*\n\s*$/ }, error_messages: { quotes_vergeten: "Let op de aanhalingstekens.", end_vergeten: "Let op dat je ook bij else afsluit met end!", default: "Dat is niet goed. Typte je\nif 9 \> 10\n puts \"Dit is bijzonder!\"\nelse\n puts \"Gelukkig, het klopt!\"\nend" } }) ])
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998464584350586, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999288320541382, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" } ]
library/membrane/securing.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" asciify = require "asciify" connect = require "connect" logger = require "winston" assert = require "assert" events = require "eventemitter2" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" url = require "url" {Barebones} = require "./skeleton" {RedisClient} = require "../applied/redis" tools = require "../nucleus/toolkit" # This is an abstract base class API stub service. Its purpose is # providing the boilerplate for ensuring that HTTP/S connection is # going through the master server! If a request is not going via # master server then deny current request with an error code. Be # aware that this compound will be effective for all HTTP methods. module.exports.OnlyMaster = class OnlyMaster extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A hook that will be called prior to firing up the processing # of the service. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. ignition: (request, response, next) -> str = (addr) -> addr?.address or null inbound = request.connection.address() assert server = @kernel.server.address() assert secure = @kernel.secure.address() assert not _.isEmpty try "#{str(inbound)}" assert master = try nconf.get "master:host" return next() if str(inbound) is str(server) return next() if str(inbound) is str(secure) return next() if str(inbound) is master content = "please use the master server" reason = "an attempt of direct access" response.writeHead 401, "#{reason}" return response.end content # This is an abstract base class API stub service. Its purpose is # providing the boilerplate for ensuring that HTTP/S connection is # going through the HTTPS channel. If a request is not going via # SSL transport then redirect the current request to such one. Be # aware that this compound will be effective for all HTTP methods. module.exports.OnlySsl = class OnlySsl extends OnlyMaster # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A hook that will be called prior to firing up the processing # of the service. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. ignition: (request, response, next) -> connection = request.connection or {} encrypted = connection.encrypted or no assert headers = request.headers or {} protocol = headers["x-forwarded-proto"] return next() if _.isObject encrypted return next() if protocol is "https" protectedUrl = tools.urlOfMaster yes current = try url.parse protectedUrl assert current.pathname = request.url assert current.query = request.params assert compiled = url.format current return response.redirect compiled
73741
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" asciify = require "asciify" connect = require "connect" logger = require "winston" assert = require "assert" events = require "eventemitter2" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" url = require "url" {Barebones} = require "./skeleton" {RedisClient} = require "../applied/redis" tools = require "../nucleus/toolkit" # This is an abstract base class API stub service. Its purpose is # providing the boilerplate for ensuring that HTTP/S connection is # going through the master server! If a request is not going via # master server then deny current request with an error code. Be # aware that this compound will be effective for all HTTP methods. module.exports.OnlyMaster = class OnlyMaster extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A hook that will be called prior to firing up the processing # of the service. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. ignition: (request, response, next) -> str = (addr) -> addr?.address or null inbound = request.connection.address() assert server = @kernel.server.address() assert secure = @kernel.secure.address() assert not _.isEmpty try "#{str(inbound)}" assert master = try nconf.get "master:host" return next() if str(inbound) is str(server) return next() if str(inbound) is str(secure) return next() if str(inbound) is master content = "please use the master server" reason = "an attempt of direct access" response.writeHead 401, "#{reason}" return response.end content # This is an abstract base class API stub service. Its purpose is # providing the boilerplate for ensuring that HTTP/S connection is # going through the HTTPS channel. If a request is not going via # SSL transport then redirect the current request to such one. Be # aware that this compound will be effective for all HTTP methods. module.exports.OnlySsl = class OnlySsl extends OnlyMaster # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A hook that will be called prior to firing up the processing # of the service. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. ignition: (request, response, next) -> connection = request.connection or {} encrypted = connection.encrypted or no assert headers = request.headers or {} protocol = headers["x-forwarded-proto"] return next() if _.isObject encrypted return next() if protocol is "https" protectedUrl = tools.urlOfMaster yes current = try url.parse protectedUrl assert current.pathname = request.url assert current.query = request.params assert compiled = url.format current return response.redirect compiled
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" asciify = require "asciify" connect = require "connect" logger = require "winston" assert = require "assert" events = require "eventemitter2" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" url = require "url" {Barebones} = require "./skeleton" {RedisClient} = require "../applied/redis" tools = require "../nucleus/toolkit" # This is an abstract base class API stub service. Its purpose is # providing the boilerplate for ensuring that HTTP/S connection is # going through the master server! If a request is not going via # master server then deny current request with an error code. Be # aware that this compound will be effective for all HTTP methods. module.exports.OnlyMaster = class OnlyMaster extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A hook that will be called prior to firing up the processing # of the service. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. ignition: (request, response, next) -> str = (addr) -> addr?.address or null inbound = request.connection.address() assert server = @kernel.server.address() assert secure = @kernel.secure.address() assert not _.isEmpty try "#{str(inbound)}" assert master = try nconf.get "master:host" return next() if str(inbound) is str(server) return next() if str(inbound) is str(secure) return next() if str(inbound) is master content = "please use the master server" reason = "an attempt of direct access" response.writeHead 401, "#{reason}" return response.end content # This is an abstract base class API stub service. Its purpose is # providing the boilerplate for ensuring that HTTP/S connection is # going through the HTTPS channel. If a request is not going via # SSL transport then redirect the current request to such one. Be # aware that this compound will be effective for all HTTP methods. module.exports.OnlySsl = class OnlySsl extends OnlyMaster # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # A hook that will be called prior to firing up the processing # of the service. Please refer to this prototype signature for # information on the parameters it accepts. Beware, this hook # is asynchronously wired in, so consult with `async` package. # Please be sure invoke the `next` arg to proceed, if relevant. ignition: (request, response, next) -> connection = request.connection or {} encrypted = connection.encrypted or no assert headers = request.headers or {} protocol = headers["x-forwarded-proto"] return next() if _.isObject encrypted return next() if protocol is "https" protectedUrl = tools.urlOfMaster yes current = try url.parse protectedUrl assert current.pathname = request.url assert current.query = request.params assert compiled = url.format current return response.redirect compiled
[ { "context": " in using token'\n REQUEST_NEW_PASSWORD : 'requested a new password'\n CHANGED_PASSWORD : 'changed their p", "end": 1084, "score": 0.9989653825759888, "start": 1060, "tag": "PASSWORD", "value": "requested a new password" }, { "context": " a new password'\n CHANGED_PASSWORD : 'changed their password'\n REQUEST_EMAIL_CHANGE : 'requested pin t", "end": 1141, "score": 0.9985809326171875, "start": 1119, "tag": "PASSWORD", "value": "changed their password" }, { "context": "ecipientEmail\n username = forcedRecipientUsername\n traits.email = forcedRecipientEmail\n\n tr", "end": 2437, "score": 0.5280947685241699, "start": 2429, "tag": "USERNAME", "value": "Username" }, { "context": "sole.error \"flushing identify failed: #{err} @sent-hil\" if err\n callback err\n\n\n @track$ = secure ", "end": 2825, "score": 0.6446328163146973, "start": 2822, "tag": "USERNAME", "value": "hil" }, { "context": "cedRecipientEmail\n username = forcedRecipientUsername\n event.to = forcedRecipientEmail\n\n event.", "end": 3650, "score": 0.6327828168869019, "start": 3642, "tag": "USERNAME", "value": "Username" } ]
workers/social/lib/social/models/tracker.coffee
ezgikaysi/koding
1
bongo = require 'bongo' KodingError = require '../error' KodingLogger = require './kodinglogger' { secure, signature } = bongo _ = require 'lodash' KONFIG = require 'koding-config-manager' { socialapi } = KONFIG exchangeName = "#{socialapi.eventExchangeName}:0" exchangeOpts = { autoDelete: no, durable:yes, type :'fanout', confirm: true } try Analytics = require('analytics-node') analytics = new Analytics(KONFIG.segment) catch e console.warn 'Segment disabled because of missing configuration' module.exports = class Tracker extends bongo.Base @share() @set sharedMethods: static: track: (signature String, Object, Function) { forcedRecipientEmail, forcedRecipientUsername, defaultFromMail } = KONFIG.email EVENT_TYPE = 'api.mail_send' @types = START_REGISTER : 'started to register' FINISH_REGISTER : 'finished register' LOGGED_IN : 'logged in' CONFIRM_USING_TOKEN : 'confirmed & logged in using token' REQUEST_NEW_PASSWORD : 'requested a new password' CHANGED_PASSWORD : 'changed their password' REQUEST_EMAIL_CHANGE : 'requested pin to change email' CHANGED_EMAIL : 'changed their email' INVITED_TEAM : 'was invited to a team' INVITED_CREATE_TEAM : 'was invited to create a team' SENT_FEEDBACK : 'sent feedback' TEAMS_JOINED_TEAM : 'joined team' USER_ENABLED_2FA : 'enabled 2-factor auth' USER_DISABLED_2FA : 'disabled 2-factor auth' STACKS_START_BUILD : 'started stack build' STACKS_BUILD_SUCCESSFULLY : 'stack build successfully' STACKS_BUILD_FAILED : 'stack build failed' STACKS_REINIT : 'reinitialized stack' STACKS_DELETE : 'deleted stack' @properties = {} @properties[@types.FINISH_REGISTER] = { category: 'NewAccount', label: 'VerifyAccount' } @identifyAndTrack = (username, event, eventProperties = {}, callback = -> ) -> @identify username, {}, (err) => return callback err if err @track username, event, eventProperties, callback @identify = (username, traits = {}, callback = -> ) -> return callback null unless KONFIG.sendEventsToSegment # use `forcedRecipientEmail` for both username and email if forcedRecipientEmail username = forcedRecipientUsername traits.email = forcedRecipientEmail traits = @addDefaults traits analytics?.identify { userId: username, traits } return callback null unless analytics # force flush so identify call doesn't sit in queue, while events # from Go/other systems are being sent analytics.flush (err, batch) -> console.error "flushing identify failed: #{err} @sent-hil" if err callback err @track$ = secure (client, subject, options = {}, callback) -> unless account = client?.connection?.delegate err = '[Tracker.track$] Account is not set!' console.error err return callback new KodingError err { profile: { nickname } } = account event = { subject } { customEvent } = options if customEvent @handleCustomEvent subject, customEvent, nickname delete options.customEvent @track nickname, event, options callback() @track = (username, event, options = {}, callback = -> ) -> return callback null unless KONFIG.sendEventsToSegment _.extend options, @properties[event.subject] # use `forcedRecipientEmail` for both username and email if forcedRecipientEmail username = forcedRecipientUsername event.to = forcedRecipientEmail event.from or= defaultFromMail event.properties = @addDefaults { options, username } require('./socialapi/requests').publishMailEvent event, (err) -> callback err # do not cause trailing parameters @page = (userId, name, category, properties) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { userId, name, category, properties } @addDefaults options analytics?.page options @alias = (previousId, userId) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { previousId, userId } @addDefaults options analytics?.alias options @group = (groupId, userId) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { groupId, userId } @addDefaults options analytics?.group options @addDefaults = (opts) -> opts['env'] = KONFIG.environment opts['hostname'] = KONFIG.hostname opts @handleCustomEvent = (subject, params, nickname) -> { STACKS_START_BUILD, STACKS_BUILD_SUCCESSFULLY, STACKS_BUILD_FAILED, STACKS_REINIT, STACKS_DELETE } = @types return unless subject in [ STACKS_START_BUILD, STACKS_BUILD_SUCCESSFULLY STACKS_BUILD_FAILED, STACKS_REINIT, STACKS_DELETE ] { stackId, group } = params JGroup = require './group' JGroup.one { slug : group }, (err, group) -> return console.log err if err { notifyAdmins } = require './notify' notifyAdmins group, 'StackStatusChanged', id : stackId group : group.slug if subject in [ STACKS_BUILD_SUCCESSFULLY, STACKS_BUILD_FAILED ] message = "#{nickname}'s #{subject}" else message = "#{nickname} #{subject}" KodingLogger.log group, message
75971
bongo = require 'bongo' KodingError = require '../error' KodingLogger = require './kodinglogger' { secure, signature } = bongo _ = require 'lodash' KONFIG = require 'koding-config-manager' { socialapi } = KONFIG exchangeName = "#{socialapi.eventExchangeName}:0" exchangeOpts = { autoDelete: no, durable:yes, type :'fanout', confirm: true } try Analytics = require('analytics-node') analytics = new Analytics(KONFIG.segment) catch e console.warn 'Segment disabled because of missing configuration' module.exports = class Tracker extends bongo.Base @share() @set sharedMethods: static: track: (signature String, Object, Function) { forcedRecipientEmail, forcedRecipientUsername, defaultFromMail } = KONFIG.email EVENT_TYPE = 'api.mail_send' @types = START_REGISTER : 'started to register' FINISH_REGISTER : 'finished register' LOGGED_IN : 'logged in' CONFIRM_USING_TOKEN : 'confirmed & logged in using token' REQUEST_NEW_PASSWORD : '<PASSWORD>' CHANGED_PASSWORD : '<PASSWORD>' REQUEST_EMAIL_CHANGE : 'requested pin to change email' CHANGED_EMAIL : 'changed their email' INVITED_TEAM : 'was invited to a team' INVITED_CREATE_TEAM : 'was invited to create a team' SENT_FEEDBACK : 'sent feedback' TEAMS_JOINED_TEAM : 'joined team' USER_ENABLED_2FA : 'enabled 2-factor auth' USER_DISABLED_2FA : 'disabled 2-factor auth' STACKS_START_BUILD : 'started stack build' STACKS_BUILD_SUCCESSFULLY : 'stack build successfully' STACKS_BUILD_FAILED : 'stack build failed' STACKS_REINIT : 'reinitialized stack' STACKS_DELETE : 'deleted stack' @properties = {} @properties[@types.FINISH_REGISTER] = { category: 'NewAccount', label: 'VerifyAccount' } @identifyAndTrack = (username, event, eventProperties = {}, callback = -> ) -> @identify username, {}, (err) => return callback err if err @track username, event, eventProperties, callback @identify = (username, traits = {}, callback = -> ) -> return callback null unless KONFIG.sendEventsToSegment # use `forcedRecipientEmail` for both username and email if forcedRecipientEmail username = forcedRecipientUsername traits.email = forcedRecipientEmail traits = @addDefaults traits analytics?.identify { userId: username, traits } return callback null unless analytics # force flush so identify call doesn't sit in queue, while events # from Go/other systems are being sent analytics.flush (err, batch) -> console.error "flushing identify failed: #{err} @sent-hil" if err callback err @track$ = secure (client, subject, options = {}, callback) -> unless account = client?.connection?.delegate err = '[Tracker.track$] Account is not set!' console.error err return callback new KodingError err { profile: { nickname } } = account event = { subject } { customEvent } = options if customEvent @handleCustomEvent subject, customEvent, nickname delete options.customEvent @track nickname, event, options callback() @track = (username, event, options = {}, callback = -> ) -> return callback null unless KONFIG.sendEventsToSegment _.extend options, @properties[event.subject] # use `forcedRecipientEmail` for both username and email if forcedRecipientEmail username = forcedRecipientUsername event.to = forcedRecipientEmail event.from or= defaultFromMail event.properties = @addDefaults { options, username } require('./socialapi/requests').publishMailEvent event, (err) -> callback err # do not cause trailing parameters @page = (userId, name, category, properties) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { userId, name, category, properties } @addDefaults options analytics?.page options @alias = (previousId, userId) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { previousId, userId } @addDefaults options analytics?.alias options @group = (groupId, userId) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { groupId, userId } @addDefaults options analytics?.group options @addDefaults = (opts) -> opts['env'] = KONFIG.environment opts['hostname'] = KONFIG.hostname opts @handleCustomEvent = (subject, params, nickname) -> { STACKS_START_BUILD, STACKS_BUILD_SUCCESSFULLY, STACKS_BUILD_FAILED, STACKS_REINIT, STACKS_DELETE } = @types return unless subject in [ STACKS_START_BUILD, STACKS_BUILD_SUCCESSFULLY STACKS_BUILD_FAILED, STACKS_REINIT, STACKS_DELETE ] { stackId, group } = params JGroup = require './group' JGroup.one { slug : group }, (err, group) -> return console.log err if err { notifyAdmins } = require './notify' notifyAdmins group, 'StackStatusChanged', id : stackId group : group.slug if subject in [ STACKS_BUILD_SUCCESSFULLY, STACKS_BUILD_FAILED ] message = "#{nickname}'s #{subject}" else message = "#{nickname} #{subject}" KodingLogger.log group, message
true
bongo = require 'bongo' KodingError = require '../error' KodingLogger = require './kodinglogger' { secure, signature } = bongo _ = require 'lodash' KONFIG = require 'koding-config-manager' { socialapi } = KONFIG exchangeName = "#{socialapi.eventExchangeName}:0" exchangeOpts = { autoDelete: no, durable:yes, type :'fanout', confirm: true } try Analytics = require('analytics-node') analytics = new Analytics(KONFIG.segment) catch e console.warn 'Segment disabled because of missing configuration' module.exports = class Tracker extends bongo.Base @share() @set sharedMethods: static: track: (signature String, Object, Function) { forcedRecipientEmail, forcedRecipientUsername, defaultFromMail } = KONFIG.email EVENT_TYPE = 'api.mail_send' @types = START_REGISTER : 'started to register' FINISH_REGISTER : 'finished register' LOGGED_IN : 'logged in' CONFIRM_USING_TOKEN : 'confirmed & logged in using token' REQUEST_NEW_PASSWORD : 'PI:PASSWORD:<PASSWORD>END_PI' CHANGED_PASSWORD : 'PI:PASSWORD:<PASSWORD>END_PI' REQUEST_EMAIL_CHANGE : 'requested pin to change email' CHANGED_EMAIL : 'changed their email' INVITED_TEAM : 'was invited to a team' INVITED_CREATE_TEAM : 'was invited to create a team' SENT_FEEDBACK : 'sent feedback' TEAMS_JOINED_TEAM : 'joined team' USER_ENABLED_2FA : 'enabled 2-factor auth' USER_DISABLED_2FA : 'disabled 2-factor auth' STACKS_START_BUILD : 'started stack build' STACKS_BUILD_SUCCESSFULLY : 'stack build successfully' STACKS_BUILD_FAILED : 'stack build failed' STACKS_REINIT : 'reinitialized stack' STACKS_DELETE : 'deleted stack' @properties = {} @properties[@types.FINISH_REGISTER] = { category: 'NewAccount', label: 'VerifyAccount' } @identifyAndTrack = (username, event, eventProperties = {}, callback = -> ) -> @identify username, {}, (err) => return callback err if err @track username, event, eventProperties, callback @identify = (username, traits = {}, callback = -> ) -> return callback null unless KONFIG.sendEventsToSegment # use `forcedRecipientEmail` for both username and email if forcedRecipientEmail username = forcedRecipientUsername traits.email = forcedRecipientEmail traits = @addDefaults traits analytics?.identify { userId: username, traits } return callback null unless analytics # force flush so identify call doesn't sit in queue, while events # from Go/other systems are being sent analytics.flush (err, batch) -> console.error "flushing identify failed: #{err} @sent-hil" if err callback err @track$ = secure (client, subject, options = {}, callback) -> unless account = client?.connection?.delegate err = '[Tracker.track$] Account is not set!' console.error err return callback new KodingError err { profile: { nickname } } = account event = { subject } { customEvent } = options if customEvent @handleCustomEvent subject, customEvent, nickname delete options.customEvent @track nickname, event, options callback() @track = (username, event, options = {}, callback = -> ) -> return callback null unless KONFIG.sendEventsToSegment _.extend options, @properties[event.subject] # use `forcedRecipientEmail` for both username and email if forcedRecipientEmail username = forcedRecipientUsername event.to = forcedRecipientEmail event.from or= defaultFromMail event.properties = @addDefaults { options, username } require('./socialapi/requests').publishMailEvent event, (err) -> callback err # do not cause trailing parameters @page = (userId, name, category, properties) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { userId, name, category, properties } @addDefaults options analytics?.page options @alias = (previousId, userId) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { previousId, userId } @addDefaults options analytics?.alias options @group = (groupId, userId) -> return unless KONFIG.sendEventsToSegment userId = KONFIG.forcedRecipientEmail or userId options = { groupId, userId } @addDefaults options analytics?.group options @addDefaults = (opts) -> opts['env'] = KONFIG.environment opts['hostname'] = KONFIG.hostname opts @handleCustomEvent = (subject, params, nickname) -> { STACKS_START_BUILD, STACKS_BUILD_SUCCESSFULLY, STACKS_BUILD_FAILED, STACKS_REINIT, STACKS_DELETE } = @types return unless subject in [ STACKS_START_BUILD, STACKS_BUILD_SUCCESSFULLY STACKS_BUILD_FAILED, STACKS_REINIT, STACKS_DELETE ] { stackId, group } = params JGroup = require './group' JGroup.one { slug : group }, (err, group) -> return console.log err if err { notifyAdmins } = require './notify' notifyAdmins group, 'StackStatusChanged', id : stackId group : group.slug if subject in [ STACKS_BUILD_SUCCESSFULLY, STACKS_BUILD_FAILED ] message = "#{nickname}'s #{subject}" else message = "#{nickname} #{subject}" KodingLogger.log group, message
[ { "context": "re is licensed under the MIT License.\n\n Copyright Fedor Indutny, 2011.\n\n Permission is hereby granted, free of c", "end": 121, "score": 0.9994741678237915, "start": 108, "tag": "NAME", "value": "Fedor Indutny" } ]
node_modules/index/lib/index/memory-storage.coffee
beshrkayali/monkey-release-action
12
### Memory storage for Node Index Module This software is licensed under the MIT License. Copyright Fedor Indutny, 2011. 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. ### util = require 'util' step = require 'step' ### Class @constructor ### Storage = exports.Storage = (options) -> @data = [ [] ] @root_pos = new Position 0 @ ### @constructor wrapper ### exports.createStorage = (options) -> return new Storage options Storage::isPosition = isPosition = (pos) -> return pos instanceof Position Storage::read = (pos, callback) -> unless isPosition pos return callback 'pos should be a valid position' process.nextTick => callback null, @data[pos.index] Storage::write = (data, callback) -> process.nextTick => callback null, new Position(@data.push(data) - 1) Storage::readRoot = (callback) -> process.nextTick => callback null, @data[@root_pos.index] Storage::writeRoot = (root_pos, callback) -> unless isPosition root_pos return callback 'pos should be a valid position' process.nextTick => @root_pos = root_pos callback null Storage::inspect = -> @data.forEach (line, i) -> util.puts i + ': ' + JSON.stringify line util.puts 'Root : ' + JSON.stringify @root_pos Position = exports.Position = (@index) -> @ ### Storage state ### Storage::getState = -> {} Storage::setState = (state) -> true ### Compaction flow ### Storage::beforeCompact = (callback) -> @_compactEdge = @data.push '--------' callback null Storage::afterCompact = (callback) -> @data[i] = 0 for i in [0...@_compactEdge] callback null
5810
### Memory storage for Node Index Module This software is licensed under the MIT License. Copyright <NAME>, 2011. 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. ### util = require 'util' step = require 'step' ### Class @constructor ### Storage = exports.Storage = (options) -> @data = [ [] ] @root_pos = new Position 0 @ ### @constructor wrapper ### exports.createStorage = (options) -> return new Storage options Storage::isPosition = isPosition = (pos) -> return pos instanceof Position Storage::read = (pos, callback) -> unless isPosition pos return callback 'pos should be a valid position' process.nextTick => callback null, @data[pos.index] Storage::write = (data, callback) -> process.nextTick => callback null, new Position(@data.push(data) - 1) Storage::readRoot = (callback) -> process.nextTick => callback null, @data[@root_pos.index] Storage::writeRoot = (root_pos, callback) -> unless isPosition root_pos return callback 'pos should be a valid position' process.nextTick => @root_pos = root_pos callback null Storage::inspect = -> @data.forEach (line, i) -> util.puts i + ': ' + JSON.stringify line util.puts 'Root : ' + JSON.stringify @root_pos Position = exports.Position = (@index) -> @ ### Storage state ### Storage::getState = -> {} Storage::setState = (state) -> true ### Compaction flow ### Storage::beforeCompact = (callback) -> @_compactEdge = @data.push '--------' callback null Storage::afterCompact = (callback) -> @data[i] = 0 for i in [0...@_compactEdge] callback null
true
### Memory storage for Node Index Module This software is licensed under the MIT License. Copyright PI:NAME:<NAME>END_PI, 2011. 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. ### util = require 'util' step = require 'step' ### Class @constructor ### Storage = exports.Storage = (options) -> @data = [ [] ] @root_pos = new Position 0 @ ### @constructor wrapper ### exports.createStorage = (options) -> return new Storage options Storage::isPosition = isPosition = (pos) -> return pos instanceof Position Storage::read = (pos, callback) -> unless isPosition pos return callback 'pos should be a valid position' process.nextTick => callback null, @data[pos.index] Storage::write = (data, callback) -> process.nextTick => callback null, new Position(@data.push(data) - 1) Storage::readRoot = (callback) -> process.nextTick => callback null, @data[@root_pos.index] Storage::writeRoot = (root_pos, callback) -> unless isPosition root_pos return callback 'pos should be a valid position' process.nextTick => @root_pos = root_pos callback null Storage::inspect = -> @data.forEach (line, i) -> util.puts i + ': ' + JSON.stringify line util.puts 'Root : ' + JSON.stringify @root_pos Position = exports.Position = (@index) -> @ ### Storage state ### Storage::getState = -> {} Storage::setState = (state) -> true ### Compaction flow ### Storage::beforeCompact = (callback) -> @_compactEdge = @data.push '--------' callback null Storage::afterCompact = (callback) -> @data[i] = 0 for i in [0...@_compactEdge] callback null
[ { "context": "ther assistance please contact the Species team on species@unep-wcmc.org')\n error: (error) ->\n console.log(err", "end": 416, "score": 0.9999316930770874, "start": 395, "tag": "EMAIL", "value": "species@unep-wcmc.org" } ]
app/assets/javascripts/trade/mixins/authorise_user.js.coffee
unepwcmc/SAPI
6
Trade.AuthoriseUser = Ember.Mixin.create userCanEdit: (callback) -> $.ajax({ type: 'GET' url: "/trade/user_can_edit" data: {} dataType: 'json' success: (response) => if response.can_edit callback() else alert('It is not possible to perform this action. If you require further assistance please contact the Species team on species@unep-wcmc.org') error: (error) -> console.log(error) })
136507
Trade.AuthoriseUser = Ember.Mixin.create userCanEdit: (callback) -> $.ajax({ type: 'GET' url: "/trade/user_can_edit" data: {} dataType: 'json' success: (response) => if response.can_edit callback() else alert('It is not possible to perform this action. If you require further assistance please contact the Species team on <EMAIL>') error: (error) -> console.log(error) })
true
Trade.AuthoriseUser = Ember.Mixin.create userCanEdit: (callback) -> $.ajax({ type: 'GET' url: "/trade/user_can_edit" data: {} dataType: 'json' success: (response) => if response.can_edit callback() else alert('It is not possible to perform this action. If you require further assistance please contact the Species team on PI:EMAIL:<EMAIL>END_PI') error: (error) -> console.log(error) })
[ { "context": "und the JSX opening and closing brackets\n# @author Diogo Franco (Kovensky)\n###\n'use strict'\n\ngetTokenBeforeClosin", "end": 115, "score": 0.9998567700386047, "start": 103, "tag": "NAME", "value": "Diogo Franco" }, { "context": "ing and closing brackets\n# @author Diogo Franco (Kovensky)\n###\n'use strict'\n\ngetTokenBeforeClosingBracket =", "end": 125, "score": 0.4742858409881592, "start": 118, "tag": "NAME", "value": "ovensky" } ]
src/rules/jsx-tag-spacing.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Validates whitespace in and around the JSX opening and closing brackets # @author Diogo Franco (Kovensky) ### 'use strict' getTokenBeforeClosingBracket = require( 'eslint-plugin-react/lib/util/getTokenBeforeClosingBracket' ) docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Validators # ------------------------------------------------------------------------------ validateBeforeSelfClosing = (context, node, option) -> sourceCode = context.getSourceCode() NEVER_MESSAGE = 'A space is forbidden before closing bracket' ALWAYS_MESSAGE = 'A space is required before closing bracket' leftToken = getTokenBeforeClosingBracket node closingSlash = sourceCode.getTokenAfter leftToken return unless leftToken.loc.end.line is closingSlash.loc.start.line if ( option is 'always' and not sourceCode.isSpaceBetweenTokens leftToken, closingSlash ) context.report { node loc: closingSlash.loc.start message: ALWAYS_MESSAGE fix: (fixer) -> fixer.insertTextBefore closingSlash, ' ' } else if ( option is 'never' and sourceCode.isSpaceBetweenTokens leftToken, closingSlash ) context.report { node loc: closingSlash.loc.start message: NEVER_MESSAGE fix: (fixer) -> previousToken = sourceCode.getTokenBefore closingSlash fixer.removeRange [previousToken.range[1], closingSlash.range[0]] } validateBeforeClosing = (context, node, option) -> # Don't enforce this rule for self closing tags unless node.selfClosing sourceCode = context.getSourceCode() NEVER_MESSAGE = 'A space is forbidden before closing bracket' ALWAYS_MESSAGE = 'Whitespace is required before closing bracket' lastTokens = sourceCode.getLastTokens node, 2 closingToken = lastTokens[1] leftToken = lastTokens[0] return unless leftToken.loc.start.line is closingToken.loc.start.line adjacent = not sourceCode.isSpaceBetweenTokens leftToken, closingToken if option is 'never' and not adjacent context.report { node loc: start: leftToken.loc.end end: closingToken.loc.start message: NEVER_MESSAGE fix: (fixer) -> fixer.removeRange [leftToken.range[1], closingToken.range[0]] } else if option is 'always' and adjacent context.report { node loc: start: leftToken.loc.end end: closingToken.loc.start message: ALWAYS_MESSAGE fix: (fixer) -> fixer.insertTextBefore closingToken, ' ' } # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ optionDefaults = beforeSelfClosing: 'always' beforeClosing: 'allow' module.exports = meta: docs: description: 'Validate whitespace in and around the JSX opening and closing brackets' category: 'Stylistic Issues' recommended: no url: docsUrl 'jsx-tag-spacing' fixable: 'whitespace' schema: [ type: 'object' properties: beforeSelfClosing: enum: ['always', 'never', 'allow'] beforeClosing: enum: ['always', 'never', 'allow'] default: optionDefaults additionalProperties: no ] create: (context) -> options = {...optionDefaults, ...context.options[0]} JSXOpeningElement: (node) -> if options.beforeSelfClosing isnt 'allow' and node.selfClosing validateBeforeSelfClosing context, node, options.beforeSelfClosing unless options.beforeClosing is 'allow' validateBeforeClosing context, node, options.beforeClosing # JSXClosingElement: (node) -> # unless options.beforeClosing is 'allow' # validateBeforeClosing context, node, options.beforeClosing
77564
###* # @fileoverview Validates whitespace in and around the JSX opening and closing brackets # @author <NAME> (K<NAME>) ### 'use strict' getTokenBeforeClosingBracket = require( 'eslint-plugin-react/lib/util/getTokenBeforeClosingBracket' ) docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Validators # ------------------------------------------------------------------------------ validateBeforeSelfClosing = (context, node, option) -> sourceCode = context.getSourceCode() NEVER_MESSAGE = 'A space is forbidden before closing bracket' ALWAYS_MESSAGE = 'A space is required before closing bracket' leftToken = getTokenBeforeClosingBracket node closingSlash = sourceCode.getTokenAfter leftToken return unless leftToken.loc.end.line is closingSlash.loc.start.line if ( option is 'always' and not sourceCode.isSpaceBetweenTokens leftToken, closingSlash ) context.report { node loc: closingSlash.loc.start message: ALWAYS_MESSAGE fix: (fixer) -> fixer.insertTextBefore closingSlash, ' ' } else if ( option is 'never' and sourceCode.isSpaceBetweenTokens leftToken, closingSlash ) context.report { node loc: closingSlash.loc.start message: NEVER_MESSAGE fix: (fixer) -> previousToken = sourceCode.getTokenBefore closingSlash fixer.removeRange [previousToken.range[1], closingSlash.range[0]] } validateBeforeClosing = (context, node, option) -> # Don't enforce this rule for self closing tags unless node.selfClosing sourceCode = context.getSourceCode() NEVER_MESSAGE = 'A space is forbidden before closing bracket' ALWAYS_MESSAGE = 'Whitespace is required before closing bracket' lastTokens = sourceCode.getLastTokens node, 2 closingToken = lastTokens[1] leftToken = lastTokens[0] return unless leftToken.loc.start.line is closingToken.loc.start.line adjacent = not sourceCode.isSpaceBetweenTokens leftToken, closingToken if option is 'never' and not adjacent context.report { node loc: start: leftToken.loc.end end: closingToken.loc.start message: NEVER_MESSAGE fix: (fixer) -> fixer.removeRange [leftToken.range[1], closingToken.range[0]] } else if option is 'always' and adjacent context.report { node loc: start: leftToken.loc.end end: closingToken.loc.start message: ALWAYS_MESSAGE fix: (fixer) -> fixer.insertTextBefore closingToken, ' ' } # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ optionDefaults = beforeSelfClosing: 'always' beforeClosing: 'allow' module.exports = meta: docs: description: 'Validate whitespace in and around the JSX opening and closing brackets' category: 'Stylistic Issues' recommended: no url: docsUrl 'jsx-tag-spacing' fixable: 'whitespace' schema: [ type: 'object' properties: beforeSelfClosing: enum: ['always', 'never', 'allow'] beforeClosing: enum: ['always', 'never', 'allow'] default: optionDefaults additionalProperties: no ] create: (context) -> options = {...optionDefaults, ...context.options[0]} JSXOpeningElement: (node) -> if options.beforeSelfClosing isnt 'allow' and node.selfClosing validateBeforeSelfClosing context, node, options.beforeSelfClosing unless options.beforeClosing is 'allow' validateBeforeClosing context, node, options.beforeClosing # JSXClosingElement: (node) -> # unless options.beforeClosing is 'allow' # validateBeforeClosing context, node, options.beforeClosing
true
###* # @fileoverview Validates whitespace in and around the JSX opening and closing brackets # @author PI:NAME:<NAME>END_PI (KPI:NAME:<NAME>END_PI) ### 'use strict' getTokenBeforeClosingBracket = require( 'eslint-plugin-react/lib/util/getTokenBeforeClosingBracket' ) docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Validators # ------------------------------------------------------------------------------ validateBeforeSelfClosing = (context, node, option) -> sourceCode = context.getSourceCode() NEVER_MESSAGE = 'A space is forbidden before closing bracket' ALWAYS_MESSAGE = 'A space is required before closing bracket' leftToken = getTokenBeforeClosingBracket node closingSlash = sourceCode.getTokenAfter leftToken return unless leftToken.loc.end.line is closingSlash.loc.start.line if ( option is 'always' and not sourceCode.isSpaceBetweenTokens leftToken, closingSlash ) context.report { node loc: closingSlash.loc.start message: ALWAYS_MESSAGE fix: (fixer) -> fixer.insertTextBefore closingSlash, ' ' } else if ( option is 'never' and sourceCode.isSpaceBetweenTokens leftToken, closingSlash ) context.report { node loc: closingSlash.loc.start message: NEVER_MESSAGE fix: (fixer) -> previousToken = sourceCode.getTokenBefore closingSlash fixer.removeRange [previousToken.range[1], closingSlash.range[0]] } validateBeforeClosing = (context, node, option) -> # Don't enforce this rule for self closing tags unless node.selfClosing sourceCode = context.getSourceCode() NEVER_MESSAGE = 'A space is forbidden before closing bracket' ALWAYS_MESSAGE = 'Whitespace is required before closing bracket' lastTokens = sourceCode.getLastTokens node, 2 closingToken = lastTokens[1] leftToken = lastTokens[0] return unless leftToken.loc.start.line is closingToken.loc.start.line adjacent = not sourceCode.isSpaceBetweenTokens leftToken, closingToken if option is 'never' and not adjacent context.report { node loc: start: leftToken.loc.end end: closingToken.loc.start message: NEVER_MESSAGE fix: (fixer) -> fixer.removeRange [leftToken.range[1], closingToken.range[0]] } else if option is 'always' and adjacent context.report { node loc: start: leftToken.loc.end end: closingToken.loc.start message: ALWAYS_MESSAGE fix: (fixer) -> fixer.insertTextBefore closingToken, ' ' } # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ optionDefaults = beforeSelfClosing: 'always' beforeClosing: 'allow' module.exports = meta: docs: description: 'Validate whitespace in and around the JSX opening and closing brackets' category: 'Stylistic Issues' recommended: no url: docsUrl 'jsx-tag-spacing' fixable: 'whitespace' schema: [ type: 'object' properties: beforeSelfClosing: enum: ['always', 'never', 'allow'] beforeClosing: enum: ['always', 'never', 'allow'] default: optionDefaults additionalProperties: no ] create: (context) -> options = {...optionDefaults, ...context.options[0]} JSXOpeningElement: (node) -> if options.beforeSelfClosing isnt 'allow' and node.selfClosing validateBeforeSelfClosing context, node, options.beforeSelfClosing unless options.beforeClosing is 'allow' validateBeforeClosing context, node, options.beforeClosing # JSXClosingElement: (node) -> # unless options.beforeClosing is 'allow' # validateBeforeClosing context, node, options.beforeClosing
[ { "context": " \"byline\"\n fullNames: \n knowtheory: \"Ted Han\"\n davidherzog: \"David Herzog\"\n janetsaidi", "end": 129, "score": 0.9998791813850403, "start": 122, "tag": "NAME", "value": "Ted Han" }, { "context": "\n knowtheory: \"Ted Han\"\n davidherzog: \"David Herzog\"\n janetsaidi: \"Janet Saidi\"\n joyandstuff", "end": 163, "score": 0.9998729825019836, "start": 151, "tag": "NAME", "value": "David Herzog" }, { "context": "davidherzog: \"David Herzog\"\n janetsaidi: \"Janet Saidi\"\n joyandstuff: \"Joy Mayer\"\n mfpatane: ", "end": 196, "score": 0.9998926520347595, "start": 185, "tag": "NAME", "value": "Janet Saidi" }, { "context": " janetsaidi: \"Janet Saidi\"\n joyandstuff: \"Joy Mayer\"\n mfpatane: \"Matthew Patane\"\n ryanfamu", "end": 227, "score": 0.9998815059661865, "start": 218, "tag": "NAME", "value": "Joy Mayer" }, { "context": " joyandstuff: \"Joy Mayer\"\n mfpatane: \"Matthew Patane\"\n ryanfamuliner: \"Ryan Famuliner\"\n scottpha", "end": 263, "score": 0.9999014735221863, "start": 249, "tag": "NAME", "value": "Matthew Patane" }, { "context": "patane: \"Matthew Patane\"\n ryanfamuliner: \"Ryan Famuliner\"\n scottphamkbia: \"Scott Pham\"\n swaffords: ", "end": 299, "score": 0.9998877644538879, "start": 285, "tag": "NAME", "value": "Ryan Famuliner" }, { "context": "anfamuliner: \"Ryan Famuliner\"\n scottphamkbia: \"Scott Pham\"\n swaffords: \"Scott Swafford\"\n jenleere", "end": 331, "score": 0.9998981952667236, "start": 321, "tag": "NAME", "value": "Scott Pham" }, { "context": " scottphamkbia: \"Scott Pham\"\n swaffords: \"Scott Swafford\"\n jenleereeves: \"Jen Lee Reeves\"\n projecto", "end": 367, "score": 0.9847507476806641, "start": 353, "tag": "NAME", "value": "Scott Swafford" }, { "context": "affords: \"Scott Swafford\"\n jenleereeves: \"Jen Lee Reeves\"\n projectopenvault: \"Project OpenVault Team\"\n ", "end": 403, "score": 0.9998974800109863, "start": 389, "tag": "NAME", "value": "Jen Lee Reeves" }, { "context": "lt: \"Project OpenVault Team\"\n stacewelsh: \"Stacey Welsh\"\n codylagrow: \"Cody LaGrow\"\n \n affiliati", "end": 485, "score": 0.9997991919517517, "start": 473, "tag": "NAME", "value": "Stacey Welsh" }, { "context": "acewelsh: \"Stacey Welsh\"\n codylagrow: \"Cody LaGrow\"\n \n affiliations:\n knowtheory: \"Project O", "end": 519, "score": 0.9965633749961853, "start": 508, "tag": "NAME", "value": "Cody LaGrow" } ]
assets/javascripts/views/username.coffee
knowtheory/projectopenvault
0
POV.views.Byline = Backbone.View.extend tagName: "span" className: "byline" fullNames: knowtheory: "Ted Han" davidherzog: "David Herzog" janetsaidi: "Janet Saidi" joyandstuff: "Joy Mayer" mfpatane: "Matthew Patane" ryanfamuliner: "Ryan Famuliner" scottphamkbia: "Scott Pham" swaffords: "Scott Swafford" jenleereeves: "Jen Lee Reeves" projectopenvault: "Project OpenVault Team" stacewelsh: "Stacey Welsh" codylagrow: "Cody LaGrow" affiliations: knowtheory: "Project Open Vault" davidherzog: "Project Open Vault" janetsaidi: "KBIA Radio" joyandstuff: "The Columbia Missourian" mfpatane: "Project Open Vault" ryanfamuliner: "KBIA Radio" scottphamkbia: "KBIA Radio" swaffords: "The Columbia Missourian" jenleereeves: "KOMU8" stacewelsh: "KOMU8" codylagrow: "KOMU8" initialize: (options) -> @username = (options.username || options.el.html() || "").toLowerCase() render: () -> affilation = """ <span class="affiliation">(#{@affiliations[@username]})</span>""" if @affiliations[@username] """#{@fullNames[@username]} #{affilation}""" attach: -> this.$el.html @render()
85488
POV.views.Byline = Backbone.View.extend tagName: "span" className: "byline" fullNames: knowtheory: "<NAME>" davidherzog: "<NAME>" janetsaidi: "<NAME>" joyandstuff: "<NAME>" mfpatane: "<NAME>" ryanfamuliner: "<NAME>" scottphamkbia: "<NAME>" swaffords: "<NAME>" jenleereeves: "<NAME>" projectopenvault: "Project OpenVault Team" stacewelsh: "<NAME>" codylagrow: "<NAME>" affiliations: knowtheory: "Project Open Vault" davidherzog: "Project Open Vault" janetsaidi: "KBIA Radio" joyandstuff: "The Columbia Missourian" mfpatane: "Project Open Vault" ryanfamuliner: "KBIA Radio" scottphamkbia: "KBIA Radio" swaffords: "The Columbia Missourian" jenleereeves: "KOMU8" stacewelsh: "KOMU8" codylagrow: "KOMU8" initialize: (options) -> @username = (options.username || options.el.html() || "").toLowerCase() render: () -> affilation = """ <span class="affiliation">(#{@affiliations[@username]})</span>""" if @affiliations[@username] """#{@fullNames[@username]} #{affilation}""" attach: -> this.$el.html @render()
true
POV.views.Byline = Backbone.View.extend tagName: "span" className: "byline" fullNames: knowtheory: "PI:NAME:<NAME>END_PI" davidherzog: "PI:NAME:<NAME>END_PI" janetsaidi: "PI:NAME:<NAME>END_PI" joyandstuff: "PI:NAME:<NAME>END_PI" mfpatane: "PI:NAME:<NAME>END_PI" ryanfamuliner: "PI:NAME:<NAME>END_PI" scottphamkbia: "PI:NAME:<NAME>END_PI" swaffords: "PI:NAME:<NAME>END_PI" jenleereeves: "PI:NAME:<NAME>END_PI" projectopenvault: "Project OpenVault Team" stacewelsh: "PI:NAME:<NAME>END_PI" codylagrow: "PI:NAME:<NAME>END_PI" affiliations: knowtheory: "Project Open Vault" davidherzog: "Project Open Vault" janetsaidi: "KBIA Radio" joyandstuff: "The Columbia Missourian" mfpatane: "Project Open Vault" ryanfamuliner: "KBIA Radio" scottphamkbia: "KBIA Radio" swaffords: "The Columbia Missourian" jenleereeves: "KOMU8" stacewelsh: "KOMU8" codylagrow: "KOMU8" initialize: (options) -> @username = (options.username || options.el.html() || "").toLowerCase() render: () -> affilation = """ <span class="affiliation">(#{@affiliations[@username]})</span>""" if @affiliations[@username] """#{@fullNames[@username]} #{affilation}""" attach: -> this.$el.html @render()
[ { "context": " require 'assert'\n\nconnString = 'mongodb://heroku:flk3ungh0x3anflx1bab@staff.mongohq.com:10092/app1321916260066'\nexpectedCommand = \"mongod", "end": 96, "score": 0.9048569798469543, "start": 58, "tag": "EMAIL", "value": "flk3ungh0x3anflx1bab@staff.mongohq.com" }, { "context": "16260066 --host staff.mongohq.com:10092 --username heroku --password flk3ungh0x3anflx1bab --out /dumps/mong", "end": 220, "score": 0.9315932393074036, "start": 214, "tag": "USERNAME", "value": "heroku" }, { "context": "aff.mongohq.com:10092 --username heroku --password flk3ungh0x3anflx1bab --out /dumps/mongodb/some-backup\"\ndirName = '/dum", "end": 252, "score": 0.9993767142295837, "start": 232, "tag": "PASSWORD", "value": "flk3ungh0x3anflx1bab" } ]
test/makeDumpCommand.coffee
Trippnology/mongo-utils
0
assert = require 'assert' connString = 'mongodb://heroku:flk3ungh0x3anflx1bab@staff.mongohq.com:10092/app1321916260066' expectedCommand = "mongodump --db app1321916260066 --host staff.mongohq.com:10092 --username heroku --password flk3ungh0x3anflx1bab --out /dumps/mongodb/some-backup" dirName = '/dumps/mongodb/some-backup' utils = require '../' describe 'makeDumpCommand', -> it 'converts query string and dirname to a mongodump command', -> command = utils.makeDumpCommand connString, dirName assert.equal command, expectedCommand it 'throws an error if no dirName is given', -> try utils.makeDumpCommand connString catch error return assert.ok true assert.ok false, 'it did not throw an error.'
184163
assert = require 'assert' connString = 'mongodb://heroku:<EMAIL>:10092/app1321916260066' expectedCommand = "mongodump --db app1321916260066 --host staff.mongohq.com:10092 --username heroku --password <PASSWORD> --out /dumps/mongodb/some-backup" dirName = '/dumps/mongodb/some-backup' utils = require '../' describe 'makeDumpCommand', -> it 'converts query string and dirname to a mongodump command', -> command = utils.makeDumpCommand connString, dirName assert.equal command, expectedCommand it 'throws an error if no dirName is given', -> try utils.makeDumpCommand connString catch error return assert.ok true assert.ok false, 'it did not throw an error.'
true
assert = require 'assert' connString = 'mongodb://heroku:PI:EMAIL:<EMAIL>END_PI:10092/app1321916260066' expectedCommand = "mongodump --db app1321916260066 --host staff.mongohq.com:10092 --username heroku --password PI:PASSWORD:<PASSWORD>END_PI --out /dumps/mongodb/some-backup" dirName = '/dumps/mongodb/some-backup' utils = require '../' describe 'makeDumpCommand', -> it 'converts query string and dirname to a mongodump command', -> command = utils.makeDumpCommand connString, dirName assert.equal command, expectedCommand it 'throws an error if no dirName is given', -> try utils.makeDumpCommand connString catch error return assert.ok true assert.ok false, 'it did not throw an error.'
[ { "context": "PR_TOKEN\n process.env.GH_RELEASE_PR_TOKEN = 'bogus-token'\n\n @subject = params.toAuth()\n\n ", "end": 1835, "score": 0.4911060929298401, "start": 1833, "tag": "PASSWORD", "value": "bo" }, { "context": "ame: 'foo'}\n\n assert.equal @subject.user, 'user'\n assert.equal @subject.repo, 'test-repo'\n", "end": 2504, "score": 0.9912585020065308, "start": 2500, "tag": "USERNAME", "value": "user" }, { "context": "ame: 'foo'}\n\n assert.equal @subject.user, 'user'\n assert.equal @subject.repo, 'original-te", "end": 3330, "score": 0.9950299859046936, "start": 3326, "tag": "USERNAME", "value": "user" } ]
test/params-test.coffee
banyan/hubot-gh-release-pr
3
assert = require 'power-assert' params = require '../src/params' describe 'params', -> describe 'toInit', -> context 'without ENV', -> beforeEach -> @subject = params.toInit() it 'gets expected values', -> assert.equal @subject.version, '3.0.0' assert.equal @subject.protocol, 'https' assert.equal @subject.debug, false assert.equal @subject.timeout, 5000 assert.equal @subject.host, 'api.github.com' context 'with ENV', -> beforeEach -> @protocol = process.env.GH_RELEASE_PR_GITHUB_PROTOCOL @debug = process.env.GH_RELEASE_PR_GITHUB_DEBUG @host = process.env.GH_RELEASE_PR_GITHUB_HOST @pathPrefix = process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX process.env.GH_RELEASE_PR_GITHUB_PROTOCOL = 'http' process.env.GH_RELEASE_PR_GITHUB_DEBUG = 'true' process.env.GH_RELEASE_PR_GITHUB_HOST = 'github.my-GHE-enabled-company.com' process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX = '/api/v3' @subject = params.toInit() afterEach -> process.env.GH_RELEASE_PR_GITHUB_PROTOCOL = @protocol process.env.GH_RELEASE_PR_GITHUB_DEBUG = @debug process.env.GH_RELEASE_PR_GITHUB_HOST = @host process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX = @pathPrefix it 'gets expected values', -> assert.equal @subject.version, '3.0.0' assert.equal @subject.protocol, 'http' assert.equal @subject.debug, true assert.equal @subject.timeout, 5000 assert.equal @subject.host, 'github.my-GHE-enabled-company.com' assert.equal @subject.pathPrefix, '/api/v3' describe 'toAuth', -> beforeEach -> @token = process.env.GH_RELEASE_PR_TOKEN process.env.GH_RELEASE_PR_TOKEN = 'bogus-token' @subject = params.toAuth() afterEach -> process.env.GH_RELEASE_PR_TOKEN = @token it 'gets expected values', -> assert.equal @subject.type, 'oauth' assert.equal @subject.token, 'bogus-token' describe 'toCreatePR', -> beforeEach -> @repo = 'test-repo' @user = process.env.GH_RELEASE_PR_USER process.env.GH_RELEASE_PR_USER = 'user' afterEach -> process.env.GH_RELEASE_PR_USER = @user context 'without custom branch', -> it 'gets expected values', -> @subject = params.toCreatePR @repo, 'production', {message: user: name: 'foo'} assert.equal @subject.user, 'user' assert.equal @subject.repo, 'test-repo' assert.equal @subject.title, "#{params.now()} production deployment by foo" assert.equal @subject.body, '' assert.equal @subject.base, 'production' assert.equal @subject.head, 'master' context 'with custom branch', -> beforeEach -> @customBranch = process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT = 'test-repo[repo]=original-test-repo&test-repo[base][production]=another-name-of-production&test-repo[head]=another-name-of-master' afterEach -> process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT = @customBranch it 'gets expected values', -> @subject = params.toCreatePR @repo, 'production', {message: user: name: 'foo'} assert.equal @subject.user, 'user' assert.equal @subject.repo, 'original-test-repo' assert.equal @subject.title, "#{params.now()} production deployment by foo" assert.equal @subject.body, '' assert.equal @subject.base, 'another-name-of-production' assert.equal @subject.head, 'another-name-of-master'
153219
assert = require 'power-assert' params = require '../src/params' describe 'params', -> describe 'toInit', -> context 'without ENV', -> beforeEach -> @subject = params.toInit() it 'gets expected values', -> assert.equal @subject.version, '3.0.0' assert.equal @subject.protocol, 'https' assert.equal @subject.debug, false assert.equal @subject.timeout, 5000 assert.equal @subject.host, 'api.github.com' context 'with ENV', -> beforeEach -> @protocol = process.env.GH_RELEASE_PR_GITHUB_PROTOCOL @debug = process.env.GH_RELEASE_PR_GITHUB_DEBUG @host = process.env.GH_RELEASE_PR_GITHUB_HOST @pathPrefix = process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX process.env.GH_RELEASE_PR_GITHUB_PROTOCOL = 'http' process.env.GH_RELEASE_PR_GITHUB_DEBUG = 'true' process.env.GH_RELEASE_PR_GITHUB_HOST = 'github.my-GHE-enabled-company.com' process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX = '/api/v3' @subject = params.toInit() afterEach -> process.env.GH_RELEASE_PR_GITHUB_PROTOCOL = @protocol process.env.GH_RELEASE_PR_GITHUB_DEBUG = @debug process.env.GH_RELEASE_PR_GITHUB_HOST = @host process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX = @pathPrefix it 'gets expected values', -> assert.equal @subject.version, '3.0.0' assert.equal @subject.protocol, 'http' assert.equal @subject.debug, true assert.equal @subject.timeout, 5000 assert.equal @subject.host, 'github.my-GHE-enabled-company.com' assert.equal @subject.pathPrefix, '/api/v3' describe 'toAuth', -> beforeEach -> @token = process.env.GH_RELEASE_PR_TOKEN process.env.GH_RELEASE_PR_TOKEN = '<PASSWORD>gus-token' @subject = params.toAuth() afterEach -> process.env.GH_RELEASE_PR_TOKEN = @token it 'gets expected values', -> assert.equal @subject.type, 'oauth' assert.equal @subject.token, 'bogus-token' describe 'toCreatePR', -> beforeEach -> @repo = 'test-repo' @user = process.env.GH_RELEASE_PR_USER process.env.GH_RELEASE_PR_USER = 'user' afterEach -> process.env.GH_RELEASE_PR_USER = @user context 'without custom branch', -> it 'gets expected values', -> @subject = params.toCreatePR @repo, 'production', {message: user: name: 'foo'} assert.equal @subject.user, 'user' assert.equal @subject.repo, 'test-repo' assert.equal @subject.title, "#{params.now()} production deployment by foo" assert.equal @subject.body, '' assert.equal @subject.base, 'production' assert.equal @subject.head, 'master' context 'with custom branch', -> beforeEach -> @customBranch = process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT = 'test-repo[repo]=original-test-repo&test-repo[base][production]=another-name-of-production&test-repo[head]=another-name-of-master' afterEach -> process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT = @customBranch it 'gets expected values', -> @subject = params.toCreatePR @repo, 'production', {message: user: name: 'foo'} assert.equal @subject.user, 'user' assert.equal @subject.repo, 'original-test-repo' assert.equal @subject.title, "#{params.now()} production deployment by foo" assert.equal @subject.body, '' assert.equal @subject.base, 'another-name-of-production' assert.equal @subject.head, 'another-name-of-master'
true
assert = require 'power-assert' params = require '../src/params' describe 'params', -> describe 'toInit', -> context 'without ENV', -> beforeEach -> @subject = params.toInit() it 'gets expected values', -> assert.equal @subject.version, '3.0.0' assert.equal @subject.protocol, 'https' assert.equal @subject.debug, false assert.equal @subject.timeout, 5000 assert.equal @subject.host, 'api.github.com' context 'with ENV', -> beforeEach -> @protocol = process.env.GH_RELEASE_PR_GITHUB_PROTOCOL @debug = process.env.GH_RELEASE_PR_GITHUB_DEBUG @host = process.env.GH_RELEASE_PR_GITHUB_HOST @pathPrefix = process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX process.env.GH_RELEASE_PR_GITHUB_PROTOCOL = 'http' process.env.GH_RELEASE_PR_GITHUB_DEBUG = 'true' process.env.GH_RELEASE_PR_GITHUB_HOST = 'github.my-GHE-enabled-company.com' process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX = '/api/v3' @subject = params.toInit() afterEach -> process.env.GH_RELEASE_PR_GITHUB_PROTOCOL = @protocol process.env.GH_RELEASE_PR_GITHUB_DEBUG = @debug process.env.GH_RELEASE_PR_GITHUB_HOST = @host process.env.GH_RELEASE_PR_GITHUB_PATH_PREFIX = @pathPrefix it 'gets expected values', -> assert.equal @subject.version, '3.0.0' assert.equal @subject.protocol, 'http' assert.equal @subject.debug, true assert.equal @subject.timeout, 5000 assert.equal @subject.host, 'github.my-GHE-enabled-company.com' assert.equal @subject.pathPrefix, '/api/v3' describe 'toAuth', -> beforeEach -> @token = process.env.GH_RELEASE_PR_TOKEN process.env.GH_RELEASE_PR_TOKEN = 'PI:PASSWORD:<PASSWORD>END_PIgus-token' @subject = params.toAuth() afterEach -> process.env.GH_RELEASE_PR_TOKEN = @token it 'gets expected values', -> assert.equal @subject.type, 'oauth' assert.equal @subject.token, 'bogus-token' describe 'toCreatePR', -> beforeEach -> @repo = 'test-repo' @user = process.env.GH_RELEASE_PR_USER process.env.GH_RELEASE_PR_USER = 'user' afterEach -> process.env.GH_RELEASE_PR_USER = @user context 'without custom branch', -> it 'gets expected values', -> @subject = params.toCreatePR @repo, 'production', {message: user: name: 'foo'} assert.equal @subject.user, 'user' assert.equal @subject.repo, 'test-repo' assert.equal @subject.title, "#{params.now()} production deployment by foo" assert.equal @subject.body, '' assert.equal @subject.base, 'production' assert.equal @subject.head, 'master' context 'with custom branch', -> beforeEach -> @customBranch = process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT = 'test-repo[repo]=original-test-repo&test-repo[base][production]=another-name-of-production&test-repo[head]=another-name-of-master' afterEach -> process.env.GH_RELEASE_PR_CUSTOM_ENDPOINT = @customBranch it 'gets expected values', -> @subject = params.toCreatePR @repo, 'production', {message: user: name: 'foo'} assert.equal @subject.user, 'user' assert.equal @subject.repo, 'original-test-repo' assert.equal @subject.title, "#{params.now()} production deployment by foo" assert.equal @subject.body, '' assert.equal @subject.base, 'another-name-of-production' assert.equal @subject.head, 'another-name-of-master'
[ { "context": "00 - 19.00'\n }\n {\n description: 'Pau Garcia | Domestic Data Streamers'\n time: '19.00 -", "end": 1583, "score": 0.9992954134941101, "start": 1573, "tag": "NAME", "value": "Pau Garcia" }, { "context": "00 - 20.00'\n }\n {\n description: 'Karsten Schmidt | Post Spectacular'\n time: '20.00 - 21.00'", "end": 1694, "score": 0.9998947381973267, "start": 1679, "tag": "NAME", "value": "Karsten Schmidt" }, { "context": " }\n ]\n sponsors: [ \n {\n name: 'Studio 727'\n logo: '/images/sponsors/studio727.png'\n ", "end": 1809, "score": 0.9420452117919922, "start": 1799, "tag": "NAME", "value": "Studio 727" }, { "context": "ttp://www.727.sk/'\n }\n {\n name: 'Nethemba'\n logo: '/images/sponsors/nethemba.png'\n ", "end": 1931, "score": 0.9996746182441711, "start": 1923, "tag": "NAME", "value": "Nethemba" }, { "context": " }\n ]\n partners: [ \n {\n name: 'Resonate'\n logo: '/images/partners/resonate-wordmar", "end": 2080, "score": 0.9386336207389832, "start": 2072, "tag": "NAME", "value": "Resonate" }, { "context": "tp://resonate.io/'\n }\n {\n name: 'Slovenská Národná Galéria'\n logo: '/images/partners/logo-sng.svg'\n ", "end": 2228, "score": 0.999898374080658, "start": 2203, "tag": "NAME", "value": "Slovenská Národná Galéria" }, { "context": "http://www.sng.sk'\n }\n {\n name: 'Lab'\n logo: '/images/partners/logo-lab.svg'\n ", "end": 2343, "score": 0.9763807654380798, "start": 2340, "tag": "NAME", "value": "Lab" } ]
docpad.coffee
phillchill/sensorium.is
0
module.exports = prompts: false templateData: conf: name: 'Sensorium 2016' description: 'Sensorium festival is a celebration of art and science taking place in Bratislava' date: 'April 19' price: '€10' venue: 'Berlinka, Slovenská Národná Galéria' address: 'Námestie Ľudovíta Štúra 33/4' city: 'Bratislava' country: 'Slovakia' site: theme: 'yellow-swan' url: 'http://sensorium.is' # googleanalytics: 'UA-33656081-1' # Styles styles: [ "/styles/bootstrap.css" # "/styles/style.css" "/styles/font-awesome-min.css" "/styles/instant-style.css" "/styles/ui-hover-effects.css" "/styles/ui-buttons.css" "/styles/schedule.css" "/styles/sponsors.css" "/styles/footer.css" ] # Scripts scripts: [ "/vendor/jquery.js" "/vendor/bootstrap.min.js" "/scripts/main.js" "/scripts/footerheight.js" "/scripts/script.js" ] sections: [ 'speakers' 'about' 'program' 'location' 'sponsors' 'partners' ] labels: about: 'About' location: 'Location' speakers: 'Speakers' program: 'Program' sponsors: 'Sponsors' partners: 'Partners' contact: 'Contact' schedule: [ # { # time: '18.00' # description: 'Welcome' # } { description: 'Special Guest | To be announced...' time: '18.00 - 19.00' } { description: 'Pau Garcia | Domestic Data Streamers' time: '19.00 - 20.00' } { description: 'Karsten Schmidt | Post Spectacular' time: '20.00 - 21.00' } ] sponsors: [ { name: 'Studio 727' logo: '/images/sponsors/studio727.png' url: 'http://www.727.sk/' } { name: 'Nethemba' logo: '/images/sponsors/nethemba.png' url: 'https://nethemba.com/sk' } ] partners: [ { name: 'Resonate' logo: '/images/partners/resonate-wordmark.svg' url: 'http://resonate.io/' } { name: 'Slovenská Národná Galéria' logo: '/images/partners/logo-sng.svg' url: 'http://www.sng.sk' } { name: 'Lab' logo: '/images/partners/logo-lab.svg' # url: '#' } ] getTheme: -> '/themes/' + @site.theme getUrl: -> @site.url collections: speakers: -> @getCollection("html").findAllLive({relativeOutDirPath: 'speakers'}, [{time:1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"}) workshops: -> @getCollection("html").findAllLive({relativeOutDirPath: 'workshops'}, [{time:1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"}) activities: -> @getCollection("html").findAllLive({relativeOutDirPath: 'program'}, [{time:-1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"})
88981
module.exports = prompts: false templateData: conf: name: 'Sensorium 2016' description: 'Sensorium festival is a celebration of art and science taking place in Bratislava' date: 'April 19' price: '€10' venue: 'Berlinka, Slovenská Národná Galéria' address: 'Námestie Ľudovíta Štúra 33/4' city: 'Bratislava' country: 'Slovakia' site: theme: 'yellow-swan' url: 'http://sensorium.is' # googleanalytics: 'UA-33656081-1' # Styles styles: [ "/styles/bootstrap.css" # "/styles/style.css" "/styles/font-awesome-min.css" "/styles/instant-style.css" "/styles/ui-hover-effects.css" "/styles/ui-buttons.css" "/styles/schedule.css" "/styles/sponsors.css" "/styles/footer.css" ] # Scripts scripts: [ "/vendor/jquery.js" "/vendor/bootstrap.min.js" "/scripts/main.js" "/scripts/footerheight.js" "/scripts/script.js" ] sections: [ 'speakers' 'about' 'program' 'location' 'sponsors' 'partners' ] labels: about: 'About' location: 'Location' speakers: 'Speakers' program: 'Program' sponsors: 'Sponsors' partners: 'Partners' contact: 'Contact' schedule: [ # { # time: '18.00' # description: 'Welcome' # } { description: 'Special Guest | To be announced...' time: '18.00 - 19.00' } { description: '<NAME> | Domestic Data Streamers' time: '19.00 - 20.00' } { description: '<NAME> | Post Spectacular' time: '20.00 - 21.00' } ] sponsors: [ { name: '<NAME>' logo: '/images/sponsors/studio727.png' url: 'http://www.727.sk/' } { name: '<NAME>' logo: '/images/sponsors/nethemba.png' url: 'https://nethemba.com/sk' } ] partners: [ { name: '<NAME>' logo: '/images/partners/resonate-wordmark.svg' url: 'http://resonate.io/' } { name: '<NAME>' logo: '/images/partners/logo-sng.svg' url: 'http://www.sng.sk' } { name: '<NAME>' logo: '/images/partners/logo-lab.svg' # url: '#' } ] getTheme: -> '/themes/' + @site.theme getUrl: -> @site.url collections: speakers: -> @getCollection("html").findAllLive({relativeOutDirPath: 'speakers'}, [{time:1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"}) workshops: -> @getCollection("html").findAllLive({relativeOutDirPath: 'workshops'}, [{time:1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"}) activities: -> @getCollection("html").findAllLive({relativeOutDirPath: 'program'}, [{time:-1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"})
true
module.exports = prompts: false templateData: conf: name: 'Sensorium 2016' description: 'Sensorium festival is a celebration of art and science taking place in Bratislava' date: 'April 19' price: '€10' venue: 'Berlinka, Slovenská Národná Galéria' address: 'Námestie Ľudovíta Štúra 33/4' city: 'Bratislava' country: 'Slovakia' site: theme: 'yellow-swan' url: 'http://sensorium.is' # googleanalytics: 'UA-33656081-1' # Styles styles: [ "/styles/bootstrap.css" # "/styles/style.css" "/styles/font-awesome-min.css" "/styles/instant-style.css" "/styles/ui-hover-effects.css" "/styles/ui-buttons.css" "/styles/schedule.css" "/styles/sponsors.css" "/styles/footer.css" ] # Scripts scripts: [ "/vendor/jquery.js" "/vendor/bootstrap.min.js" "/scripts/main.js" "/scripts/footerheight.js" "/scripts/script.js" ] sections: [ 'speakers' 'about' 'program' 'location' 'sponsors' 'partners' ] labels: about: 'About' location: 'Location' speakers: 'Speakers' program: 'Program' sponsors: 'Sponsors' partners: 'Partners' contact: 'Contact' schedule: [ # { # time: '18.00' # description: 'Welcome' # } { description: 'Special Guest | To be announced...' time: '18.00 - 19.00' } { description: 'PI:NAME:<NAME>END_PI | Domestic Data Streamers' time: '19.00 - 20.00' } { description: 'PI:NAME:<NAME>END_PI | Post Spectacular' time: '20.00 - 21.00' } ] sponsors: [ { name: 'PI:NAME:<NAME>END_PI' logo: '/images/sponsors/studio727.png' url: 'http://www.727.sk/' } { name: 'PI:NAME:<NAME>END_PI' logo: '/images/sponsors/nethemba.png' url: 'https://nethemba.com/sk' } ] partners: [ { name: 'PI:NAME:<NAME>END_PI' logo: '/images/partners/resonate-wordmark.svg' url: 'http://resonate.io/' } { name: 'PI:NAME:<NAME>END_PI' logo: '/images/partners/logo-sng.svg' url: 'http://www.sng.sk' } { name: 'PI:NAME:<NAME>END_PI' logo: '/images/partners/logo-lab.svg' # url: '#' } ] getTheme: -> '/themes/' + @site.theme getUrl: -> @site.url collections: speakers: -> @getCollection("html").findAllLive({relativeOutDirPath: 'speakers'}, [{time:1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"}) workshops: -> @getCollection("html").findAllLive({relativeOutDirPath: 'workshops'}, [{time:1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"}) activities: -> @getCollection("html").findAllLive({relativeOutDirPath: 'program'}, [{time:-1}]).on "add", (model) -> model.setMetaDefaults({layout:"speaker"})
[ { "context": "###\n@author Nicholas Sardo <gcc.programmer@gmail.com>\n©2018 \n###\n\nimport { T", "end": 26, "score": 0.9998924136161804, "start": 12, "tag": "NAME", "value": "Nicholas Sardo" }, { "context": "###\n@author Nicholas Sardo <gcc.programmer@gmail.com>\n©2018 \n###\n\nimport { Template } from 'meteor/tem", "end": 52, "score": 0.9999315738677979, "start": 28, "tag": "EMAIL", "value": "gcc.programmer@gmail.com" } ]
client/main.coffee
nsardo/meteor-1.8-coffeescript-example
0
### @author Nicholas Sardo <gcc.programmer@gmail.com> ©2018 ### import { Template } from 'meteor/templating' import { Meteor } from 'meteor/meteor' import './main.coffee' Template.hello.onCreated = Session.setDefault 'counter', 0 Template.hello.helpers counter: -> Session.get 'counter' records: -> Session.get 'records' Template.hello.events 'click button#click1': -> console.log Session.get 'counter' Session.set 'counter', Session.get('counter') + 1 'click button#click2': -> #Session.set 'records', Meteor.call 'returnFoo' Meteor.call 'returnFoo', (err, result) -> console.error('cb err ', err) if err console.log('result is ', result) Session.set('records', result.title)
169967
### @author <NAME> <<EMAIL>> ©2018 ### import { Template } from 'meteor/templating' import { Meteor } from 'meteor/meteor' import './main.coffee' Template.hello.onCreated = Session.setDefault 'counter', 0 Template.hello.helpers counter: -> Session.get 'counter' records: -> Session.get 'records' Template.hello.events 'click button#click1': -> console.log Session.get 'counter' Session.set 'counter', Session.get('counter') + 1 'click button#click2': -> #Session.set 'records', Meteor.call 'returnFoo' Meteor.call 'returnFoo', (err, result) -> console.error('cb err ', err) if err console.log('result is ', result) Session.set('records', result.title)
true
### @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ©2018 ### import { Template } from 'meteor/templating' import { Meteor } from 'meteor/meteor' import './main.coffee' Template.hello.onCreated = Session.setDefault 'counter', 0 Template.hello.helpers counter: -> Session.get 'counter' records: -> Session.get 'records' Template.hello.events 'click button#click1': -> console.log Session.get 'counter' Session.set 'counter', Session.get('counter') + 1 'click button#click2': -> #Session.set 'records', Meteor.call 'returnFoo' Meteor.call 'returnFoo', (err, result) -> console.error('cb err ', err) if err console.log('result is ', result) Session.set('records', result.title)
[ { "context": "key_Z = 90\n key_questionmark = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad", "end": 6549, "score": 0.9314455389976501, "start": 6547, "tag": "KEY", "value": "48" }, { "context": "Z = 90\n key_questionmark = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [", "end": 6553, "score": 0.9460746049880981, "start": 6551, "tag": "KEY", "value": "49" }, { "context": "90\n key_questionmark = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, ", "end": 6557, "score": 0.8192967176437378, "start": 6555, "tag": "KEY", "value": "50" }, { "context": "key_questionmark = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, 97, ", "end": 6561, "score": 0.9205347895622253, "start": 6560, "tag": "KEY", "value": "1" }, { "context": "questionmark = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, 97, 98, ", "end": 6565, "score": 0.9074132442474365, "start": 6564, "tag": "KEY", "value": "2" }, { "context": "tionmark = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, 97, 98, 99, ", "end": 6569, "score": 0.9004343152046204, "start": 6568, "tag": "KEY", "value": "3" }, { "context": "mark = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, 97, 98, 99, 100,", "end": 6573, "score": 0.919346034526825, "start": 6572, "tag": "KEY", "value": "4" }, { "context": " = 191\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, 97, 98, 99, 100, 101", "end": 6577, "score": 0.9153489470481873, "start": 6576, "tag": "KEY", "value": "5" }, { "context": "91\n\n key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, 97, 98, 99, 100, 101, 10", "end": 6581, "score": 0.9394277334213257, "start": 6580, "tag": "KEY", "value": "6" }, { "context": " key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57]\n key_numpad = [96, 97, 98, 99, 100, 101, 102, 1", "end": 6585, "score": 0.8528074622154236, "start": 6584, "tag": "KEY", "value": "7" } ]
src/EventHandlers.coffee
dunkelziffer/Roofpig
0
#= require utils #= require OneChange #This is all page wide data and functions. class EventHandlers @initialized = false @set_focus: (new_focus) -> if @_focus != new_focus @dom.has_focus(false) if @_focus @_focus = new_focus unless @focus().is_null @camera = @_focus.world3d.camera @dom = @_focus.dom @dom.has_focus(true) NO_FOCUS = { add_changer: -> {} is_null: true } @focus: -> @_focus || NO_FOCUS @initialize: -> return if @initialized @down_keys = {} $('body').keydown (e) -> EventHandlers.key_down(e) $('body').keyup (e) -> EventHandlers.key_up(e) $(document).on('mousedown', '.roofpig', (e) -> EventHandlers.mouse_down(e, $(this).data('cube-id'))) $('body').mousemove (e) -> EventHandlers.mouse_move(e) $('body').mouseup (e) -> EventHandlers.mouse_end(e) $('body').mouseleave (e) -> EventHandlers.mouse_end(e) $(document).on('click', '.roofpig', (e) -> cube = CubeAnimation.by_id[$(this).data('cube-id')] EventHandlers.set_focus(cube) ) $(document).on('click', '.focus .mouse_target', (e) -> EventHandlers.left_cube_click(e, $(this).data('side')) ) $(document).on('contextmenu', '.focus .mouse_target', (e) -> EventHandlers.right_cube_click(e, $(this).data('side')) ) $(document).on('click', '.roofpig button', (e) -> [button_name, cube_id] = $(this).attr('id').split('-') CubeAnimation.by_id[cube_id].button_click(button_name, e.shiftKey) ) $(document).on('click', '.roofpig-help-button', (e) -> [_, cube_id] = $(this).attr('id').split('-') CubeAnimation.by_id[cube_id].dom.show_help() ) @initialized = true @mouse_down: (e, clicked_cube_id) -> @dom.remove_help() if clicked_cube_id == @focus().id @bend_start_x = e.pageX @bend_start_y = e.pageY @bending = true @mouse_end: (e) -> @focus().add_changer('camera', new OneChange( => @camera.bend(0, 0))) @bending = false @mouse_move: (e) -> if @bending dx = -0.02 * (e.pageX - @bend_start_x) / @dom.scale dy = -0.02 * (e.pageY - @bend_start_y) / @dom.scale if e.shiftKey dy = 0 @focus().add_changer('camera', new OneChange( => @camera.bend(dx, dy))) @left_cube_click: (e, click_side) -> this._handle_cube_click(e, click_side) @right_cube_click: (e, click_side) -> this._handle_cube_click(e, click_side) e.preventDefault() # no context menu @_handle_cube_click: (e, click_side) -> return false unless @focus().user_controlled() third_key = e.metaKey || e.ctrlKey opposite = false side_map = switch e.which when 1 # left button opposite = third_key if third_key then {F: 'B', U: 'D', R: 'L'} else {F: 'F', U: 'U', R: 'R'} when 3 # right button if third_key then {F: 'f', U: 'u', R: 'r'} else {F: 'z', U: 'y', R: 'x'} when 2 # middle button opposite = third_key if third_key then {F: 'b', U: 'd', R: 'l'} else {F: 'f', U: 'u', R: 'r'} @focus().external_move(side_map[click_side]+this._turns(e, opposite)) @_turns: (e, opposite = false) -> result = if e.shiftKey then -1 else if e.altKey then 2 else 1 result = -result if opposite { 1: '', 2: '2', '-1': "'", '-2': 'Z'}[result] # ---- Keyboard Events ---- @key_down: (e) -> @down_keys[e.keyCode] = true return if @focus().is_null help_toggled = @dom.remove_help() if this.cube_key_moves(e) return true if e.ctrlKey || e.metaKey || e.altKey return true [key, shift] = [e.keyCode, e.shiftKey] if key == key_tab new_focus = if shift then @focus().previous_cube() else @focus().next_cube() this.set_focus(new_focus) else if key == key_end || (key == key_right_arrow && shift) @focus().add_changer('pieces', new OneChange( => @focus().alg.to_end(@focus().world3d))) else if key in button_keys this._fake_click_down(this._button_for(key, shift)) else if key == key_questionmark @focus().dom.show_help() unless help_toggled else unhandled = true unless unhandled e.preventDefault() e.stopPropagation() @cube_key_moves: (e) -> return false unless @focus().user_controlled() number_key = Math.max(key_num.indexOf(e.keyCode), key_numpad.indexOf(e.keyCode)) return false unless number_key > 0 side = switch number_key when 1, 4, 7 then "F" when 2, 5, 8 then "U" when 3, 6, 9 then "R" turns = switch number_key when 1, 2, 3 then 2 when 4, 5, 6 then 1 when 7, 8, 9 then -1 turn_code = Move.turn_code(turns) anti_turn_code = Move.turn_code(-turns) opposite = @down_keys[key_Z] middle = @down_keys[key_X] the_side = @down_keys[key_C] || (!opposite && !middle) moves = [] if the_side moves.push("#{side}#{turn_code}") if middle switch side when 'F' then moves.push("S"+turn_code) when 'U' then moves.push("E"+anti_turn_code) when 'R' then moves.push("M"+anti_turn_code) if opposite switch side when 'F' then moves.push("B"+anti_turn_code) when 'U' then moves.push("D"+anti_turn_code) when 'R' then moves.push("L"+anti_turn_code) @focus().external_move(moves.join('+')) true @_button_for: (key, shift) -> switch key when key_home @dom.reset when key_left_arrow unless shift then @dom.prev else @dom.reset when key_right_arrow @dom.next when key_space @dom.play_or_pause @key_up: (e) -> @down_keys[e.keyCode] = false button_key = e.keyCode in button_keys if button_key if @down_button this._fake_click_up(@down_button) @down_button = null return button_key @_fake_click_down: (button) -> unless button.attr("disabled") @down_button = button button.addClass('roofpig-button-fake-active') @_fake_click_up: (button) -> unless button.attr("disabled") button.removeClass('roofpig-button-fake-active') button.click() # http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes key_tab = 9 key_space = 32 key_end = 35 key_home = 36 key_left_arrow = 37 key_up_arrow = 38 key_right_arrow = 39 key_down_arrow = 40 key_A = 65 key_C = 67 key_D = 68 key_J = 74 key_K = 75 key_L = 76 key_S = 83 key_X = 88 key_Z = 90 key_questionmark = 191 key_num = [48, 49, 50, 51, 52 ,53 ,54 ,55, 56, 57] key_numpad = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105] button_keys = [key_space, key_home, key_left_arrow, key_right_arrow]
204734
#= require utils #= require OneChange #This is all page wide data and functions. class EventHandlers @initialized = false @set_focus: (new_focus) -> if @_focus != new_focus @dom.has_focus(false) if @_focus @_focus = new_focus unless @focus().is_null @camera = @_focus.world3d.camera @dom = @_focus.dom @dom.has_focus(true) NO_FOCUS = { add_changer: -> {} is_null: true } @focus: -> @_focus || NO_FOCUS @initialize: -> return if @initialized @down_keys = {} $('body').keydown (e) -> EventHandlers.key_down(e) $('body').keyup (e) -> EventHandlers.key_up(e) $(document).on('mousedown', '.roofpig', (e) -> EventHandlers.mouse_down(e, $(this).data('cube-id'))) $('body').mousemove (e) -> EventHandlers.mouse_move(e) $('body').mouseup (e) -> EventHandlers.mouse_end(e) $('body').mouseleave (e) -> EventHandlers.mouse_end(e) $(document).on('click', '.roofpig', (e) -> cube = CubeAnimation.by_id[$(this).data('cube-id')] EventHandlers.set_focus(cube) ) $(document).on('click', '.focus .mouse_target', (e) -> EventHandlers.left_cube_click(e, $(this).data('side')) ) $(document).on('contextmenu', '.focus .mouse_target', (e) -> EventHandlers.right_cube_click(e, $(this).data('side')) ) $(document).on('click', '.roofpig button', (e) -> [button_name, cube_id] = $(this).attr('id').split('-') CubeAnimation.by_id[cube_id].button_click(button_name, e.shiftKey) ) $(document).on('click', '.roofpig-help-button', (e) -> [_, cube_id] = $(this).attr('id').split('-') CubeAnimation.by_id[cube_id].dom.show_help() ) @initialized = true @mouse_down: (e, clicked_cube_id) -> @dom.remove_help() if clicked_cube_id == @focus().id @bend_start_x = e.pageX @bend_start_y = e.pageY @bending = true @mouse_end: (e) -> @focus().add_changer('camera', new OneChange( => @camera.bend(0, 0))) @bending = false @mouse_move: (e) -> if @bending dx = -0.02 * (e.pageX - @bend_start_x) / @dom.scale dy = -0.02 * (e.pageY - @bend_start_y) / @dom.scale if e.shiftKey dy = 0 @focus().add_changer('camera', new OneChange( => @camera.bend(dx, dy))) @left_cube_click: (e, click_side) -> this._handle_cube_click(e, click_side) @right_cube_click: (e, click_side) -> this._handle_cube_click(e, click_side) e.preventDefault() # no context menu @_handle_cube_click: (e, click_side) -> return false unless @focus().user_controlled() third_key = e.metaKey || e.ctrlKey opposite = false side_map = switch e.which when 1 # left button opposite = third_key if third_key then {F: 'B', U: 'D', R: 'L'} else {F: 'F', U: 'U', R: 'R'} when 3 # right button if third_key then {F: 'f', U: 'u', R: 'r'} else {F: 'z', U: 'y', R: 'x'} when 2 # middle button opposite = third_key if third_key then {F: 'b', U: 'd', R: 'l'} else {F: 'f', U: 'u', R: 'r'} @focus().external_move(side_map[click_side]+this._turns(e, opposite)) @_turns: (e, opposite = false) -> result = if e.shiftKey then -1 else if e.altKey then 2 else 1 result = -result if opposite { 1: '', 2: '2', '-1': "'", '-2': 'Z'}[result] # ---- Keyboard Events ---- @key_down: (e) -> @down_keys[e.keyCode] = true return if @focus().is_null help_toggled = @dom.remove_help() if this.cube_key_moves(e) return true if e.ctrlKey || e.metaKey || e.altKey return true [key, shift] = [e.keyCode, e.shiftKey] if key == key_tab new_focus = if shift then @focus().previous_cube() else @focus().next_cube() this.set_focus(new_focus) else if key == key_end || (key == key_right_arrow && shift) @focus().add_changer('pieces', new OneChange( => @focus().alg.to_end(@focus().world3d))) else if key in button_keys this._fake_click_down(this._button_for(key, shift)) else if key == key_questionmark @focus().dom.show_help() unless help_toggled else unhandled = true unless unhandled e.preventDefault() e.stopPropagation() @cube_key_moves: (e) -> return false unless @focus().user_controlled() number_key = Math.max(key_num.indexOf(e.keyCode), key_numpad.indexOf(e.keyCode)) return false unless number_key > 0 side = switch number_key when 1, 4, 7 then "F" when 2, 5, 8 then "U" when 3, 6, 9 then "R" turns = switch number_key when 1, 2, 3 then 2 when 4, 5, 6 then 1 when 7, 8, 9 then -1 turn_code = Move.turn_code(turns) anti_turn_code = Move.turn_code(-turns) opposite = @down_keys[key_Z] middle = @down_keys[key_X] the_side = @down_keys[key_C] || (!opposite && !middle) moves = [] if the_side moves.push("#{side}#{turn_code}") if middle switch side when 'F' then moves.push("S"+turn_code) when 'U' then moves.push("E"+anti_turn_code) when 'R' then moves.push("M"+anti_turn_code) if opposite switch side when 'F' then moves.push("B"+anti_turn_code) when 'U' then moves.push("D"+anti_turn_code) when 'R' then moves.push("L"+anti_turn_code) @focus().external_move(moves.join('+')) true @_button_for: (key, shift) -> switch key when key_home @dom.reset when key_left_arrow unless shift then @dom.prev else @dom.reset when key_right_arrow @dom.next when key_space @dom.play_or_pause @key_up: (e) -> @down_keys[e.keyCode] = false button_key = e.keyCode in button_keys if button_key if @down_button this._fake_click_up(@down_button) @down_button = null return button_key @_fake_click_down: (button) -> unless button.attr("disabled") @down_button = button button.addClass('roofpig-button-fake-active') @_fake_click_up: (button) -> unless button.attr("disabled") button.removeClass('roofpig-button-fake-active') button.click() # http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes key_tab = 9 key_space = 32 key_end = 35 key_home = 36 key_left_arrow = 37 key_up_arrow = 38 key_right_arrow = 39 key_down_arrow = 40 key_A = 65 key_C = 67 key_D = 68 key_J = 74 key_K = 75 key_L = 76 key_S = 83 key_X = 88 key_Z = 90 key_questionmark = 191 key_num = [<KEY>, <KEY>, <KEY>, 5<KEY>, 5<KEY> ,5<KEY> ,5<KEY> ,5<KEY>, 5<KEY>, 5<KEY>] key_numpad = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105] button_keys = [key_space, key_home, key_left_arrow, key_right_arrow]
true
#= require utils #= require OneChange #This is all page wide data and functions. class EventHandlers @initialized = false @set_focus: (new_focus) -> if @_focus != new_focus @dom.has_focus(false) if @_focus @_focus = new_focus unless @focus().is_null @camera = @_focus.world3d.camera @dom = @_focus.dom @dom.has_focus(true) NO_FOCUS = { add_changer: -> {} is_null: true } @focus: -> @_focus || NO_FOCUS @initialize: -> return if @initialized @down_keys = {} $('body').keydown (e) -> EventHandlers.key_down(e) $('body').keyup (e) -> EventHandlers.key_up(e) $(document).on('mousedown', '.roofpig', (e) -> EventHandlers.mouse_down(e, $(this).data('cube-id'))) $('body').mousemove (e) -> EventHandlers.mouse_move(e) $('body').mouseup (e) -> EventHandlers.mouse_end(e) $('body').mouseleave (e) -> EventHandlers.mouse_end(e) $(document).on('click', '.roofpig', (e) -> cube = CubeAnimation.by_id[$(this).data('cube-id')] EventHandlers.set_focus(cube) ) $(document).on('click', '.focus .mouse_target', (e) -> EventHandlers.left_cube_click(e, $(this).data('side')) ) $(document).on('contextmenu', '.focus .mouse_target', (e) -> EventHandlers.right_cube_click(e, $(this).data('side')) ) $(document).on('click', '.roofpig button', (e) -> [button_name, cube_id] = $(this).attr('id').split('-') CubeAnimation.by_id[cube_id].button_click(button_name, e.shiftKey) ) $(document).on('click', '.roofpig-help-button', (e) -> [_, cube_id] = $(this).attr('id').split('-') CubeAnimation.by_id[cube_id].dom.show_help() ) @initialized = true @mouse_down: (e, clicked_cube_id) -> @dom.remove_help() if clicked_cube_id == @focus().id @bend_start_x = e.pageX @bend_start_y = e.pageY @bending = true @mouse_end: (e) -> @focus().add_changer('camera', new OneChange( => @camera.bend(0, 0))) @bending = false @mouse_move: (e) -> if @bending dx = -0.02 * (e.pageX - @bend_start_x) / @dom.scale dy = -0.02 * (e.pageY - @bend_start_y) / @dom.scale if e.shiftKey dy = 0 @focus().add_changer('camera', new OneChange( => @camera.bend(dx, dy))) @left_cube_click: (e, click_side) -> this._handle_cube_click(e, click_side) @right_cube_click: (e, click_side) -> this._handle_cube_click(e, click_side) e.preventDefault() # no context menu @_handle_cube_click: (e, click_side) -> return false unless @focus().user_controlled() third_key = e.metaKey || e.ctrlKey opposite = false side_map = switch e.which when 1 # left button opposite = third_key if third_key then {F: 'B', U: 'D', R: 'L'} else {F: 'F', U: 'U', R: 'R'} when 3 # right button if third_key then {F: 'f', U: 'u', R: 'r'} else {F: 'z', U: 'y', R: 'x'} when 2 # middle button opposite = third_key if third_key then {F: 'b', U: 'd', R: 'l'} else {F: 'f', U: 'u', R: 'r'} @focus().external_move(side_map[click_side]+this._turns(e, opposite)) @_turns: (e, opposite = false) -> result = if e.shiftKey then -1 else if e.altKey then 2 else 1 result = -result if opposite { 1: '', 2: '2', '-1': "'", '-2': 'Z'}[result] # ---- Keyboard Events ---- @key_down: (e) -> @down_keys[e.keyCode] = true return if @focus().is_null help_toggled = @dom.remove_help() if this.cube_key_moves(e) return true if e.ctrlKey || e.metaKey || e.altKey return true [key, shift] = [e.keyCode, e.shiftKey] if key == key_tab new_focus = if shift then @focus().previous_cube() else @focus().next_cube() this.set_focus(new_focus) else if key == key_end || (key == key_right_arrow && shift) @focus().add_changer('pieces', new OneChange( => @focus().alg.to_end(@focus().world3d))) else if key in button_keys this._fake_click_down(this._button_for(key, shift)) else if key == key_questionmark @focus().dom.show_help() unless help_toggled else unhandled = true unless unhandled e.preventDefault() e.stopPropagation() @cube_key_moves: (e) -> return false unless @focus().user_controlled() number_key = Math.max(key_num.indexOf(e.keyCode), key_numpad.indexOf(e.keyCode)) return false unless number_key > 0 side = switch number_key when 1, 4, 7 then "F" when 2, 5, 8 then "U" when 3, 6, 9 then "R" turns = switch number_key when 1, 2, 3 then 2 when 4, 5, 6 then 1 when 7, 8, 9 then -1 turn_code = Move.turn_code(turns) anti_turn_code = Move.turn_code(-turns) opposite = @down_keys[key_Z] middle = @down_keys[key_X] the_side = @down_keys[key_C] || (!opposite && !middle) moves = [] if the_side moves.push("#{side}#{turn_code}") if middle switch side when 'F' then moves.push("S"+turn_code) when 'U' then moves.push("E"+anti_turn_code) when 'R' then moves.push("M"+anti_turn_code) if opposite switch side when 'F' then moves.push("B"+anti_turn_code) when 'U' then moves.push("D"+anti_turn_code) when 'R' then moves.push("L"+anti_turn_code) @focus().external_move(moves.join('+')) true @_button_for: (key, shift) -> switch key when key_home @dom.reset when key_left_arrow unless shift then @dom.prev else @dom.reset when key_right_arrow @dom.next when key_space @dom.play_or_pause @key_up: (e) -> @down_keys[e.keyCode] = false button_key = e.keyCode in button_keys if button_key if @down_button this._fake_click_up(@down_button) @down_button = null return button_key @_fake_click_down: (button) -> unless button.attr("disabled") @down_button = button button.addClass('roofpig-button-fake-active') @_fake_click_up: (button) -> unless button.attr("disabled") button.removeClass('roofpig-button-fake-active') button.click() # http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes key_tab = 9 key_space = 32 key_end = 35 key_home = 36 key_left_arrow = 37 key_up_arrow = 38 key_right_arrow = 39 key_down_arrow = 40 key_A = 65 key_C = 67 key_D = 68 key_J = 74 key_K = 75 key_L = 76 key_S = 83 key_X = 88 key_Z = 90 key_questionmark = 191 key_num = [PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI, PI:KEY:<KEY>END_PI, 5PI:KEY:<KEY>END_PI, 5PI:KEY:<KEY>END_PI ,5PI:KEY:<KEY>END_PI ,5PI:KEY:<KEY>END_PI ,5PI:KEY:<KEY>END_PI, 5PI:KEY:<KEY>END_PI, 5PI:KEY:<KEY>END_PI] key_numpad = [96, 97, 98, 99, 100, 101, 102, 103, 104, 105] button_keys = [key_space, key_home, key_left_arrow, key_right_arrow]
[ { "context": ":\n# Coconut pictures, based on\n# Applause from Orson Welles and others\n#\n# Dependencies:\n# None\n#\n# Configu", "end": 76, "score": 0.9961780309677124, "start": 64, "tag": "NAME", "value": "Orson Welles" }, { "context": "s:\n# coconut - Get coconut image\n#\n# Author:\n# mxlje\n\nimages = [\n \"http://i.imgur.com/wyGu3R4.jpg\",\n ", "end": 210, "score": 0.9997227191925049, "start": 205, "tag": "USERNAME", "value": "mxlje" } ]
scripts/coconut.coffee
mxlje/ben
0
# Description: # Coconut pictures, based on # Applause from Orson Welles and others # # Dependencies: # None # # Configuration: # None # # Commands: # coconut - Get coconut image # # Author: # mxlje images = [ "http://i.imgur.com/wyGu3R4.jpg", "http://i.imgur.com/eDVVKXZ.jpg", "http://i.imgur.com/1rbE6Gt.jpg", "http://i.imgur.com/HuQyy1O.jpg" ] module.exports = (robot) -> robot.hear /coconut/i, (msg) -> msg.send msg.random images
150876
# Description: # Coconut pictures, based on # Applause from <NAME> and others # # Dependencies: # None # # Configuration: # None # # Commands: # coconut - Get coconut image # # Author: # mxlje images = [ "http://i.imgur.com/wyGu3R4.jpg", "http://i.imgur.com/eDVVKXZ.jpg", "http://i.imgur.com/1rbE6Gt.jpg", "http://i.imgur.com/HuQyy1O.jpg" ] module.exports = (robot) -> robot.hear /coconut/i, (msg) -> msg.send msg.random images
true
# Description: # Coconut pictures, based on # Applause from PI:NAME:<NAME>END_PI and others # # Dependencies: # None # # Configuration: # None # # Commands: # coconut - Get coconut image # # Author: # mxlje images = [ "http://i.imgur.com/wyGu3R4.jpg", "http://i.imgur.com/eDVVKXZ.jpg", "http://i.imgur.com/1rbE6Gt.jpg", "http://i.imgur.com/HuQyy1O.jpg" ] module.exports = (robot) -> robot.hear /coconut/i, (msg) -> msg.send msg.random images
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.999912440776825, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/search.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @Search constructor: -> @debouncedSubmitInput = _.debounce @submitInput, 500 $(document).on 'click', '.js-search--forum-options-reset', @forumPostReset $(document).on 'input', '.js-search--input', @debouncedSubmitInput $(document).on 'keydown', '.js-search--input', @maybeSubmitInput $(document).on 'submit', '.js-search', @submitForm addEventListener 'turbolinks:load', @restoreFocus forumPostReset: => $form = $('.js-search') $form.find('[name=username], [name=forum_id]').val '' $form.find('[name=forum_children]').prop 'checked', false maybeSubmitInput: (e) => return if e.keyCode != 13 e.preventDefault() @submitInput(e) submitInput: (e) => input = e.currentTarget value = input.value.trim() return if value in ['', input.dataset.searchCurrent?.trim()] input.dataset.searchCurrent = value @submit() submitForm: (e) => e.preventDefault() @submit() submit: => @searchingToggle(true) params = $('.js-search').serialize() $(document).one 'turbolinks:before-cache', => @activeElement = document.activeElement @searchingToggle(false) Turbolinks.visit("?#{params}") searchingToggle: (state) => $('.js-search--header').toggleClass('js-search--searching', state) restoreFocus: => @activeElement?.focus() @activeElement = null
213225
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @Search constructor: -> @debouncedSubmitInput = _.debounce @submitInput, 500 $(document).on 'click', '.js-search--forum-options-reset', @forumPostReset $(document).on 'input', '.js-search--input', @debouncedSubmitInput $(document).on 'keydown', '.js-search--input', @maybeSubmitInput $(document).on 'submit', '.js-search', @submitForm addEventListener 'turbolinks:load', @restoreFocus forumPostReset: => $form = $('.js-search') $form.find('[name=username], [name=forum_id]').val '' $form.find('[name=forum_children]').prop 'checked', false maybeSubmitInput: (e) => return if e.keyCode != 13 e.preventDefault() @submitInput(e) submitInput: (e) => input = e.currentTarget value = input.value.trim() return if value in ['', input.dataset.searchCurrent?.trim()] input.dataset.searchCurrent = value @submit() submitForm: (e) => e.preventDefault() @submit() submit: => @searchingToggle(true) params = $('.js-search').serialize() $(document).one 'turbolinks:before-cache', => @activeElement = document.activeElement @searchingToggle(false) Turbolinks.visit("?#{params}") searchingToggle: (state) => $('.js-search--header').toggleClass('js-search--searching', state) restoreFocus: => @activeElement?.focus() @activeElement = null
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @Search constructor: -> @debouncedSubmitInput = _.debounce @submitInput, 500 $(document).on 'click', '.js-search--forum-options-reset', @forumPostReset $(document).on 'input', '.js-search--input', @debouncedSubmitInput $(document).on 'keydown', '.js-search--input', @maybeSubmitInput $(document).on 'submit', '.js-search', @submitForm addEventListener 'turbolinks:load', @restoreFocus forumPostReset: => $form = $('.js-search') $form.find('[name=username], [name=forum_id]').val '' $form.find('[name=forum_children]').prop 'checked', false maybeSubmitInput: (e) => return if e.keyCode != 13 e.preventDefault() @submitInput(e) submitInput: (e) => input = e.currentTarget value = input.value.trim() return if value in ['', input.dataset.searchCurrent?.trim()] input.dataset.searchCurrent = value @submit() submitForm: (e) => e.preventDefault() @submit() submit: => @searchingToggle(true) params = $('.js-search').serialize() $(document).one 'turbolinks:before-cache', => @activeElement = document.activeElement @searchingToggle(false) Turbolinks.visit("?#{params}") searchingToggle: (state) => $('.js-search--header').toggleClass('js-search--searching', state) restoreFocus: => @activeElement?.focus() @activeElement = null
[ { "context": "key: 'math-inline'\npatterns: [\n\n name: 'inline.math.markup.md'\n m", "end": 17, "score": 0.9337267875671387, "start": 6, "tag": "KEY", "value": "math-inline" } ]
grammars/repositories/flavors/math-inline.cson
doc22940/language-markdown
138
key: 'math-inline' patterns: [ name: 'inline.math.markup.md' match: '(\\$)(?! )(.+?)(?<! )(\\$)(?!\\d)' captures: 1: name: 'punctuation.md' 2: patterns: [{ include: 'text.tex.latex' }] 3: name: 'punctuation.md' ]
72273
key: '<KEY>' patterns: [ name: 'inline.math.markup.md' match: '(\\$)(?! )(.+?)(?<! )(\\$)(?!\\d)' captures: 1: name: 'punctuation.md' 2: patterns: [{ include: 'text.tex.latex' }] 3: name: 'punctuation.md' ]
true
key: 'PI:KEY:<KEY>END_PI' patterns: [ name: 'inline.math.markup.md' match: '(\\$)(?! )(.+?)(?<! )(\\$)(?!\\d)' captures: 1: name: 'punctuation.md' 2: patterns: [{ include: 'text.tex.latex' }] 3: name: 'punctuation.md' ]