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": "ok /is a thirteen episode anime series directed by Akitaro Daichi and written by Hideyuki Kurata/.test(html)\n", "end": 734, "score": 0.9998883008956909, "start": 720, "tag": "NAME", "value": "Akitaro Daichi" }, { "context": "e series directed by Akitaro Daichi and writ...
test/formatter.coffee
Falkirks/node-unfluff
1,173
suite 'Formatter', -> formatter = require("../src/formatter") cheerio = require("cheerio") test 'exists', -> ok formatter test 'replaces links with plain text', -> html = fs.readFileSync("./fixtures/test_businessWeek1.html").toString() origDoc = cheerio.load(html) eq origDoc("a").length, 232 formatter(origDoc, origDoc('body'), 'en') eq origDoc("a").length, 0 test 'doesn\'t drop text nodes accidentally', -> html = fs.readFileSync("./fixtures/test_wikipedia1.html").toString() doc = cheerio.load(html) formatter(doc, doc('body'), 'en') html = doc.html() # This text was getting dropped by the formatter ok /is a thirteen episode anime series directed by Akitaro Daichi and written by Hideyuki Kurata/.test(html)
7866
suite 'Formatter', -> formatter = require("../src/formatter") cheerio = require("cheerio") test 'exists', -> ok formatter test 'replaces links with plain text', -> html = fs.readFileSync("./fixtures/test_businessWeek1.html").toString() origDoc = cheerio.load(html) eq origDoc("a").length, 232 formatter(origDoc, origDoc('body'), 'en') eq origDoc("a").length, 0 test 'doesn\'t drop text nodes accidentally', -> html = fs.readFileSync("./fixtures/test_wikipedia1.html").toString() doc = cheerio.load(html) formatter(doc, doc('body'), 'en') html = doc.html() # This text was getting dropped by the formatter ok /is a thirteen episode anime series directed by <NAME> and written by <NAME>/.test(html)
true
suite 'Formatter', -> formatter = require("../src/formatter") cheerio = require("cheerio") test 'exists', -> ok formatter test 'replaces links with plain text', -> html = fs.readFileSync("./fixtures/test_businessWeek1.html").toString() origDoc = cheerio.load(html) eq origDoc("a").length, 232 formatter(origDoc, origDoc('body'), 'en') eq origDoc("a").length, 0 test 'doesn\'t drop text nodes accidentally', -> html = fs.readFileSync("./fixtures/test_wikipedia1.html").toString() doc = cheerio.load(html) formatter(doc, doc('body'), 'en') html = doc.html() # This text was getting dropped by the formatter ok /is a thirteen episode anime series directed by PI:NAME:<NAME>END_PI and written by PI:NAME:<NAME>END_PI/.test(html)
[ { "context": "aCluster.clusterCount}\"\n @name = \"Customers DB\"\n @state = \"active\"\n @status ", "end": 243, "score": 0.7196711301803589, "start": 231, "tag": "NAME", "value": "Customers DB" }, { "context": "= 'cluster'\n @tunnelCredentials ...
stage/shims/data-cluster.coffee
nanobox-io/nanobox-dash-ui-clobber-box
1
Host = require './host' module.exports = class DataCluster @clusterCount : 0 constructor: () -> totalGenerations = 1 @id = "cluster.#{DataCluster.clusterCount}" @name = "Customers DB" @state = "active" @status = "online" @running = false @serviceType = "mysql-db" @category = "data" @clusterable = true @adminPath = "/some/path/to/admin" @uri = @id @generations = [] @clusterShapeIs = 'data-single' @clusterShapeCanBe = clobbershim.getClusterPotential(false) @topology = 'cluster' @tunnelCredentials = host: "127.0.0.1", port: "provided in tunnel command output" for i in [1..totalGenerations] generation = id : "db.main.gen#{i}" state : "active" # Not used ? status : "online" # Not used ? instances : [] roles = ['primary', 'secondary', 'arbiter'] for role, i in roles generation.instances.push id : i hostId : "do.#{i}" hostName : "do.#{i}" state : "active" status : "online" role : role serverSpecsId : "d16" running : true @generations.push generation # # @appComponent = new AppComponent() # delete # @instances = [] # delete # for i in [1..totalMembers] # @instances.push {id:"web.#{AppComponent.appComponentCount}.#{i}", hostId:"ec2.#{++Host.hostCount}", hostName:"ec2.#{Host.hostCount}"} serialize : () -> id : @id uid : @id state : @state status : @status running : @running name : @name category : @category clusterable : @clusterable generations : @generations serviceType : @serviceType adminPath : @adminPath uri : @uri clusterShapeIs : @clusterShapeIs clusterShapeCanBe : @clusterShapeCanBe topology : @topology tunnelCredentials : @tunnelCredentials # instances : @instances
48959
Host = require './host' module.exports = class DataCluster @clusterCount : 0 constructor: () -> totalGenerations = 1 @id = "cluster.#{DataCluster.clusterCount}" @name = "<NAME>" @state = "active" @status = "online" @running = false @serviceType = "mysql-db" @category = "data" @clusterable = true @adminPath = "/some/path/to/admin" @uri = @id @generations = [] @clusterShapeIs = 'data-single' @clusterShapeCanBe = clobbershim.getClusterPotential(false) @topology = 'cluster' @tunnelCredentials = host: "127.0.0.1", port: "provided in tunnel command output" for i in [1..totalGenerations] generation = id : "db.main.gen#{i}" state : "active" # Not used ? status : "online" # Not used ? instances : [] roles = ['primary', 'secondary', 'arbiter'] for role, i in roles generation.instances.push id : i hostId : "do.#{i}" hostName : "do.#{i}" state : "active" status : "online" role : role serverSpecsId : "d16" running : true @generations.push generation # # @appComponent = new AppComponent() # delete # @instances = [] # delete # for i in [1..totalMembers] # @instances.push {id:"web.#{AppComponent.appComponentCount}.#{i}", hostId:"ec2.#{++Host.hostCount}", hostName:"ec2.#{Host.hostCount}"} serialize : () -> id : @id uid : @id state : @state status : @status running : @running name :<NAME> @name category : @category clusterable : @clusterable generations : @generations serviceType : @serviceType adminPath : @adminPath uri : @uri clusterShapeIs : @clusterShapeIs clusterShapeCanBe : @clusterShapeCanBe topology : @topology tunnelCredentials : @tunnelCredentials # instances : @instances
true
Host = require './host' module.exports = class DataCluster @clusterCount : 0 constructor: () -> totalGenerations = 1 @id = "cluster.#{DataCluster.clusterCount}" @name = "PI:NAME:<NAME>END_PI" @state = "active" @status = "online" @running = false @serviceType = "mysql-db" @category = "data" @clusterable = true @adminPath = "/some/path/to/admin" @uri = @id @generations = [] @clusterShapeIs = 'data-single' @clusterShapeCanBe = clobbershim.getClusterPotential(false) @topology = 'cluster' @tunnelCredentials = host: "127.0.0.1", port: "provided in tunnel command output" for i in [1..totalGenerations] generation = id : "db.main.gen#{i}" state : "active" # Not used ? status : "online" # Not used ? instances : [] roles = ['primary', 'secondary', 'arbiter'] for role, i in roles generation.instances.push id : i hostId : "do.#{i}" hostName : "do.#{i}" state : "active" status : "online" role : role serverSpecsId : "d16" running : true @generations.push generation # # @appComponent = new AppComponent() # delete # @instances = [] # delete # for i in [1..totalMembers] # @instances.push {id:"web.#{AppComponent.appComponentCount}.#{i}", hostId:"ec2.#{++Host.hostCount}", hostName:"ec2.#{Host.hostCount}"} serialize : () -> id : @id uid : @id state : @state status : @status running : @running name :PI:NAME:<NAME>END_PI @name category : @category clusterable : @clusterable generations : @generations serviceType : @serviceType adminPath : @adminPath uri : @uri clusterShapeIs : @clusterShapeIs clusterShapeCanBe : @clusterShapeCanBe topology : @topology tunnelCredentials : @tunnelCredentials # instances : @instances
[ { "context": ".to.equal 'https://imgflo.herokuapp.com/graph/key/6e48078f4a068533f7112dc63c28df9f/passthrough.jpeg?input=https%3A%2F%2Fimgflo.herok", "end": 2868, "score": 0.9606040120124817, "start": 2836, "tag": "KEY", "value": "6e48078f4a068533f7112dc63c28df9f" }, { "context": ".to...
spec/imgflo-url.coffee
imgflo/imgflo-url
0
{expect} = require 'chai' imgflo = require '../lib/imgflo-url' getConfig = -> server: 'https://imgflo.herokuapp.com/' key: 'key' secret: 'secret' describe 'imgflo-url', -> describe 'without a config object', -> it 'should throw an error', -> exercise = -> imgflo null, 'passthrough' expect(exercise).to.throw Error, 'imgflo config object not provided' describe 'with a config object', -> context 'without a server', -> it 'should throw an error', -> exercise = -> config = key: 'key' secret: 'secret' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "server" key' context 'without a key', -> it 'should throw an error', -> exercise = -> config = server: 'https://imgflo.herokuapp.com/' secret: 'secret' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "key" key' context 'without a secret', -> it 'should throw an error', -> exercise = -> config = server: 'https://imgflo.herokuapp.com/' key: 'key' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "secret" key' describe 'without imgflo params', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, 'passthrough' expect(exercise).to.throw Error, 'imgflo params not provided' describe 'with imgflo params', -> context 'without an input URL', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, 'passthrough', {} expect(exercise).to.throw Error, 'imgflo params must contain an "input" key' context 'with an input URL for a GIF image', -> it 'should return a proxying URL with noop graph', -> config = getConfig() url = imgflo config, 'passthrough', input: 'https://a.com/b.gif' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/408ff9579217fc27ec7472b8de5e8c3b/noop.gif?input=https%3A%2F%2Fa.com%2Fb.gif' context 'with an imgflo noop url', -> it 'should return double-encoded passthrough', -> config = getConfig() url = imgflo config, 'passthrough', input: 'https://imgflo.herokuapp.com/graph/vahj1ThiexotieMo/5764f83177c27abe632d7dce03e55e6d/noop.jpeg?input=https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1200%2F1*f7gpfegwe5jhpYs_1R_neA.jpeg' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/6e48078f4a068533f7112dc63c28df9f/passthrough.jpeg?input=https%3A%2F%2Fimgflo.herokuapp.com%2Fgraph%2Fvahj1ThiexotieMo%2F5764f83177c27abe632d7dce03e55e6d%2Fnoop.jpeg%3Finput%3Dhttps%253A%252F%252Fcdn-images-1.medium.com%252Fmax%252F1200%252F1*f7gpfegwe5jhpYs_1R_neA.jpeg' context 'with an input data: URL', -> it 'should return the same URL', -> config = getConfig() url = imgflo config, 'passthrough', input: 'data:image/gif;base64,R0lGODlhDwAMAL...' expect(url).to.equal 'data:image/gif;base64,R0lGODlhDwAMAL...' context 'with an input blob: URL', -> it 'should return the same URL', -> config = getConfig() url = imgflo config, 'passthrough', input: 'blob:http://localhost/0000-0123' expect(url).to.equal 'blob:http://localhost/0000-0123' context 'with twitter image url issues', -> it '.jpg:large should return noop.jpg', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' url = imgflo config, 'noop', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/0125cf1fec905afdcf07a2963c907b2d/noop.jpg?input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge" it '.jpg%3Alarge should return noop.jpg', -> config = getConfig() params = input: 'https://imgflo.herokuapp.com/graph/2b2431f8e7ba7b0/dabcd2b47c33e25505fb1f5615586fb5/noop.jpg?input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FCocKWjJWEAAlPJI.jpg%3Alarge' url = imgflo config, 'noop', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/c2ee25e62a242c68c32702ad90aedf2e/noop.jpg?input=https%3A%2F%2Fimgflo.herokuapp.com%2Fgraph%2F2b2431f8e7ba7b0%2Fdabcd2b47c33e25505fb1f5615586fb5%2Fnoop.jpg%3Finput%3Dhttps%253A%252F%252Fpbs.twimg.com%252Fmedia%252FCocKWjJWEAAlPJI.jpg%253Alarge" describe 'without a graph name', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, null, input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo graph name not provided' describe 'with imgflo params', -> context 'not specifying an image format', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/49467a1d8a94cf6c8350841299ecfb56/gradientmap.jpg?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge&srgb=true" context 'with a url with query parameters', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://v.cdn.vine.co/r/videos/B5B06468B91176403722801139712_342c9a1c624.1.5.15775156368984795444.mp4.jpg?versionId=edU_LrAtIFsGvZj.Fgi0Si1bem68tBlk' url = imgflo config, 'passthrough', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/0256dbdaea357ae9928f19c50d3d088a/passthrough.jpg?input=https%3A%2F%2Fv.cdn.vine.co%2Fr%2Fvideos%2FB5B06468B91176403722801139712_342c9a1c624.1.5.15775156368984795444.mp4.jpg%3FversionId%3DedU_LrAtIFsGvZj.Fgi0Si1bem68tBlk" context 'with a url with uppercase JPG extension', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'http://1.bp.blogspot.com/-1h8jX1lfGJc/UnlTZ3Fsq6I/AAAAAAAAAOo/dw7IXnJBO5A/s1600/IMG_1722.JPG' url = imgflo config, 'passthrough', params expect(url).to.contain 'passthrough.jpg' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/e48c2b3866af0e91fb4b1ef4d5399b7d/passthrough.jpg?input=http%3A%2F%2F1.bp.blogspot.com%2F-1h8jX1lfGJc%2FUnlTZ3Fsq6I%2FAAAAAAAAAOo%2Fdw7IXnJBO5A%2Fs1600%2FIMG_1722.JPG' context 'with a url without an extension', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://lh6.ggpht.com/qhLc1KUYP3YpNUtf9MujZVld1ctgsU0_oEEqp6Jkte8hW1UNJqKSm9-ExP-uzyL3r2c=h556' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/36d57f858d35674ca1626a1a57842b3e/gradientmap?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Flh6.ggpht.com%2FqhLc1KUYP3YpNUtf9MujZVld1ctgsU0_oEEqp6Jkte8hW1UNJqKSm9-ExP-uzyL3r2c%3Dh556&srgb=true' context 'specifying an image format', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params, 'png' expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/47d2fa8035119a3f038dc2be3756e10d/gradientmap.png?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge&srgb=true"
40025
{expect} = require 'chai' imgflo = require '../lib/imgflo-url' getConfig = -> server: 'https://imgflo.herokuapp.com/' key: 'key' secret: 'secret' describe 'imgflo-url', -> describe 'without a config object', -> it 'should throw an error', -> exercise = -> imgflo null, 'passthrough' expect(exercise).to.throw Error, 'imgflo config object not provided' describe 'with a config object', -> context 'without a server', -> it 'should throw an error', -> exercise = -> config = key: 'key' secret: 'secret' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "server" key' context 'without a key', -> it 'should throw an error', -> exercise = -> config = server: 'https://imgflo.herokuapp.com/' secret: 'secret' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "key" key' context 'without a secret', -> it 'should throw an error', -> exercise = -> config = server: 'https://imgflo.herokuapp.com/' key: 'key' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "secret" key' describe 'without imgflo params', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, 'passthrough' expect(exercise).to.throw Error, 'imgflo params not provided' describe 'with imgflo params', -> context 'without an input URL', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, 'passthrough', {} expect(exercise).to.throw Error, 'imgflo params must contain an "input" key' context 'with an input URL for a GIF image', -> it 'should return a proxying URL with noop graph', -> config = getConfig() url = imgflo config, 'passthrough', input: 'https://a.com/b.gif' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/408ff9579217fc27ec7472b8de5e8c3b/noop.gif?input=https%3A%2F%2Fa.com%2Fb.gif' context 'with an imgflo noop url', -> it 'should return double-encoded passthrough', -> config = getConfig() url = imgflo config, 'passthrough', input: 'https://imgflo.herokuapp.com/graph/vahj1ThiexotieMo/5764f83177c27abe632d7dce03e55e6d/noop.jpeg?input=https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1200%2F1*f7gpfegwe5jhpYs_1R_neA.jpeg' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/<KEY>/passthrough.jpeg?input=https%3A%2F%2Fimgflo.herokuapp.com%2Fgraph%2Fvahj1ThiexotieMo%2F5764f83177c27abe632d7dce03e55e6d%2Fnoop.jpeg%3Finput%3Dhttps%253A%252F%252Fcdn-images-1.medium.com%252Fmax%252F1200%252F1*f7gpfegwe5jhpYs_1R_neA.jpeg' context 'with an input data: URL', -> it 'should return the same URL', -> config = getConfig() url = imgflo config, 'passthrough', input: 'data:image/gif;base64,R0lGODlhDwAMAL...' expect(url).to.equal 'data:image/gif;base64,R0lGODlhDwAMAL...' context 'with an input blob: URL', -> it 'should return the same URL', -> config = getConfig() url = imgflo config, 'passthrough', input: 'blob:http://localhost/0000-0123' expect(url).to.equal 'blob:http://localhost/0000-0123' context 'with twitter image url issues', -> it '.jpg:large should return noop.jpg', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' url = imgflo config, 'noop', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/<KEY>/noop.jpg?input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge" it '.jpg%3Alarge should return noop.jpg', -> config = getConfig() params = input: 'https://imgflo.herokuapp.com/graph/2b2431f8e7ba7b0/dabcd2b47c33e25505fb1f5615586fb5/noop.jpg?input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FCocKWjJWEAAlPJI.jpg%3Alarge' url = imgflo config, 'noop', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/<KEY>/noop.jpg?input=https%3A%2F%2Fimgflo.herokuapp.com%2Fgraph%2F2b2431f8e7ba7b0%2Fdabcd2b47c33e25505fb1f5615586fb5%2Fnoop.jpg%3Finput%3Dhttps%253A%252F%252Fpbs.twimg.com%252Fmedia%252FCocKWjJWEAAlPJI.jpg%253Alarge" describe 'without a graph name', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, null, input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo graph name not provided' describe 'with imgflo params', -> context 'not specifying an image format', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/49467a1d8a94cf6c8350841299ecfb56/gradientmap.jpg?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge&srgb=true" context 'with a url with query parameters', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://v.cdn.vine.co/r/videos/B5B06468B91176403722801139712_342c9a1c624.1.5.15775156368984795444.mp4.jpg?versionId=edU_LrAtIFsGvZj.Fgi0Si1bem68tBlk' url = imgflo config, 'passthrough', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/0256dbdaea357ae9928<KEY>9c50d3d088a/passthrough.jpg?input=https%3A%2F%2Fv.cdn.vine.co%2Fr%2Fvideos%2FB5B06468B91176403722801139712_342c9a1c624.1.5.15775156368984795444.mp4.jpg%3FversionId%3DedU_LrAtIFsGvZj.Fgi0Si1bem68tBlk" context 'with a url with uppercase JPG extension', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'http://1.bp.blogspot.com/-1h8jX1lfGJc/UnlTZ3Fsq6I/AAAAAAAAAOo/dw7IXnJBO5A/s1600/IMG_1722.JPG' url = imgflo config, 'passthrough', params expect(url).to.contain 'passthrough.jpg' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/e48c2b3866af0e91fb4b1ef4d5399b7d/passthrough.jpg?input=http%3A%2F%2F1.bp.blogspot.com%2F-1h8jX1lfGJc%2FUnlTZ3Fsq6I%2FAAAAAAAAAOo%2Fdw7IXnJBO5A%2Fs1600%2FIMG_1722.JPG' context 'with a url without an extension', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://lh6.ggpht.com/qhLc1KUYP3YpNUtf9MujZVld1ctgsU0_oEEqp6Jkte8hW1UNJqKSm9-ExP-uzyL3r2c=h556' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/36d57f858d35674ca1626a1a57842b3e/gradientmap?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Flh6.ggpht.com%2FqhLc1KUYP3YpNUtf9MujZVld1ctgsU0_oEEqp6Jkte8hW1UNJqKSm9-ExP-uzyL3r2c%3Dh556&srgb=true' context 'specifying an image format', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params, 'png' expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/47d2fa8035119a3f038dc2be3756e10d/gradientmap.png?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge&srgb=true"
true
{expect} = require 'chai' imgflo = require '../lib/imgflo-url' getConfig = -> server: 'https://imgflo.herokuapp.com/' key: 'key' secret: 'secret' describe 'imgflo-url', -> describe 'without a config object', -> it 'should throw an error', -> exercise = -> imgflo null, 'passthrough' expect(exercise).to.throw Error, 'imgflo config object not provided' describe 'with a config object', -> context 'without a server', -> it 'should throw an error', -> exercise = -> config = key: 'key' secret: 'secret' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "server" key' context 'without a key', -> it 'should throw an error', -> exercise = -> config = server: 'https://imgflo.herokuapp.com/' secret: 'secret' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "key" key' context 'without a secret', -> it 'should throw an error', -> exercise = -> config = server: 'https://imgflo.herokuapp.com/' key: 'key' imgflo config, 'passthrough', input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo config must contain a "secret" key' describe 'without imgflo params', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, 'passthrough' expect(exercise).to.throw Error, 'imgflo params not provided' describe 'with imgflo params', -> context 'without an input URL', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, 'passthrough', {} expect(exercise).to.throw Error, 'imgflo params must contain an "input" key' context 'with an input URL for a GIF image', -> it 'should return a proxying URL with noop graph', -> config = getConfig() url = imgflo config, 'passthrough', input: 'https://a.com/b.gif' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/408ff9579217fc27ec7472b8de5e8c3b/noop.gif?input=https%3A%2F%2Fa.com%2Fb.gif' context 'with an imgflo noop url', -> it 'should return double-encoded passthrough', -> config = getConfig() url = imgflo config, 'passthrough', input: 'https://imgflo.herokuapp.com/graph/vahj1ThiexotieMo/5764f83177c27abe632d7dce03e55e6d/noop.jpeg?input=https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1200%2F1*f7gpfegwe5jhpYs_1R_neA.jpeg' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/PI:KEY:<KEY>END_PI/passthrough.jpeg?input=https%3A%2F%2Fimgflo.herokuapp.com%2Fgraph%2Fvahj1ThiexotieMo%2F5764f83177c27abe632d7dce03e55e6d%2Fnoop.jpeg%3Finput%3Dhttps%253A%252F%252Fcdn-images-1.medium.com%252Fmax%252F1200%252F1*f7gpfegwe5jhpYs_1R_neA.jpeg' context 'with an input data: URL', -> it 'should return the same URL', -> config = getConfig() url = imgflo config, 'passthrough', input: 'data:image/gif;base64,R0lGODlhDwAMAL...' expect(url).to.equal 'data:image/gif;base64,R0lGODlhDwAMAL...' context 'with an input blob: URL', -> it 'should return the same URL', -> config = getConfig() url = imgflo config, 'passthrough', input: 'blob:http://localhost/0000-0123' expect(url).to.equal 'blob:http://localhost/0000-0123' context 'with twitter image url issues', -> it '.jpg:large should return noop.jpg', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' url = imgflo config, 'noop', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/PI:KEY:<KEY>END_PI/noop.jpg?input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge" it '.jpg%3Alarge should return noop.jpg', -> config = getConfig() params = input: 'https://imgflo.herokuapp.com/graph/2b2431f8e7ba7b0/dabcd2b47c33e25505fb1f5615586fb5/noop.jpg?input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FCocKWjJWEAAlPJI.jpg%3Alarge' url = imgflo config, 'noop', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/PI:KEY:<KEY>END_PI/noop.jpg?input=https%3A%2F%2Fimgflo.herokuapp.com%2Fgraph%2F2b2431f8e7ba7b0%2Fdabcd2b47c33e25505fb1f5615586fb5%2Fnoop.jpg%3Finput%3Dhttps%253A%252F%252Fpbs.twimg.com%252Fmedia%252FCocKWjJWEAAlPJI.jpg%253Alarge" describe 'without a graph name', -> it 'should throw an error', -> exercise = -> config = getConfig() imgflo config, null, input: 'https://a.com/b.png' expect(exercise).to.throw Error, 'imgflo graph name not provided' describe 'with imgflo params', -> context 'not specifying an image format', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/49467a1d8a94cf6c8350841299ecfb56/gradientmap.jpg?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge&srgb=true" context 'with a url with query parameters', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://v.cdn.vine.co/r/videos/B5B06468B91176403722801139712_342c9a1c624.1.5.15775156368984795444.mp4.jpg?versionId=edU_LrAtIFsGvZj.Fgi0Si1bem68tBlk' url = imgflo config, 'passthrough', params expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/0256dbdaea357ae9928PI:KEY:<KEY>END_PI9c50d3d088a/passthrough.jpg?input=https%3A%2F%2Fv.cdn.vine.co%2Fr%2Fvideos%2FB5B06468B91176403722801139712_342c9a1c624.1.5.15775156368984795444.mp4.jpg%3FversionId%3DedU_LrAtIFsGvZj.Fgi0Si1bem68tBlk" context 'with a url with uppercase JPG extension', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'http://1.bp.blogspot.com/-1h8jX1lfGJc/UnlTZ3Fsq6I/AAAAAAAAAOo/dw7IXnJBO5A/s1600/IMG_1722.JPG' url = imgflo config, 'passthrough', params expect(url).to.contain 'passthrough.jpg' expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/e48c2b3866af0e91fb4b1ef4d5399b7d/passthrough.jpg?input=http%3A%2F%2F1.bp.blogspot.com%2F-1h8jX1lfGJc%2FUnlTZ3Fsq6I%2FAAAAAAAAAOo%2Fdw7IXnJBO5A%2Fs1600%2FIMG_1722.JPG' context 'with a url without an extension', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://lh6.ggpht.com/qhLc1KUYP3YpNUtf9MujZVld1ctgsU0_oEEqp6Jkte8hW1UNJqKSm9-ExP-uzyL3r2c=h556' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params expect(url).to.equal 'https://imgflo.herokuapp.com/graph/key/36d57f858d35674ca1626a1a57842b3e/gradientmap?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Flh6.ggpht.com%2FqhLc1KUYP3YpNUtf9MujZVld1ctgsU0_oEEqp6Jkte8hW1UNJqKSm9-ExP-uzyL3r2c%3Dh556&srgb=true' context 'specifying an image format', -> it 'should produce the correct URL', -> config = getConfig() params = input: 'https://pbs.twimg.com/media/BlM0d2-CcAAT9ic.jpg:large' color1: '#0A2A2F' color2: '#FDE7A0' srgb: true url = imgflo config, 'gradientmap', params, 'png' expect(url).to.equal "https://imgflo.herokuapp.com/graph/key/47d2fa8035119a3f038dc2be3756e10d/gradientmap.png?color1=%230A2A2F&color2=%23FDE7A0&input=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBlM0d2-CcAAT9ic.jpg%3Alarge&srgb=true"
[ { "context": ")\n model = new Backbone.Model({id: 'dog', name: 'Rover'})\n model_ref = new ModelRef(collection, 'dog')\n", "end": 3808, "score": 0.9980055093765259, "start": 3803, "tag": "NAME", "value": "Rover" }, { "context": "g', 'can get an id')\n\n equal(model.get('name'), 'R...
test/core/test.coffee
kmalakoff/backbone-modelref
2
module("Backbone-ModelRef.js") # import Underscore (or Lo-Dash with precedence), Backbone, and ModelRef _ = if not window._ and (typeof(require) != 'undefined') then require('underscore') else window._ _ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY Backbone = if not window.Backbone and(typeof(require) != 'undefined') then require('backbone') else window.Backbone ModelRef = if not Backbone.ModelRef and (typeof(require) != 'undefined') then require('backbone-modelref') else Backbone.ModelRef test("TEST DEPENDENCY MISSING", -> ok(!!_); ok(!!Backbone); ok(!!ModelRef) ) class MyModel extends Backbone.Model class MyCollection extends Backbone.Collection model: MyModel test("Standard use case: no events", -> collection = new MyCollection() model_ref = new ModelRef(collection, 'dog') equal(model_ref.isLoaded(), false, 'model_ref is not yet loaded') ok(!model_ref.getModel(), 'model_ref is not yet loaded') collection.add(collection.parse([{id: 'cat'}])) equal(model_ref.isLoaded(), false, 'model_ref is not yet loaded') ok(!model_ref.getModel(), 'model_ref is not yet loaded') collection.add(collection.parse([{id: 'dog'}])) equal(model_ref.isLoaded(), true, 'model_ref is loaded') equal(model_ref.getModel(), collection.get('dog'), 'model_ref is loaded') collection.remove(collection.get('dog')) equal(model_ref.isLoaded(), false, 'model_ref is no longer loaded') ok(!model_ref.getModel(), 'model_ref is no longer loaded') collection.add(collection.parse([{id: 'dog'}])) equal(model_ref.isLoaded(), true, 'model_ref is loaded again') equal(model_ref.getModel(), collection.get('dog'), 'model_ref is loaded again') collection.reset() equal(model_ref.isLoaded(), false, 'model_ref is no longer loaded') ok(!model_ref.getModel(), 'model_ref is no longer loaded') ) test("Standard use case: with events", -> test_model = null loaded_count = 0 loaded_fn = (model) -> loaded_count++; throw new Error('model mismatch') if model != test_model unloaded_fn = (model) -> loaded_count--; ; throw new Error('model mismatch') if model != test_model collection = new MyCollection() model_ref = new ModelRef(collection, 'dog') model_ref.bind('loaded', loaded_fn) model_ref.bind('unloaded', unloaded_fn) equal(loaded_count, 0, 'test model is not loaded') test_model = new MyModel({id: 'dog'}) equal(loaded_count, 0, 'test model is not loaded') collection.add(test_model) equal(loaded_count, 1, 'test model is loaded') collection.remove(test_model) equal(loaded_count, 0, 'test model is not loaded again') collection.add(test_model) equal(loaded_count, 1, 'test model is loaded again') collection.reset() equal(loaded_count, 0, 'test model is not loaded again, again') ) test("Standard use case in a view", -> class MyView constructor: (@model_ref) -> _.bindAll(this, 'render', 'renderWaiting') @model_ref.retain() @model_ref.bind('loaded', @render); @model_ref.bind('unloaded', @renderWaiting) if @model_ref.isLoaded() then @render() else @renderWaiting() render: -> @is_waiting = false renderWaiting: -> @is_waiting = true destroy: -> @model_ref.release(); @model_ref = null collection = new MyCollection() view = new MyView(new ModelRef(collection, 'dog')) equal(view.is_waiting, true, 'view is in waiting state') collection.add(collection.parse([{id: 'dog'}])) equal(view.is_waiting, false, 'view is in render state') model = collection.get('dog') collection.reset() equal(view.is_waiting, true, 'view is in waiting state again') collection.add(model) equal(view.is_waiting, false, 'view is in render state again') ) test("Emulated API signatures: simple case", -> collection = new MyCollection() model = new Backbone.Model({id: 'dog', name: 'Rover'}) model_ref = new ModelRef(collection, 'dog') ####################################### equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), 'Rover', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), null, 'model is not yet loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), false, 'model is not yet loaded') ####################################### collection.add(model) equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), 'Rover', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), model, 'model is now loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), true, 'model is now loaded') ####################################### collection.reset() equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), 'Rover', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), null, 'model is not yet loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), false, 'model is not yet loaded') ) test("Emulated API signatures: binding", -> create_counter_fn = (counter_attribute) -> return (model) -> model[counter_attribute] = 0 unless model.hasOwnProperty(counter_attribute) model[counter_attribute]++ collection = new MyCollection() model = new Backbone.Model({id: 'dog', name: 'Rover'}) model_ref = new ModelRef(collection, 'dog') ####################################### model.bindLoadingStates(create_counter_fn('model_loaded')) equal(model.model_loaded, 1, 'model is loaded so called immediately, but not bound so subsequent loads and unload will do nothing. You need a model ref for tracking those changes') ####################################### model.bindLoadingStates({loaded: create_counter_fn('model_loaded'), unloaded: create_counter_fn('model_unloaded')}) equal(model.model_loaded, 2, 'model is loaded so called immediately') equal(model.model_unloaded, undefined, 'model is loaded and unload will never be called') ####################################### model_ref.bindLoadingStates(create_counter_fn('model_ref_loaded')) equal(model_ref.model_ref_loaded, undefined, 'model is not loaded so not yet called') collection.add(model) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model.model_ref_loaded, 1, 'model is now loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model.model_ref_loaded, 1, 'model unload did nothing') ####################################### model_ref.bindLoadingStates({loaded: create_counter_fn('model_ref_loaded'), unloaded: create_counter_fn('model_ref_unloaded')}) equal(model.model_ref_loaded, 1, 'model still unloaded') equal(model.model_ref_unloaded, undefined, 'model unload not yet happened with the function') collection.add(model) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model.model_ref_loaded, 3, 'model is loaded again and both original and new binding called') equal(model.model_ref_unloaded, undefined, 'model unload not yet happened with the function') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model.model_ref_loaded, 3, 'model unload did nothing') equal(model.model_ref_unloaded, 1, 'model unload recorded') ####################################### model_ref2 = new ModelRef(collection, 'dog') collection.add(model) model_ref2.bindLoadingStates({loaded: create_counter_fn('model_ref2_loaded'), unloaded: create_counter_fn('model_ref2_unloaded')}) equal(model_ref2.isLoaded(), true, 'model ref is loaded') equal(model.model_ref2_loaded, 1, 'model was already laoded so callback was called') equal(model.model_ref2_unloaded, undefined, 'model unload not yet happened with the function') collection.reset() equal(model_ref2.isLoaded(), false, 'model ref not loaded') equal(model.model_ref2_loaded, 1, 'model unload did nothing') equal(model.model_ref2_unloaded, 1, 'model unload recorded') ) test("changing the model ref", -> create_counter_fn = (counter_attribute) -> return (model) -> model[counter_attribute] = 0 unless model.hasOwnProperty(counter_attribute) model[counter_attribute]++ collection = new MyCollection() model_dog = new Backbone.Model({id: 'dog', name: 'Rover'}) model_cat = new Backbone.Model({id: 'cat', name: 'Kitty'}) model_ref = new ModelRef(collection, 'dog') model_ref.bindLoadingStates({loaded: create_counter_fn('model_ref_loaded'), unloaded: create_counter_fn('model_ref_unloaded')}) model_ref2 = new ModelRef(collection, 'dog') ####################################### equal(model_ref.model_ref_loaded, undefined, 'model is not loaded so not yet called') collection.add(model_dog) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 1, 'model_dog is now loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model_dog.model_ref_loaded, 1, 'model_dog unload did nothing') equal(model_dog.model_ref_unloaded, 1, 'model_dog was unloaded') ####################################### collection.add([model_dog, model_cat]) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 2, 'model_dog is now loaded') ####################################### model_ref.model(model_cat) equal(model_dog.model_ref_unloaded, 2, 'model_dog was unloaded') equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_cat.model_ref_loaded, 1, 'model_cat was loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref is unloaded') equal(model_cat.model_ref_unloaded, 1, 'model_cat was loaded') ####################################### collection.add([model_dog, model_cat]) model_ref.model(model_ref2) equal(model_cat.model_ref_unloaded, 2, 'model_cat was unloaded') equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 3, 'model_dog was loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref is unloaded') equal(model_dog.model_ref_unloaded, 3, 'model_dog was loaded') ) test("Standard use case: expected errors", -> raises((->new ModelRef(null, 'dog')), Error, "ModelRef: collection is missing") model_ref = new ModelRef(new Backbone.Collection(), null, new Backbone.Model({id: 'hello'})) equal(model_ref.get('id'), 'hello', 'can get an id of a cached model') raises((->model_ref.get('foo')), Error, "ModelRef.get(): only id is permitted") model_ref.release() raises((->model_ref.release()), Error, "ModelRef.release(): ref count is corrupt") model_ref = new ModelRef(new Backbone.Collection(), 'hello') equal(model_ref.get('id'), 'hello', 'can get an id of a cached model') raises((->model_ref.get('foo')), Error, "ModelRef.get(): only id is permitted") )
76380
module("Backbone-ModelRef.js") # import Underscore (or Lo-Dash with precedence), Backbone, and ModelRef _ = if not window._ and (typeof(require) != 'undefined') then require('underscore') else window._ _ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY Backbone = if not window.Backbone and(typeof(require) != 'undefined') then require('backbone') else window.Backbone ModelRef = if not Backbone.ModelRef and (typeof(require) != 'undefined') then require('backbone-modelref') else Backbone.ModelRef test("TEST DEPENDENCY MISSING", -> ok(!!_); ok(!!Backbone); ok(!!ModelRef) ) class MyModel extends Backbone.Model class MyCollection extends Backbone.Collection model: MyModel test("Standard use case: no events", -> collection = new MyCollection() model_ref = new ModelRef(collection, 'dog') equal(model_ref.isLoaded(), false, 'model_ref is not yet loaded') ok(!model_ref.getModel(), 'model_ref is not yet loaded') collection.add(collection.parse([{id: 'cat'}])) equal(model_ref.isLoaded(), false, 'model_ref is not yet loaded') ok(!model_ref.getModel(), 'model_ref is not yet loaded') collection.add(collection.parse([{id: 'dog'}])) equal(model_ref.isLoaded(), true, 'model_ref is loaded') equal(model_ref.getModel(), collection.get('dog'), 'model_ref is loaded') collection.remove(collection.get('dog')) equal(model_ref.isLoaded(), false, 'model_ref is no longer loaded') ok(!model_ref.getModel(), 'model_ref is no longer loaded') collection.add(collection.parse([{id: 'dog'}])) equal(model_ref.isLoaded(), true, 'model_ref is loaded again') equal(model_ref.getModel(), collection.get('dog'), 'model_ref is loaded again') collection.reset() equal(model_ref.isLoaded(), false, 'model_ref is no longer loaded') ok(!model_ref.getModel(), 'model_ref is no longer loaded') ) test("Standard use case: with events", -> test_model = null loaded_count = 0 loaded_fn = (model) -> loaded_count++; throw new Error('model mismatch') if model != test_model unloaded_fn = (model) -> loaded_count--; ; throw new Error('model mismatch') if model != test_model collection = new MyCollection() model_ref = new ModelRef(collection, 'dog') model_ref.bind('loaded', loaded_fn) model_ref.bind('unloaded', unloaded_fn) equal(loaded_count, 0, 'test model is not loaded') test_model = new MyModel({id: 'dog'}) equal(loaded_count, 0, 'test model is not loaded') collection.add(test_model) equal(loaded_count, 1, 'test model is loaded') collection.remove(test_model) equal(loaded_count, 0, 'test model is not loaded again') collection.add(test_model) equal(loaded_count, 1, 'test model is loaded again') collection.reset() equal(loaded_count, 0, 'test model is not loaded again, again') ) test("Standard use case in a view", -> class MyView constructor: (@model_ref) -> _.bindAll(this, 'render', 'renderWaiting') @model_ref.retain() @model_ref.bind('loaded', @render); @model_ref.bind('unloaded', @renderWaiting) if @model_ref.isLoaded() then @render() else @renderWaiting() render: -> @is_waiting = false renderWaiting: -> @is_waiting = true destroy: -> @model_ref.release(); @model_ref = null collection = new MyCollection() view = new MyView(new ModelRef(collection, 'dog')) equal(view.is_waiting, true, 'view is in waiting state') collection.add(collection.parse([{id: 'dog'}])) equal(view.is_waiting, false, 'view is in render state') model = collection.get('dog') collection.reset() equal(view.is_waiting, true, 'view is in waiting state again') collection.add(model) equal(view.is_waiting, false, 'view is in render state again') ) test("Emulated API signatures: simple case", -> collection = new MyCollection() model = new Backbone.Model({id: 'dog', name: '<NAME>'}) model_ref = new ModelRef(collection, 'dog') ####################################### equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), '<NAME>', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), null, 'model is not yet loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), false, 'model is not yet loaded') ####################################### collection.add(model) equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), '<NAME>', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), model, 'model is now loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), true, 'model is now loaded') ####################################### collection.reset() equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), '<NAME>', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), null, 'model is not yet loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), false, 'model is not yet loaded') ) test("Emulated API signatures: binding", -> create_counter_fn = (counter_attribute) -> return (model) -> model[counter_attribute] = 0 unless model.hasOwnProperty(counter_attribute) model[counter_attribute]++ collection = new MyCollection() model = new Backbone.Model({id: 'dog', name: '<NAME>'}) model_ref = new ModelRef(collection, 'dog') ####################################### model.bindLoadingStates(create_counter_fn('model_loaded')) equal(model.model_loaded, 1, 'model is loaded so called immediately, but not bound so subsequent loads and unload will do nothing. You need a model ref for tracking those changes') ####################################### model.bindLoadingStates({loaded: create_counter_fn('model_loaded'), unloaded: create_counter_fn('model_unloaded')}) equal(model.model_loaded, 2, 'model is loaded so called immediately') equal(model.model_unloaded, undefined, 'model is loaded and unload will never be called') ####################################### model_ref.bindLoadingStates(create_counter_fn('model_ref_loaded')) equal(model_ref.model_ref_loaded, undefined, 'model is not loaded so not yet called') collection.add(model) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model.model_ref_loaded, 1, 'model is now loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model.model_ref_loaded, 1, 'model unload did nothing') ####################################### model_ref.bindLoadingStates({loaded: create_counter_fn('model_ref_loaded'), unloaded: create_counter_fn('model_ref_unloaded')}) equal(model.model_ref_loaded, 1, 'model still unloaded') equal(model.model_ref_unloaded, undefined, 'model unload not yet happened with the function') collection.add(model) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model.model_ref_loaded, 3, 'model is loaded again and both original and new binding called') equal(model.model_ref_unloaded, undefined, 'model unload not yet happened with the function') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model.model_ref_loaded, 3, 'model unload did nothing') equal(model.model_ref_unloaded, 1, 'model unload recorded') ####################################### model_ref2 = new ModelRef(collection, 'dog') collection.add(model) model_ref2.bindLoadingStates({loaded: create_counter_fn('model_ref2_loaded'), unloaded: create_counter_fn('model_ref2_unloaded')}) equal(model_ref2.isLoaded(), true, 'model ref is loaded') equal(model.model_ref2_loaded, 1, 'model was already laoded so callback was called') equal(model.model_ref2_unloaded, undefined, 'model unload not yet happened with the function') collection.reset() equal(model_ref2.isLoaded(), false, 'model ref not loaded') equal(model.model_ref2_loaded, 1, 'model unload did nothing') equal(model.model_ref2_unloaded, 1, 'model unload recorded') ) test("changing the model ref", -> create_counter_fn = (counter_attribute) -> return (model) -> model[counter_attribute] = 0 unless model.hasOwnProperty(counter_attribute) model[counter_attribute]++ collection = new MyCollection() model_dog = new Backbone.Model({id: 'dog', name: 'Rover'}) model_cat = new Backbone.Model({id: 'cat', name: 'Kitty'}) model_ref = new ModelRef(collection, 'dog') model_ref.bindLoadingStates({loaded: create_counter_fn('model_ref_loaded'), unloaded: create_counter_fn('model_ref_unloaded')}) model_ref2 = new ModelRef(collection, 'dog') ####################################### equal(model_ref.model_ref_loaded, undefined, 'model is not loaded so not yet called') collection.add(model_dog) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 1, 'model_dog is now loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model_dog.model_ref_loaded, 1, 'model_dog unload did nothing') equal(model_dog.model_ref_unloaded, 1, 'model_dog was unloaded') ####################################### collection.add([model_dog, model_cat]) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 2, 'model_dog is now loaded') ####################################### model_ref.model(model_cat) equal(model_dog.model_ref_unloaded, 2, 'model_dog was unloaded') equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_cat.model_ref_loaded, 1, 'model_cat was loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref is unloaded') equal(model_cat.model_ref_unloaded, 1, 'model_cat was loaded') ####################################### collection.add([model_dog, model_cat]) model_ref.model(model_ref2) equal(model_cat.model_ref_unloaded, 2, 'model_cat was unloaded') equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 3, 'model_dog was loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref is unloaded') equal(model_dog.model_ref_unloaded, 3, 'model_dog was loaded') ) test("Standard use case: expected errors", -> raises((->new ModelRef(null, 'dog')), Error, "ModelRef: collection is missing") model_ref = new ModelRef(new Backbone.Collection(), null, new Backbone.Model({id: 'hello'})) equal(model_ref.get('id'), 'hello', 'can get an id of a cached model') raises((->model_ref.get('foo')), Error, "ModelRef.get(): only id is permitted") model_ref.release() raises((->model_ref.release()), Error, "ModelRef.release(): ref count is corrupt") model_ref = new ModelRef(new Backbone.Collection(), 'hello') equal(model_ref.get('id'), 'hello', 'can get an id of a cached model') raises((->model_ref.get('foo')), Error, "ModelRef.get(): only id is permitted") )
true
module("Backbone-ModelRef.js") # import Underscore (or Lo-Dash with precedence), Backbone, and ModelRef _ = if not window._ and (typeof(require) != 'undefined') then require('underscore') else window._ _ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY Backbone = if not window.Backbone and(typeof(require) != 'undefined') then require('backbone') else window.Backbone ModelRef = if not Backbone.ModelRef and (typeof(require) != 'undefined') then require('backbone-modelref') else Backbone.ModelRef test("TEST DEPENDENCY MISSING", -> ok(!!_); ok(!!Backbone); ok(!!ModelRef) ) class MyModel extends Backbone.Model class MyCollection extends Backbone.Collection model: MyModel test("Standard use case: no events", -> collection = new MyCollection() model_ref = new ModelRef(collection, 'dog') equal(model_ref.isLoaded(), false, 'model_ref is not yet loaded') ok(!model_ref.getModel(), 'model_ref is not yet loaded') collection.add(collection.parse([{id: 'cat'}])) equal(model_ref.isLoaded(), false, 'model_ref is not yet loaded') ok(!model_ref.getModel(), 'model_ref is not yet loaded') collection.add(collection.parse([{id: 'dog'}])) equal(model_ref.isLoaded(), true, 'model_ref is loaded') equal(model_ref.getModel(), collection.get('dog'), 'model_ref is loaded') collection.remove(collection.get('dog')) equal(model_ref.isLoaded(), false, 'model_ref is no longer loaded') ok(!model_ref.getModel(), 'model_ref is no longer loaded') collection.add(collection.parse([{id: 'dog'}])) equal(model_ref.isLoaded(), true, 'model_ref is loaded again') equal(model_ref.getModel(), collection.get('dog'), 'model_ref is loaded again') collection.reset() equal(model_ref.isLoaded(), false, 'model_ref is no longer loaded') ok(!model_ref.getModel(), 'model_ref is no longer loaded') ) test("Standard use case: with events", -> test_model = null loaded_count = 0 loaded_fn = (model) -> loaded_count++; throw new Error('model mismatch') if model != test_model unloaded_fn = (model) -> loaded_count--; ; throw new Error('model mismatch') if model != test_model collection = new MyCollection() model_ref = new ModelRef(collection, 'dog') model_ref.bind('loaded', loaded_fn) model_ref.bind('unloaded', unloaded_fn) equal(loaded_count, 0, 'test model is not loaded') test_model = new MyModel({id: 'dog'}) equal(loaded_count, 0, 'test model is not loaded') collection.add(test_model) equal(loaded_count, 1, 'test model is loaded') collection.remove(test_model) equal(loaded_count, 0, 'test model is not loaded again') collection.add(test_model) equal(loaded_count, 1, 'test model is loaded again') collection.reset() equal(loaded_count, 0, 'test model is not loaded again, again') ) test("Standard use case in a view", -> class MyView constructor: (@model_ref) -> _.bindAll(this, 'render', 'renderWaiting') @model_ref.retain() @model_ref.bind('loaded', @render); @model_ref.bind('unloaded', @renderWaiting) if @model_ref.isLoaded() then @render() else @renderWaiting() render: -> @is_waiting = false renderWaiting: -> @is_waiting = true destroy: -> @model_ref.release(); @model_ref = null collection = new MyCollection() view = new MyView(new ModelRef(collection, 'dog')) equal(view.is_waiting, true, 'view is in waiting state') collection.add(collection.parse([{id: 'dog'}])) equal(view.is_waiting, false, 'view is in render state') model = collection.get('dog') collection.reset() equal(view.is_waiting, true, 'view is in waiting state again') collection.add(model) equal(view.is_waiting, false, 'view is in render state again') ) test("Emulated API signatures: simple case", -> collection = new MyCollection() model = new Backbone.Model({id: 'dog', name: 'PI:NAME:<NAME>END_PI'}) model_ref = new ModelRef(collection, 'dog') ####################################### equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), 'PI:NAME:<NAME>END_PI', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), null, 'model is not yet loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), false, 'model is not yet loaded') ####################################### collection.add(model) equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), 'PI:NAME:<NAME>END_PI', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), model, 'model is now loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), true, 'model is now loaded') ####################################### collection.reset() equal(model.get('id'), 'dog', 'can get an id') equal(model_ref.get('id'), 'dog', 'can get an id') equal(model.get('name'), 'PI:NAME:<NAME>END_PI', 'can get an attribute') raises((->model_ref.get('name')), Error, "ModelRef.get(): only id is permitted") equal(model.model(), model, 'can get self') equal(model_ref.model(), null, 'model is not yet loaded') equal(model.isLoaded(), true, 'model is always loaded') equal(model_ref.isLoaded(), false, 'model is not yet loaded') ) test("Emulated API signatures: binding", -> create_counter_fn = (counter_attribute) -> return (model) -> model[counter_attribute] = 0 unless model.hasOwnProperty(counter_attribute) model[counter_attribute]++ collection = new MyCollection() model = new Backbone.Model({id: 'dog', name: 'PI:NAME:<NAME>END_PI'}) model_ref = new ModelRef(collection, 'dog') ####################################### model.bindLoadingStates(create_counter_fn('model_loaded')) equal(model.model_loaded, 1, 'model is loaded so called immediately, but not bound so subsequent loads and unload will do nothing. You need a model ref for tracking those changes') ####################################### model.bindLoadingStates({loaded: create_counter_fn('model_loaded'), unloaded: create_counter_fn('model_unloaded')}) equal(model.model_loaded, 2, 'model is loaded so called immediately') equal(model.model_unloaded, undefined, 'model is loaded and unload will never be called') ####################################### model_ref.bindLoadingStates(create_counter_fn('model_ref_loaded')) equal(model_ref.model_ref_loaded, undefined, 'model is not loaded so not yet called') collection.add(model) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model.model_ref_loaded, 1, 'model is now loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model.model_ref_loaded, 1, 'model unload did nothing') ####################################### model_ref.bindLoadingStates({loaded: create_counter_fn('model_ref_loaded'), unloaded: create_counter_fn('model_ref_unloaded')}) equal(model.model_ref_loaded, 1, 'model still unloaded') equal(model.model_ref_unloaded, undefined, 'model unload not yet happened with the function') collection.add(model) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model.model_ref_loaded, 3, 'model is loaded again and both original and new binding called') equal(model.model_ref_unloaded, undefined, 'model unload not yet happened with the function') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model.model_ref_loaded, 3, 'model unload did nothing') equal(model.model_ref_unloaded, 1, 'model unload recorded') ####################################### model_ref2 = new ModelRef(collection, 'dog') collection.add(model) model_ref2.bindLoadingStates({loaded: create_counter_fn('model_ref2_loaded'), unloaded: create_counter_fn('model_ref2_unloaded')}) equal(model_ref2.isLoaded(), true, 'model ref is loaded') equal(model.model_ref2_loaded, 1, 'model was already laoded so callback was called') equal(model.model_ref2_unloaded, undefined, 'model unload not yet happened with the function') collection.reset() equal(model_ref2.isLoaded(), false, 'model ref not loaded') equal(model.model_ref2_loaded, 1, 'model unload did nothing') equal(model.model_ref2_unloaded, 1, 'model unload recorded') ) test("changing the model ref", -> create_counter_fn = (counter_attribute) -> return (model) -> model[counter_attribute] = 0 unless model.hasOwnProperty(counter_attribute) model[counter_attribute]++ collection = new MyCollection() model_dog = new Backbone.Model({id: 'dog', name: 'Rover'}) model_cat = new Backbone.Model({id: 'cat', name: 'Kitty'}) model_ref = new ModelRef(collection, 'dog') model_ref.bindLoadingStates({loaded: create_counter_fn('model_ref_loaded'), unloaded: create_counter_fn('model_ref_unloaded')}) model_ref2 = new ModelRef(collection, 'dog') ####################################### equal(model_ref.model_ref_loaded, undefined, 'model is not loaded so not yet called') collection.add(model_dog) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 1, 'model_dog is now loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref not loaded') equal(model_dog.model_ref_loaded, 1, 'model_dog unload did nothing') equal(model_dog.model_ref_unloaded, 1, 'model_dog was unloaded') ####################################### collection.add([model_dog, model_cat]) equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 2, 'model_dog is now loaded') ####################################### model_ref.model(model_cat) equal(model_dog.model_ref_unloaded, 2, 'model_dog was unloaded') equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_cat.model_ref_loaded, 1, 'model_cat was loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref is unloaded') equal(model_cat.model_ref_unloaded, 1, 'model_cat was loaded') ####################################### collection.add([model_dog, model_cat]) model_ref.model(model_ref2) equal(model_cat.model_ref_unloaded, 2, 'model_cat was unloaded') equal(model_ref.isLoaded(), true, 'model ref is loaded') equal(model_dog.model_ref_loaded, 3, 'model_dog was loaded') collection.reset() equal(model_ref.isLoaded(), false, 'model ref is unloaded') equal(model_dog.model_ref_unloaded, 3, 'model_dog was loaded') ) test("Standard use case: expected errors", -> raises((->new ModelRef(null, 'dog')), Error, "ModelRef: collection is missing") model_ref = new ModelRef(new Backbone.Collection(), null, new Backbone.Model({id: 'hello'})) equal(model_ref.get('id'), 'hello', 'can get an id of a cached model') raises((->model_ref.get('foo')), Error, "ModelRef.get(): only id is permitted") model_ref.release() raises((->model_ref.release()), Error, "ModelRef.release(): ref count is corrupt") model_ref = new ModelRef(new Backbone.Collection(), 'hello') equal(model_ref.get('id'), 'hello', 'can get an id of a cached model') raises((->model_ref.get('foo')), Error, "ModelRef.get(): only id is permitted") )
[ { "context": "eruvian.org'\n\t\t\tscope: 'read write'\n\t\t\tclientId: '97d0753a-98b6-47e1-9968-896922c578e1',\n\t\t\tredirectUri: 'http://localhost:9000'\n\nclass ", "end": 216, "score": 0.9948058724403381, "start": 180, "tag": "KEY", "value": "97d0753a-98b6-47e1-9968-896922c578e1" } ]
app/config/config.dev.coffee
dianw/yama-admin
0
'use strict' class OauthConfig extends Config constructor: (oauthProvider) -> oauthProvider.configure site: 'http://yama2.meruvian.org' scope: 'read write' clientId: '97d0753a-98b6-47e1-9968-896922c578e1', redirectUri: 'http://localhost:9000' class RestConfig extends Config constructor: (RestangularProvider) -> RestangularProvider.setBaseUrl '/api'
105081
'use strict' class OauthConfig extends Config constructor: (oauthProvider) -> oauthProvider.configure site: 'http://yama2.meruvian.org' scope: 'read write' clientId: '<KEY>', redirectUri: 'http://localhost:9000' class RestConfig extends Config constructor: (RestangularProvider) -> RestangularProvider.setBaseUrl '/api'
true
'use strict' class OauthConfig extends Config constructor: (oauthProvider) -> oauthProvider.configure site: 'http://yama2.meruvian.org' scope: 'read write' clientId: 'PI:KEY:<KEY>END_PI', redirectUri: 'http://localhost:9000' class RestConfig extends Config constructor: (RestangularProvider) -> RestangularProvider.setBaseUrl '/api'
[ { "context": "s specific dom-wrapper\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nclass Form extends Element\n\n #\n # Basic const", "end": 80, "score": 0.9998874664306641, "start": 63, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/dom/src/form.coffee
lovely-io/lovely.io-stl
2
# # The forms specific dom-wrapper # # Copyright (C) 2011-2012 Nikolay Nemshilov # class Form extends Element # # Basic constructor # # :js # new Form(raw_dom_form) # new Form(method: 'post', action: '/some.url') # # @param {HTMLFormElement|Object} raw dom-form or a set of options # @param {Object} options # @return {Form} this # constructor: (element, options) -> if !element or (!isElement(element) and isObject(element)) options = element || {} element = 'form' remote = 'remote' of options delete(options.remote) super(element, options) @remotize() if remote and @remotize return @ # making the methods with NodeList shortcuts Form.include = Element.include Form.include # # Returns the form elements as an array of extended units # # @return {NodeList} list of elements # elements: -> @find('input,button,select,textarea') # # Returns the list of all the input elements on the form # # @return {NodeList} list of elements # inputs: -> @elements().filter (input)-> !(input._.type in ['submit', 'button', 'reset', 'image', null]) # # Accessing an input by name # # @param {String} name # @return {Input} field # input: (name)-> inputs = @find "*[name=\"#{name}\"]" if inputs.length isnt 0 && inputs[0]._.type is 'radio' inputs else inputs[0] # # Focuses on the first input element on the form (if any) # # @return {Form} this # focus: -> for element in @inputs() element.focus(); break; return @ # # Removes focus out of all the form elements # # @return {Form} this # blur: -> @elements().forEach('blur') return @ # # disables all the elements on the form # # @return {Form} this # disable: -> @elements().forEach('disable') return @ # # enables all the elements on the form # # @return {Form} this # enable: -> @elements().forEach('enable') return @ # # returns the list of the form values # # @return {Object} values # values: -> values = {} @inputs().forEach (element)-> input = element._ name = input.name hash = values keys = name.match(/[^\[]+/g) if !input.disabled and name and (!(input.type in ['checkbox', 'radio']) || input.checked) # getting throught the smth[smth][smth][] in the name while keys.length > 1 key = keys.shift() key = key.substr(0, key.length-1) if key[key.length-1] is ']' hash = (hash[key] or= (if keys[0] is ']' then [] else {})) key = keys.shift() key = key.substr(0, key.length-1) if key[key.length-1] is ']' if key is '' # an array hash.push(element.value()) else hash[key] = element.value() return # nothing return values # # Delegating the submit method # # @return {Form} this # submit: -> @_.submit() return @ # # Delegating the 'reset' method # # @return {Form} this # reset: -> @_.reset() return @
122836
# # The forms specific dom-wrapper # # Copyright (C) 2011-2012 <NAME> # class Form extends Element # # Basic constructor # # :js # new Form(raw_dom_form) # new Form(method: 'post', action: '/some.url') # # @param {HTMLFormElement|Object} raw dom-form or a set of options # @param {Object} options # @return {Form} this # constructor: (element, options) -> if !element or (!isElement(element) and isObject(element)) options = element || {} element = 'form' remote = 'remote' of options delete(options.remote) super(element, options) @remotize() if remote and @remotize return @ # making the methods with NodeList shortcuts Form.include = Element.include Form.include # # Returns the form elements as an array of extended units # # @return {NodeList} list of elements # elements: -> @find('input,button,select,textarea') # # Returns the list of all the input elements on the form # # @return {NodeList} list of elements # inputs: -> @elements().filter (input)-> !(input._.type in ['submit', 'button', 'reset', 'image', null]) # # Accessing an input by name # # @param {String} name # @return {Input} field # input: (name)-> inputs = @find "*[name=\"#{name}\"]" if inputs.length isnt 0 && inputs[0]._.type is 'radio' inputs else inputs[0] # # Focuses on the first input element on the form (if any) # # @return {Form} this # focus: -> for element in @inputs() element.focus(); break; return @ # # Removes focus out of all the form elements # # @return {Form} this # blur: -> @elements().forEach('blur') return @ # # disables all the elements on the form # # @return {Form} this # disable: -> @elements().forEach('disable') return @ # # enables all the elements on the form # # @return {Form} this # enable: -> @elements().forEach('enable') return @ # # returns the list of the form values # # @return {Object} values # values: -> values = {} @inputs().forEach (element)-> input = element._ name = input.name hash = values keys = name.match(/[^\[]+/g) if !input.disabled and name and (!(input.type in ['checkbox', 'radio']) || input.checked) # getting throught the smth[smth][smth][] in the name while keys.length > 1 key = keys.shift() key = key.substr(0, key.length-1) if key[key.length-1] is ']' hash = (hash[key] or= (if keys[0] is ']' then [] else {})) key = keys.shift() key = key.substr(0, key.length-1) if key[key.length-1] is ']' if key is '' # an array hash.push(element.value()) else hash[key] = element.value() return # nothing return values # # Delegating the submit method # # @return {Form} this # submit: -> @_.submit() return @ # # Delegating the 'reset' method # # @return {Form} this # reset: -> @_.reset() return @
true
# # The forms specific dom-wrapper # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # class Form extends Element # # Basic constructor # # :js # new Form(raw_dom_form) # new Form(method: 'post', action: '/some.url') # # @param {HTMLFormElement|Object} raw dom-form or a set of options # @param {Object} options # @return {Form} this # constructor: (element, options) -> if !element or (!isElement(element) and isObject(element)) options = element || {} element = 'form' remote = 'remote' of options delete(options.remote) super(element, options) @remotize() if remote and @remotize return @ # making the methods with NodeList shortcuts Form.include = Element.include Form.include # # Returns the form elements as an array of extended units # # @return {NodeList} list of elements # elements: -> @find('input,button,select,textarea') # # Returns the list of all the input elements on the form # # @return {NodeList} list of elements # inputs: -> @elements().filter (input)-> !(input._.type in ['submit', 'button', 'reset', 'image', null]) # # Accessing an input by name # # @param {String} name # @return {Input} field # input: (name)-> inputs = @find "*[name=\"#{name}\"]" if inputs.length isnt 0 && inputs[0]._.type is 'radio' inputs else inputs[0] # # Focuses on the first input element on the form (if any) # # @return {Form} this # focus: -> for element in @inputs() element.focus(); break; return @ # # Removes focus out of all the form elements # # @return {Form} this # blur: -> @elements().forEach('blur') return @ # # disables all the elements on the form # # @return {Form} this # disable: -> @elements().forEach('disable') return @ # # enables all the elements on the form # # @return {Form} this # enable: -> @elements().forEach('enable') return @ # # returns the list of the form values # # @return {Object} values # values: -> values = {} @inputs().forEach (element)-> input = element._ name = input.name hash = values keys = name.match(/[^\[]+/g) if !input.disabled and name and (!(input.type in ['checkbox', 'radio']) || input.checked) # getting throught the smth[smth][smth][] in the name while keys.length > 1 key = keys.shift() key = key.substr(0, key.length-1) if key[key.length-1] is ']' hash = (hash[key] or= (if keys[0] is ']' then [] else {})) key = keys.shift() key = key.substr(0, key.length-1) if key[key.length-1] is ']' if key is '' # an array hash.push(element.value()) else hash[key] = element.value() return # nothing return values # # Delegating the submit method # # @return {Form} this # submit: -> @_.submit() return @ # # Delegating the 'reset' method # # @return {Form} this # reset: -> @_.reset() return @
[ { "context": "#Textile Editor v0.2\n#created by: dave olsen, wvu web services\n#created on: march 17, 2007\n#pr", "end": 44, "score": 0.9998793601989746, "start": 34, "tag": "NAME", "value": "dave olsen" }, { "context": " page: slateinfo.blogs.wvu.edu\n#\n#inspired by:\n# - Patrick W...
app/assets/javascripts/textile-editor.js.coffee
Jorgelig/hoshinplan
12
#Textile Editor v0.2 #created by: dave olsen, wvu web services #created on: march 17, 2007 #project page: slateinfo.blogs.wvu.edu # #inspired by: # - Patrick Woods, http://www.hakjoon.com/code/38/textile-quicktags-redirect & # - Alex King, http://alexking.org/projects/js-quicktags # #features: # - supports: IE7, FF2, Safari2 # - ability to use "simple" vs. "extended" editor # - supports all block elements in textile except footnote # - supports all block modifier elements in textile # - supports simple ordered and unordered lists # - supports most of the phrase modifiers, very easy to add the missing ones # - supports multiple-paragraph modification # - can have multiple "editors" on one page, access key use in this environment is flaky # - access key support # - select text to add and remove tags, selection stays highlighted # - seamlessly change between tags and modifiers # - doesn't need to be in the body onload tag # - can supply your own, custom IDs for the editor to be drawn around # # TODO: # - a clean way of providing image and link inserts # - get the selection to properly show in IE # #more on textile: # - Textism, http://www.textism.com/tools/textile/index.php # - Textile Reference, http://hobix.com/textile/ class TextileEditorButton constructor: (id, display, tagStart, tagEnd, access, title, sve, open) -> @id = id # used to name the toolbar button @display = display # label on button @tagStart = tagStart # open tag @tagEnd = tagEnd # close tag @access = access # set to -1 if tag does not need to be closed @title = title # sets the title attribute of the button to give 'tool tips' @sve = sve # sve = simple vs. extended. add an 's' to make it show up in the simple toolbar @open = open # set to -1 if tag does not need to be closed @standard = true # this is a standard button window.TextileEditorButton = TextileEditorButton class TextileEditorButtonSeparator constructor: (sve) -> @separator = true @sve = sve window.TextileEditorButtonSeparator = TextileEditorButtonSeparator class TextileEditor @setButtons: (buttons) -> TextileEditor.buttons = buttons @addButton: (button) -> @getButtons().push(button) @getButtons: () -> TextileEditor.buttons || new Array() constructor: (canvas, view) -> toolbar = document.createElement("div") toolbar.id = "textile-toolbar-" + canvas toolbar.className = "textile-toolbar" @canvas = document.getElementById(canvas) @canvas.parentNode.insertBefore(toolbar, @canvas) @openTags = new Array() # Create the local Button array by assigning theButtons array to edButtons edButtons = TextileEditor.getButtons() standardButtons = new Array() i = 0 while i < edButtons.length thisButton = @prepareButton(edButtons[i]) if view is "simple" if edButtons[i].sve is "s" toolbar.appendChild thisButton standardButtons.push thisButton else if typeof thisButton is "string" toolbar.innerHTML += thisButton else toolbar.appendChild thisButton standardButtons.push thisButton i++ te = this buttons = toolbar.getElementsByTagName("button") i = 0 while i < buttons.length unless buttons[i].onclick buttons[i].onclick = -> te.insertTag this return false buttons[i].tagStart = buttons[i].getAttribute("tagStart") buttons[i].tagEnd = buttons[i].getAttribute("tagEnd") buttons[i].open = buttons[i].getAttribute("open") buttons[i].textile_editor = te buttons[i].canvas = te.canvas i++ # draw individual buttons (edShowButton) prepareButton: (button) -> if button.separator theButton = document.createElement("span") theButton.className = "ed_sep" return theButton if button.standard theButton = document.createElement("button") theButton.id = button.id theButton.setAttribute("class", "standard") theButton.setAttribute("tagStart", button.tagStart) theButton.setAttribute("tagEnd", button.tagEnd) theButton.setAttribute("open", button.open) img = document.createElement("img") img.src = button.display theButton.appendChild(img) else return button theButton.accessKey = button.access theButton.title = button.title return theButton # if clicked, no selected text, tag not open highlight button # (edAddTag) addTag: (button) -> unless button.tagEnd is "" @openTags[@openTags.length] = button button.className = "selected" return button # if clicked, no selected text, tag open lowlight button # (edRemoveTag) removeTag: (button) -> i = 0 while i < @openTags.length if @openTags[i] is button @openTags.splice(button, 1) #var el = document.getElementById(button.id); #el.className = 'unselected'; button.className = "unselected" i++ return undefined # see if there are open tags. for the remove tag bit... # (edCheckOpenTags) checkOpenTags: (button) -> tag = 0 i = 0 while i < @openTags.length tag++ if @openTags[i] is button i++ return (tag > 0) # tag found / not found # insert the tag. this is the bulk of the code. # (edInsertTag) insertTag: (button, tagStart, tagEnd) -> myField = button.canvas if tagStart button.tagStart = tagStart button.tagEnd = (if tagEnd then tagEnd else "\n") textSelected = false finalText = "" FF = false # grab the text that's going to be manipulated, by browser if document.selection # IE support myField.focus() sel = document.selection.createRange() # set-up the text vars beginningText = "" followupText = "" selectedText = sel.text # check if text has been selected textSelected = true if sel.text.length > 0 # set-up newline regex's so we can swap tags across multiple paragraphs newlineReplaceRegexClean = /\r\n\s\n/g newlineReplaceRegexDirty = "\\r\\n\\s\\n" newlineReplaceClean = "\r\n\n" else if myField.selectionStart or myField.selectionStart == 0 or myField.selectionStart == '0' # MOZ/FF/NS/S support # figure out cursor and selection positions startPos = myField.selectionStart endPos = myField.selectionEnd cursorPos = endPos scrollTop = myField.scrollTop FF = true # note that is is a FF/MOZ/NS/S browser # set-up the text vars beginningText = myField.value.substring(0, startPos) followupText = myField.value.substring(endPos, myField.value.length) # check if text has been selected unless startPos is endPos textSelected = true selectedText = myField.value.substring(startPos, endPos) # set-up newline regex's so we can swap tags across multiple paragraphs newlineReplaceRegexClean = /\n\n/g newlineReplaceRegexDirty = "\\n\\n" newlineReplaceClean = "\n\n" # if there is text that has been highlighted... if textSelected # set-up some defaults for how to handle bad new line characters newlineStart = "" newlineStartPos = 0 newlineEnd = "" newlineEndPos = 0 newlineFollowup = "" # set-up some defaults for how to handle placing the beginning and end of selection posDiffPos = 0 posDiffNeg = 0 mplier = 1 # remove newline from the beginning of the selectedText. if selectedText.match(/^\n/) selectedText = selectedText.replace(/^\n/, "") newlineStart = "\n" newlineStartpos = 1 # remove newline from the end of the selectedText. if selectedText.match(/\n$/g) selectedText = selectedText.replace(/\n$/g, "") newlineEnd = "\n" newlineEndPos = 1 # no clue, i'm sure it made sense at the time i wrote it if followupText.match(/^\n/) newlineFollowup = "" else newlineFollowup = "\n\n" # first off let's check if the user is trying to mess with lists if (button.tagStart is " * ") or (button.tagStart is " # ") listItems = 0 # sets up a default to be able to properly manipulate final selection # set-up all of the regex's re_start = new RegExp("^ (\\*|\\#) ", "g") if button.tagStart is " # " re_tag = new RegExp(" \\# ", "g") # because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though else re_tag = new RegExp(" \\* ", "g") re_replace = new RegExp(" (\\*|\\#) ", "g") # try to remove bullets in text copied from ms word **Mac Only!** re_word_bullet_m_s = new RegExp("• ", "g") # mac/safari re_word_bullet_m_f = new RegExp("∑ ", "g") # mac/firefox selectedText = selectedText.replace(re_word_bullet_m_s, "").replace(re_word_bullet_m_f, "") # if the selected text starts with one of the tags we're working with... if selectedText.match(re_start) # if tag that begins the selection matches the one clicked, remove them all if selectedText.match(re_tag) finalText = beginningText + newlineStart + selectedText.replace(re_replace, "") + newlineEnd + followupText listItems = matches.length if matches = selectedText.match(RegExp(" (\\*|\\#) ", "g")) posDiffNeg = listItems * 3 # how many list items were there because that's 3 spaces to remove from final selection # else replace the current tag type with the selected tag type else finalText = beginningText + newlineStart + selectedText.replace(re_replace, button.tagStart) + newlineEnd + followupText # else try to create the list type # NOTE: the items in a list will only be replaced if a newline starts with some character, not a space else finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean, newlineReplaceClean + button.tagStart).replace(/\n(\S)/g, "\n" + button.tagStart + "$1") + newlineEnd + followupText listItems = matches.length if matches = selectedText.match(/\n(\S)/g) posDiffPos = 3 + listItems * 3 # now lets look and see if the user is trying to muck with a block or block modifier else if button.tagStart.match(/^(h1|h2|h3|h4|h5|h6|bq|p|\>|\<\>|\<|\=|\(|\))/g) insertTag = "" insertModifier = "" tagPartBlock = "" tagPartModifier = "" tagPartModifierOrig = "" # ugly hack but it's late drawSwitch = "" captureIndentStart = false captureListStart = false periodAddition = "\\. " periodAdditionClean = ". " listItemsAddition = 0 re_list_items = new RegExp("(\\*+|\\#+)", "g") # need this regex later on when checking indentation of lists re_block_modifier = new RegExp("^(h1|h2|h3|h4|h5|h6|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)", "g") if tagPartMatches = re_block_modifier.exec(selectedText) tagPartBlock = tagPartMatches[1] tagPartModifier = tagPartMatches[2] tagPartModifierOrig = tagPartMatches[2] tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g, "\\(") # if tag already up is the same as the tag provided replace the whole tag if tagPartBlock is button.tagStart insertTag = tagPartBlock + tagPartModifierOrig # use Orig because it's escaped for regex drawSwitch = 0 # else if let's check to add/remove block modifier else if (tagPartModifier is button.tagStart) or (newm = tagPartModifier.match(/[\(]{2,}/g)) if (button.tagStart is "(") or (button.tagStart is ")") indentLength = tagPartModifier.length if button.tagStart is "(" indentLength = indentLength + 1 else indentLength = indentLength - 1 i = 0 while i < indentLength insertModifier = insertModifier + "(" i++ insertTag = tagPartBlock + insertModifier else if button.tagStart is tagPartModifier insertTag = tagPartBlock # going to rely on the default empty insertModifier else if button.tagStart.match(/(\>|\<\>|\<|\=)/g) insertTag = tagPartBlock + button.tagStart else insertTag = button.tagStart + tagPartModifier drawSwitch = 1 # indentation of list items else if listPartMatches = re_list_items.exec(tagPartBlock) listTypeMatch = listPartMatches[1] indentLength = tagPartBlock.length - 2 listInsert = "" if button.tagStart is "(" indentLength = indentLength + 1 else indentLength = indentLength - 1 if listTypeMatch.match(/[\*]{1,}/g) listType = "*" listReplace = "\\*" else listType = "#" listReplace = "\\#" i = 0 while i < indentLength listInsert = listInsert + listType i++ unless listInsert is "" insertTag = " " + listInsert + " " else insertTag = "" tagPartBlock = tagPartBlock.replace(/(\*|\#)/g, listReplace) drawSwitch = 1 captureListStart = true periodAddition = "" periodAdditionClean = "" listItemsAddition = matches.length if matches = selectedText.match(/\n\s/g) # must be a block modification e.g. p>. to p<. else # if this is a block modification/addition if button.tagStart.match(/(h1|h2|h3|h4|h5|h6|bq|p)/g) if tagPartBlock is "" drawSwitch = 2 else drawSwitch = 1 insertTag = button.tagStart + tagPartModifier # else this is a modifier modification/addition else if (tagPartModifier is "") and (tagPartBlock isnt "") drawSwitch = 1 else if tagPartModifier is "" drawSwitch = 2 else drawSwitch = 1 # if no tag part block but a modifier we need at least the p tag tagPartBlock = "p" if tagPartBlock is "" #make sure to swap out outdent if button.tagStart is ")" tagPartModifier = "" else tagPartModifier = button.tagStart captureIndentStart = true # ugly hack to fix issue with proper selection handling insertTag = tagPartBlock + tagPartModifier mplier = 0 if captureListStart or (tagPartModifier.match(/[\(\)]{1,}/g)) re_start = new RegExp(insertTag.escape + periodAddition, "g") # for tags that mimic regex properties, parens + list tags else re_start = new RegExp(insertTag + periodAddition, "g") # for tags that don't, why i can't just escape everything i have no clue re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition, "g") re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape, "g") re_tag = new RegExp(insertTag.escape + periodAddition.escape, "g") # ************************************************************************************************************************* # this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements # ************************************************************************************************************************* if (drawSwitch is 0) or (drawSwitch is 1) if drawSwitch is 0 # completely removing a tag finalText = beginningText + newlineStart + selectedText.replace(re_start, "").replace(re_middle, newlineReplaceClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffNeg = insertTag.length + 2 + (mplier * 4) else # modifying a tag, though we do delete bullets here finalText = beginningText + newlineStart + selectedText.replace(re_old, insertTag + periodAdditionClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) # figure out the length of various elements to modify the selection position if captureIndentStart # need to double-check that this wasn't the first indent tagPreviousLength = tagPartBlock.length tagCurrentLength = insertTag.length else if captureListStart # if this is a list we're manipulating if button.tagStart is "(" # if indenting tagPreviousLength = listTypeMatch.length + 2 tagCurrentLength = insertTag.length + listItemsAddition else if insertTag.match(/(\*|\#)/g) # if removing but still has bullets tagPreviousLength = insertTag.length + listItemsAddition tagCurrentLength = listTypeMatch.length else # if removing last bullet tagPreviousLength = insertTag.length + listItemsAddition tagCurrentLength = listTypeMatch.length - (3 * listItemsAddition) - 1 else # everything else tagPreviousLength = tagPartBlock.length + tagPartModifier.length tagCurrentLength = insertTag.length if tagCurrentLength > tagPreviousLength posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier * (tagCurrentLength - tagPreviousLength)) else posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier * (tagPreviousLength - tagCurrentLength)) else # for adding tags other then bullets (have their own statement) finalText = beginningText + newlineStart + insertTag + ". " + selectedText.replace(newlineReplaceRegexClean, button.tagEnd + "\n" + insertTag + ". ") + newlineFollowup + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffPos = insertTag.length + 2 + (mplier * 4) # swap in and out the simple tags around a selection like bold else mplier = 1 # the multiplier for the tag length re_start = new RegExp("^\\" + button.tagStart, "g") re_end = new RegExp("\\" + button.tagEnd + "$", "g") re_middle = new RegExp("\\" + button.tagEnd + newlineReplaceRegexDirty + "\\" + button.tagStart, "g") if selectedText.match(re_start) and selectedText.match(re_end) finalText = beginningText + newlineStart + selectedText.replace(re_start, "").replace(re_end, "").replace(re_middle, newlineReplaceClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffNeg = button.tagStart.length * mplier + button.tagEnd.length * mplier else finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean, button.tagEnd + newlineReplaceClean + button.tagStart) + button.tagEnd + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffPos = (button.tagStart.length * mplier) + (button.tagEnd.length * mplier) cursorPos += button.tagStart.length + button.tagEnd.length # just swap in and out single values, e.g. someone clicks b they'll get a * else buttonStart = "" buttonEnd = "" re_p = new RegExp("(\\<|\\>|\\=|\\<\\>|\\(|\\))", "g") re_h = new RegExp("^(h1|h2|h3|h4|h5|h6|p|bq)", "g") if not @checkOpenTags(button) or button.tagEnd is "" # opening tag if button.tagStart.match(re_h) buttonStart = button.tagStart + ". " else buttonStart = button.tagStart if button.tagStart.match(re_p) # make sure that invoking block modifiers don't do anything finalText = beginningText + followupText cursorPos = startPos else finalText = beginningText + buttonStart + followupText @addTag button cursorPos = startPos + buttonStart.length else # closing tag if button.tagStart.match(re_p) buttonEnd = "\n\n" else if button.tagStart.match(re_h) buttonEnd = "\n\n" else buttonEnd = button.tagEnd finalText = beginningText + button.tagEnd + followupText @removeTag button cursorPos = startPos + button.tagEnd.length # set the appropriate DOM value with the final text if FF is true myField.value = finalText myField.scrollTop = scrollTop else sel.text = finalText if textSelected # build up the selection capture, doesn't work in IE myField.selectionStart = startPos + newlineStartPos myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos else myField.selectionStart = cursorPos myField.selectionEnd = cursorPos window.TextileEditor = TextileEditor
8383
#Textile Editor v0.2 #created by: <NAME>, wvu web services #created on: march 17, 2007 #project page: slateinfo.blogs.wvu.edu # #inspired by: # - <NAME>, http://www.hakjoon.com/code/38/textile-quicktags-redirect & # - <NAME>, http://alexking.org/projects/js-quicktags # #features: # - supports: IE7, FF2, Safari2 # - ability to use "simple" vs. "extended" editor # - supports all block elements in textile except footnote # - supports all block modifier elements in textile # - supports simple ordered and unordered lists # - supports most of the phrase modifiers, very easy to add the missing ones # - supports multiple-paragraph modification # - can have multiple "editors" on one page, access key use in this environment is flaky # - access key support # - select text to add and remove tags, selection stays highlighted # - seamlessly change between tags and modifiers # - doesn't need to be in the body onload tag # - can supply your own, custom IDs for the editor to be drawn around # # TODO: # - a clean way of providing image and link inserts # - get the selection to properly show in IE # #more on textile: # - Textism, http://www.textism.com/tools/textile/index.php # - Textile Reference, http://hobix.com/textile/ class TextileEditorButton constructor: (id, display, tagStart, tagEnd, access, title, sve, open) -> @id = id # used to name the toolbar button @display = display # label on button @tagStart = tagStart # open tag @tagEnd = tagEnd # close tag @access = access # set to -1 if tag does not need to be closed @title = title # sets the title attribute of the button to give 'tool tips' @sve = sve # sve = simple vs. extended. add an 's' to make it show up in the simple toolbar @open = open # set to -1 if tag does not need to be closed @standard = true # this is a standard button window.TextileEditorButton = TextileEditorButton class TextileEditorButtonSeparator constructor: (sve) -> @separator = true @sve = sve window.TextileEditorButtonSeparator = TextileEditorButtonSeparator class TextileEditor @setButtons: (buttons) -> TextileEditor.buttons = buttons @addButton: (button) -> @getButtons().push(button) @getButtons: () -> TextileEditor.buttons || new Array() constructor: (canvas, view) -> toolbar = document.createElement("div") toolbar.id = "textile-toolbar-" + canvas toolbar.className = "textile-toolbar" @canvas = document.getElementById(canvas) @canvas.parentNode.insertBefore(toolbar, @canvas) @openTags = new Array() # Create the local Button array by assigning theButtons array to edButtons edButtons = TextileEditor.getButtons() standardButtons = new Array() i = 0 while i < edButtons.length thisButton = @prepareButton(edButtons[i]) if view is "simple" if edButtons[i].sve is "s" toolbar.appendChild thisButton standardButtons.push thisButton else if typeof thisButton is "string" toolbar.innerHTML += thisButton else toolbar.appendChild thisButton standardButtons.push thisButton i++ te = this buttons = toolbar.getElementsByTagName("button") i = 0 while i < buttons.length unless buttons[i].onclick buttons[i].onclick = -> te.insertTag this return false buttons[i].tagStart = buttons[i].getAttribute("tagStart") buttons[i].tagEnd = buttons[i].getAttribute("tagEnd") buttons[i].open = buttons[i].getAttribute("open") buttons[i].textile_editor = te buttons[i].canvas = te.canvas i++ # draw individual buttons (edShowButton) prepareButton: (button) -> if button.separator theButton = document.createElement("span") theButton.className = "ed_sep" return theButton if button.standard theButton = document.createElement("button") theButton.id = button.id theButton.setAttribute("class", "standard") theButton.setAttribute("tagStart", button.tagStart) theButton.setAttribute("tagEnd", button.tagEnd) theButton.setAttribute("open", button.open) img = document.createElement("img") img.src = button.display theButton.appendChild(img) else return button theButton.accessKey = button.access theButton.title = button.title return theButton # if clicked, no selected text, tag not open highlight button # (edAddTag) addTag: (button) -> unless button.tagEnd is "" @openTags[@openTags.length] = button button.className = "selected" return button # if clicked, no selected text, tag open lowlight button # (edRemoveTag) removeTag: (button) -> i = 0 while i < @openTags.length if @openTags[i] is button @openTags.splice(button, 1) #var el = document.getElementById(button.id); #el.className = 'unselected'; button.className = "unselected" i++ return undefined # see if there are open tags. for the remove tag bit... # (edCheckOpenTags) checkOpenTags: (button) -> tag = 0 i = 0 while i < @openTags.length tag++ if @openTags[i] is button i++ return (tag > 0) # tag found / not found # insert the tag. this is the bulk of the code. # (edInsertTag) insertTag: (button, tagStart, tagEnd) -> myField = button.canvas if tagStart button.tagStart = tagStart button.tagEnd = (if tagEnd then tagEnd else "\n") textSelected = false finalText = "" FF = false # grab the text that's going to be manipulated, by browser if document.selection # IE support myField.focus() sel = document.selection.createRange() # set-up the text vars beginningText = "" followupText = "" selectedText = sel.text # check if text has been selected textSelected = true if sel.text.length > 0 # set-up newline regex's so we can swap tags across multiple paragraphs newlineReplaceRegexClean = /\r\n\s\n/g newlineReplaceRegexDirty = "\\r\\n\\s\\n" newlineReplaceClean = "\r\n\n" else if myField.selectionStart or myField.selectionStart == 0 or myField.selectionStart == '0' # MOZ/FF/NS/S support # figure out cursor and selection positions startPos = myField.selectionStart endPos = myField.selectionEnd cursorPos = endPos scrollTop = myField.scrollTop FF = true # note that is is a FF/MOZ/NS/S browser # set-up the text vars beginningText = myField.value.substring(0, startPos) followupText = myField.value.substring(endPos, myField.value.length) # check if text has been selected unless startPos is endPos textSelected = true selectedText = myField.value.substring(startPos, endPos) # set-up newline regex's so we can swap tags across multiple paragraphs newlineReplaceRegexClean = /\n\n/g newlineReplaceRegexDirty = "\\n\\n" newlineReplaceClean = "\n\n" # if there is text that has been highlighted... if textSelected # set-up some defaults for how to handle bad new line characters newlineStart = "" newlineStartPos = 0 newlineEnd = "" newlineEndPos = 0 newlineFollowup = "" # set-up some defaults for how to handle placing the beginning and end of selection posDiffPos = 0 posDiffNeg = 0 mplier = 1 # remove newline from the beginning of the selectedText. if selectedText.match(/^\n/) selectedText = selectedText.replace(/^\n/, "") newlineStart = "\n" newlineStartpos = 1 # remove newline from the end of the selectedText. if selectedText.match(/\n$/g) selectedText = selectedText.replace(/\n$/g, "") newlineEnd = "\n" newlineEndPos = 1 # no clue, i'm sure it made sense at the time i wrote it if followupText.match(/^\n/) newlineFollowup = "" else newlineFollowup = "\n\n" # first off let's check if the user is trying to mess with lists if (button.tagStart is " * ") or (button.tagStart is " # ") listItems = 0 # sets up a default to be able to properly manipulate final selection # set-up all of the regex's re_start = new RegExp("^ (\\*|\\#) ", "g") if button.tagStart is " # " re_tag = new RegExp(" \\# ", "g") # because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though else re_tag = new RegExp(" \\* ", "g") re_replace = new RegExp(" (\\*|\\#) ", "g") # try to remove bullets in text copied from ms word **Mac Only!** re_word_bullet_m_s = new RegExp("• ", "g") # mac/safari re_word_bullet_m_f = new RegExp("∑ ", "g") # mac/firefox selectedText = selectedText.replace(re_word_bullet_m_s, "").replace(re_word_bullet_m_f, "") # if the selected text starts with one of the tags we're working with... if selectedText.match(re_start) # if tag that begins the selection matches the one clicked, remove them all if selectedText.match(re_tag) finalText = beginningText + newlineStart + selectedText.replace(re_replace, "") + newlineEnd + followupText listItems = matches.length if matches = selectedText.match(RegExp(" (\\*|\\#) ", "g")) posDiffNeg = listItems * 3 # how many list items were there because that's 3 spaces to remove from final selection # else replace the current tag type with the selected tag type else finalText = beginningText + newlineStart + selectedText.replace(re_replace, button.tagStart) + newlineEnd + followupText # else try to create the list type # NOTE: the items in a list will only be replaced if a newline starts with some character, not a space else finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean, newlineReplaceClean + button.tagStart).replace(/\n(\S)/g, "\n" + button.tagStart + "$1") + newlineEnd + followupText listItems = matches.length if matches = selectedText.match(/\n(\S)/g) posDiffPos = 3 + listItems * 3 # now lets look and see if the user is trying to muck with a block or block modifier else if button.tagStart.match(/^(h1|h2|h3|h4|h5|h6|bq|p|\>|\<\>|\<|\=|\(|\))/g) insertTag = "" insertModifier = "" tagPartBlock = "" tagPartModifier = "" tagPartModifierOrig = "" # ugly hack but it's late drawSwitch = "" captureIndentStart = false captureListStart = false periodAddition = "\\. " periodAdditionClean = ". " listItemsAddition = 0 re_list_items = new RegExp("(\\*+|\\#+)", "g") # need this regex later on when checking indentation of lists re_block_modifier = new RegExp("^(h1|h2|h3|h4|h5|h6|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)", "g") if tagPartMatches = re_block_modifier.exec(selectedText) tagPartBlock = tagPartMatches[1] tagPartModifier = tagPartMatches[2] tagPartModifierOrig = tagPartMatches[2] tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g, "\\(") # if tag already up is the same as the tag provided replace the whole tag if tagPartBlock is button.tagStart insertTag = tagPartBlock + tagPartModifierOrig # use Orig because it's escaped for regex drawSwitch = 0 # else if let's check to add/remove block modifier else if (tagPartModifier is button.tagStart) or (newm = tagPartModifier.match(/[\(]{2,}/g)) if (button.tagStart is "(") or (button.tagStart is ")") indentLength = tagPartModifier.length if button.tagStart is "(" indentLength = indentLength + 1 else indentLength = indentLength - 1 i = 0 while i < indentLength insertModifier = insertModifier + "(" i++ insertTag = tagPartBlock + insertModifier else if button.tagStart is tagPartModifier insertTag = tagPartBlock # going to rely on the default empty insertModifier else if button.tagStart.match(/(\>|\<\>|\<|\=)/g) insertTag = tagPartBlock + button.tagStart else insertTag = button.tagStart + tagPartModifier drawSwitch = 1 # indentation of list items else if listPartMatches = re_list_items.exec(tagPartBlock) listTypeMatch = listPartMatches[1] indentLength = tagPartBlock.length - 2 listInsert = "" if button.tagStart is "(" indentLength = indentLength + 1 else indentLength = indentLength - 1 if listTypeMatch.match(/[\*]{1,}/g) listType = "*" listReplace = "\\*" else listType = "#" listReplace = "\\#" i = 0 while i < indentLength listInsert = listInsert + listType i++ unless listInsert is "" insertTag = " " + listInsert + " " else insertTag = "" tagPartBlock = tagPartBlock.replace(/(\*|\#)/g, listReplace) drawSwitch = 1 captureListStart = true periodAddition = "" periodAdditionClean = "" listItemsAddition = matches.length if matches = selectedText.match(/\n\s/g) # must be a block modification e.g. p>. to p<. else # if this is a block modification/addition if button.tagStart.match(/(h1|h2|h3|h4|h5|h6|bq|p)/g) if tagPartBlock is "" drawSwitch = 2 else drawSwitch = 1 insertTag = button.tagStart + tagPartModifier # else this is a modifier modification/addition else if (tagPartModifier is "") and (tagPartBlock isnt "") drawSwitch = 1 else if tagPartModifier is "" drawSwitch = 2 else drawSwitch = 1 # if no tag part block but a modifier we need at least the p tag tagPartBlock = "p" if tagPartBlock is "" #make sure to swap out outdent if button.tagStart is ")" tagPartModifier = "" else tagPartModifier = button.tagStart captureIndentStart = true # ugly hack to fix issue with proper selection handling insertTag = tagPartBlock + tagPartModifier mplier = 0 if captureListStart or (tagPartModifier.match(/[\(\)]{1,}/g)) re_start = new RegExp(insertTag.escape + periodAddition, "g") # for tags that mimic regex properties, parens + list tags else re_start = new RegExp(insertTag + periodAddition, "g") # for tags that don't, why i can't just escape everything i have no clue re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition, "g") re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape, "g") re_tag = new RegExp(insertTag.escape + periodAddition.escape, "g") # ************************************************************************************************************************* # this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements # ************************************************************************************************************************* if (drawSwitch is 0) or (drawSwitch is 1) if drawSwitch is 0 # completely removing a tag finalText = beginningText + newlineStart + selectedText.replace(re_start, "").replace(re_middle, newlineReplaceClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffNeg = insertTag.length + 2 + (mplier * 4) else # modifying a tag, though we do delete bullets here finalText = beginningText + newlineStart + selectedText.replace(re_old, insertTag + periodAdditionClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) # figure out the length of various elements to modify the selection position if captureIndentStart # need to double-check that this wasn't the first indent tagPreviousLength = tagPartBlock.length tagCurrentLength = insertTag.length else if captureListStart # if this is a list we're manipulating if button.tagStart is "(" # if indenting tagPreviousLength = listTypeMatch.length + 2 tagCurrentLength = insertTag.length + listItemsAddition else if insertTag.match(/(\*|\#)/g) # if removing but still has bullets tagPreviousLength = insertTag.length + listItemsAddition tagCurrentLength = listTypeMatch.length else # if removing last bullet tagPreviousLength = insertTag.length + listItemsAddition tagCurrentLength = listTypeMatch.length - (3 * listItemsAddition) - 1 else # everything else tagPreviousLength = tagPartBlock.length + tagPartModifier.length tagCurrentLength = insertTag.length if tagCurrentLength > tagPreviousLength posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier * (tagCurrentLength - tagPreviousLength)) else posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier * (tagPreviousLength - tagCurrentLength)) else # for adding tags other then bullets (have their own statement) finalText = beginningText + newlineStart + insertTag + ". " + selectedText.replace(newlineReplaceRegexClean, button.tagEnd + "\n" + insertTag + ". ") + newlineFollowup + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffPos = insertTag.length + 2 + (mplier * 4) # swap in and out the simple tags around a selection like bold else mplier = 1 # the multiplier for the tag length re_start = new RegExp("^\\" + button.tagStart, "g") re_end = new RegExp("\\" + button.tagEnd + "$", "g") re_middle = new RegExp("\\" + button.tagEnd + newlineReplaceRegexDirty + "\\" + button.tagStart, "g") if selectedText.match(re_start) and selectedText.match(re_end) finalText = beginningText + newlineStart + selectedText.replace(re_start, "").replace(re_end, "").replace(re_middle, newlineReplaceClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffNeg = button.tagStart.length * mplier + button.tagEnd.length * mplier else finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean, button.tagEnd + newlineReplaceClean + button.tagStart) + button.tagEnd + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffPos = (button.tagStart.length * mplier) + (button.tagEnd.length * mplier) cursorPos += button.tagStart.length + button.tagEnd.length # just swap in and out single values, e.g. someone clicks b they'll get a * else buttonStart = "" buttonEnd = "" re_p = new RegExp("(\\<|\\>|\\=|\\<\\>|\\(|\\))", "g") re_h = new RegExp("^(h1|h2|h3|h4|h5|h6|p|bq)", "g") if not @checkOpenTags(button) or button.tagEnd is "" # opening tag if button.tagStart.match(re_h) buttonStart = button.tagStart + ". " else buttonStart = button.tagStart if button.tagStart.match(re_p) # make sure that invoking block modifiers don't do anything finalText = beginningText + followupText cursorPos = startPos else finalText = beginningText + buttonStart + followupText @addTag button cursorPos = startPos + buttonStart.length else # closing tag if button.tagStart.match(re_p) buttonEnd = "\n\n" else if button.tagStart.match(re_h) buttonEnd = "\n\n" else buttonEnd = button.tagEnd finalText = beginningText + button.tagEnd + followupText @removeTag button cursorPos = startPos + button.tagEnd.length # set the appropriate DOM value with the final text if FF is true myField.value = finalText myField.scrollTop = scrollTop else sel.text = finalText if textSelected # build up the selection capture, doesn't work in IE myField.selectionStart = startPos + newlineStartPos myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos else myField.selectionStart = cursorPos myField.selectionEnd = cursorPos window.TextileEditor = TextileEditor
true
#Textile Editor v0.2 #created by: PI:NAME:<NAME>END_PI, wvu web services #created on: march 17, 2007 #project page: slateinfo.blogs.wvu.edu # #inspired by: # - PI:NAME:<NAME>END_PI, http://www.hakjoon.com/code/38/textile-quicktags-redirect & # - PI:NAME:<NAME>END_PI, http://alexking.org/projects/js-quicktags # #features: # - supports: IE7, FF2, Safari2 # - ability to use "simple" vs. "extended" editor # - supports all block elements in textile except footnote # - supports all block modifier elements in textile # - supports simple ordered and unordered lists # - supports most of the phrase modifiers, very easy to add the missing ones # - supports multiple-paragraph modification # - can have multiple "editors" on one page, access key use in this environment is flaky # - access key support # - select text to add and remove tags, selection stays highlighted # - seamlessly change between tags and modifiers # - doesn't need to be in the body onload tag # - can supply your own, custom IDs for the editor to be drawn around # # TODO: # - a clean way of providing image and link inserts # - get the selection to properly show in IE # #more on textile: # - Textism, http://www.textism.com/tools/textile/index.php # - Textile Reference, http://hobix.com/textile/ class TextileEditorButton constructor: (id, display, tagStart, tagEnd, access, title, sve, open) -> @id = id # used to name the toolbar button @display = display # label on button @tagStart = tagStart # open tag @tagEnd = tagEnd # close tag @access = access # set to -1 if tag does not need to be closed @title = title # sets the title attribute of the button to give 'tool tips' @sve = sve # sve = simple vs. extended. add an 's' to make it show up in the simple toolbar @open = open # set to -1 if tag does not need to be closed @standard = true # this is a standard button window.TextileEditorButton = TextileEditorButton class TextileEditorButtonSeparator constructor: (sve) -> @separator = true @sve = sve window.TextileEditorButtonSeparator = TextileEditorButtonSeparator class TextileEditor @setButtons: (buttons) -> TextileEditor.buttons = buttons @addButton: (button) -> @getButtons().push(button) @getButtons: () -> TextileEditor.buttons || new Array() constructor: (canvas, view) -> toolbar = document.createElement("div") toolbar.id = "textile-toolbar-" + canvas toolbar.className = "textile-toolbar" @canvas = document.getElementById(canvas) @canvas.parentNode.insertBefore(toolbar, @canvas) @openTags = new Array() # Create the local Button array by assigning theButtons array to edButtons edButtons = TextileEditor.getButtons() standardButtons = new Array() i = 0 while i < edButtons.length thisButton = @prepareButton(edButtons[i]) if view is "simple" if edButtons[i].sve is "s" toolbar.appendChild thisButton standardButtons.push thisButton else if typeof thisButton is "string" toolbar.innerHTML += thisButton else toolbar.appendChild thisButton standardButtons.push thisButton i++ te = this buttons = toolbar.getElementsByTagName("button") i = 0 while i < buttons.length unless buttons[i].onclick buttons[i].onclick = -> te.insertTag this return false buttons[i].tagStart = buttons[i].getAttribute("tagStart") buttons[i].tagEnd = buttons[i].getAttribute("tagEnd") buttons[i].open = buttons[i].getAttribute("open") buttons[i].textile_editor = te buttons[i].canvas = te.canvas i++ # draw individual buttons (edShowButton) prepareButton: (button) -> if button.separator theButton = document.createElement("span") theButton.className = "ed_sep" return theButton if button.standard theButton = document.createElement("button") theButton.id = button.id theButton.setAttribute("class", "standard") theButton.setAttribute("tagStart", button.tagStart) theButton.setAttribute("tagEnd", button.tagEnd) theButton.setAttribute("open", button.open) img = document.createElement("img") img.src = button.display theButton.appendChild(img) else return button theButton.accessKey = button.access theButton.title = button.title return theButton # if clicked, no selected text, tag not open highlight button # (edAddTag) addTag: (button) -> unless button.tagEnd is "" @openTags[@openTags.length] = button button.className = "selected" return button # if clicked, no selected text, tag open lowlight button # (edRemoveTag) removeTag: (button) -> i = 0 while i < @openTags.length if @openTags[i] is button @openTags.splice(button, 1) #var el = document.getElementById(button.id); #el.className = 'unselected'; button.className = "unselected" i++ return undefined # see if there are open tags. for the remove tag bit... # (edCheckOpenTags) checkOpenTags: (button) -> tag = 0 i = 0 while i < @openTags.length tag++ if @openTags[i] is button i++ return (tag > 0) # tag found / not found # insert the tag. this is the bulk of the code. # (edInsertTag) insertTag: (button, tagStart, tagEnd) -> myField = button.canvas if tagStart button.tagStart = tagStart button.tagEnd = (if tagEnd then tagEnd else "\n") textSelected = false finalText = "" FF = false # grab the text that's going to be manipulated, by browser if document.selection # IE support myField.focus() sel = document.selection.createRange() # set-up the text vars beginningText = "" followupText = "" selectedText = sel.text # check if text has been selected textSelected = true if sel.text.length > 0 # set-up newline regex's so we can swap tags across multiple paragraphs newlineReplaceRegexClean = /\r\n\s\n/g newlineReplaceRegexDirty = "\\r\\n\\s\\n" newlineReplaceClean = "\r\n\n" else if myField.selectionStart or myField.selectionStart == 0 or myField.selectionStart == '0' # MOZ/FF/NS/S support # figure out cursor and selection positions startPos = myField.selectionStart endPos = myField.selectionEnd cursorPos = endPos scrollTop = myField.scrollTop FF = true # note that is is a FF/MOZ/NS/S browser # set-up the text vars beginningText = myField.value.substring(0, startPos) followupText = myField.value.substring(endPos, myField.value.length) # check if text has been selected unless startPos is endPos textSelected = true selectedText = myField.value.substring(startPos, endPos) # set-up newline regex's so we can swap tags across multiple paragraphs newlineReplaceRegexClean = /\n\n/g newlineReplaceRegexDirty = "\\n\\n" newlineReplaceClean = "\n\n" # if there is text that has been highlighted... if textSelected # set-up some defaults for how to handle bad new line characters newlineStart = "" newlineStartPos = 0 newlineEnd = "" newlineEndPos = 0 newlineFollowup = "" # set-up some defaults for how to handle placing the beginning and end of selection posDiffPos = 0 posDiffNeg = 0 mplier = 1 # remove newline from the beginning of the selectedText. if selectedText.match(/^\n/) selectedText = selectedText.replace(/^\n/, "") newlineStart = "\n" newlineStartpos = 1 # remove newline from the end of the selectedText. if selectedText.match(/\n$/g) selectedText = selectedText.replace(/\n$/g, "") newlineEnd = "\n" newlineEndPos = 1 # no clue, i'm sure it made sense at the time i wrote it if followupText.match(/^\n/) newlineFollowup = "" else newlineFollowup = "\n\n" # first off let's check if the user is trying to mess with lists if (button.tagStart is " * ") or (button.tagStart is " # ") listItems = 0 # sets up a default to be able to properly manipulate final selection # set-up all of the regex's re_start = new RegExp("^ (\\*|\\#) ", "g") if button.tagStart is " # " re_tag = new RegExp(" \\# ", "g") # because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though else re_tag = new RegExp(" \\* ", "g") re_replace = new RegExp(" (\\*|\\#) ", "g") # try to remove bullets in text copied from ms word **Mac Only!** re_word_bullet_m_s = new RegExp("• ", "g") # mac/safari re_word_bullet_m_f = new RegExp("∑ ", "g") # mac/firefox selectedText = selectedText.replace(re_word_bullet_m_s, "").replace(re_word_bullet_m_f, "") # if the selected text starts with one of the tags we're working with... if selectedText.match(re_start) # if tag that begins the selection matches the one clicked, remove them all if selectedText.match(re_tag) finalText = beginningText + newlineStart + selectedText.replace(re_replace, "") + newlineEnd + followupText listItems = matches.length if matches = selectedText.match(RegExp(" (\\*|\\#) ", "g")) posDiffNeg = listItems * 3 # how many list items were there because that's 3 spaces to remove from final selection # else replace the current tag type with the selected tag type else finalText = beginningText + newlineStart + selectedText.replace(re_replace, button.tagStart) + newlineEnd + followupText # else try to create the list type # NOTE: the items in a list will only be replaced if a newline starts with some character, not a space else finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean, newlineReplaceClean + button.tagStart).replace(/\n(\S)/g, "\n" + button.tagStart + "$1") + newlineEnd + followupText listItems = matches.length if matches = selectedText.match(/\n(\S)/g) posDiffPos = 3 + listItems * 3 # now lets look and see if the user is trying to muck with a block or block modifier else if button.tagStart.match(/^(h1|h2|h3|h4|h5|h6|bq|p|\>|\<\>|\<|\=|\(|\))/g) insertTag = "" insertModifier = "" tagPartBlock = "" tagPartModifier = "" tagPartModifierOrig = "" # ugly hack but it's late drawSwitch = "" captureIndentStart = false captureListStart = false periodAddition = "\\. " periodAdditionClean = ". " listItemsAddition = 0 re_list_items = new RegExp("(\\*+|\\#+)", "g") # need this regex later on when checking indentation of lists re_block_modifier = new RegExp("^(h1|h2|h3|h4|h5|h6|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)", "g") if tagPartMatches = re_block_modifier.exec(selectedText) tagPartBlock = tagPartMatches[1] tagPartModifier = tagPartMatches[2] tagPartModifierOrig = tagPartMatches[2] tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g, "\\(") # if tag already up is the same as the tag provided replace the whole tag if tagPartBlock is button.tagStart insertTag = tagPartBlock + tagPartModifierOrig # use Orig because it's escaped for regex drawSwitch = 0 # else if let's check to add/remove block modifier else if (tagPartModifier is button.tagStart) or (newm = tagPartModifier.match(/[\(]{2,}/g)) if (button.tagStart is "(") or (button.tagStart is ")") indentLength = tagPartModifier.length if button.tagStart is "(" indentLength = indentLength + 1 else indentLength = indentLength - 1 i = 0 while i < indentLength insertModifier = insertModifier + "(" i++ insertTag = tagPartBlock + insertModifier else if button.tagStart is tagPartModifier insertTag = tagPartBlock # going to rely on the default empty insertModifier else if button.tagStart.match(/(\>|\<\>|\<|\=)/g) insertTag = tagPartBlock + button.tagStart else insertTag = button.tagStart + tagPartModifier drawSwitch = 1 # indentation of list items else if listPartMatches = re_list_items.exec(tagPartBlock) listTypeMatch = listPartMatches[1] indentLength = tagPartBlock.length - 2 listInsert = "" if button.tagStart is "(" indentLength = indentLength + 1 else indentLength = indentLength - 1 if listTypeMatch.match(/[\*]{1,}/g) listType = "*" listReplace = "\\*" else listType = "#" listReplace = "\\#" i = 0 while i < indentLength listInsert = listInsert + listType i++ unless listInsert is "" insertTag = " " + listInsert + " " else insertTag = "" tagPartBlock = tagPartBlock.replace(/(\*|\#)/g, listReplace) drawSwitch = 1 captureListStart = true periodAddition = "" periodAdditionClean = "" listItemsAddition = matches.length if matches = selectedText.match(/\n\s/g) # must be a block modification e.g. p>. to p<. else # if this is a block modification/addition if button.tagStart.match(/(h1|h2|h3|h4|h5|h6|bq|p)/g) if tagPartBlock is "" drawSwitch = 2 else drawSwitch = 1 insertTag = button.tagStart + tagPartModifier # else this is a modifier modification/addition else if (tagPartModifier is "") and (tagPartBlock isnt "") drawSwitch = 1 else if tagPartModifier is "" drawSwitch = 2 else drawSwitch = 1 # if no tag part block but a modifier we need at least the p tag tagPartBlock = "p" if tagPartBlock is "" #make sure to swap out outdent if button.tagStart is ")" tagPartModifier = "" else tagPartModifier = button.tagStart captureIndentStart = true # ugly hack to fix issue with proper selection handling insertTag = tagPartBlock + tagPartModifier mplier = 0 if captureListStart or (tagPartModifier.match(/[\(\)]{1,}/g)) re_start = new RegExp(insertTag.escape + periodAddition, "g") # for tags that mimic regex properties, parens + list tags else re_start = new RegExp(insertTag + periodAddition, "g") # for tags that don't, why i can't just escape everything i have no clue re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition, "g") re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape, "g") re_tag = new RegExp(insertTag.escape + periodAddition.escape, "g") # ************************************************************************************************************************* # this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements # ************************************************************************************************************************* if (drawSwitch is 0) or (drawSwitch is 1) if drawSwitch is 0 # completely removing a tag finalText = beginningText + newlineStart + selectedText.replace(re_start, "").replace(re_middle, newlineReplaceClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffNeg = insertTag.length + 2 + (mplier * 4) else # modifying a tag, though we do delete bullets here finalText = beginningText + newlineStart + selectedText.replace(re_old, insertTag + periodAdditionClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) # figure out the length of various elements to modify the selection position if captureIndentStart # need to double-check that this wasn't the first indent tagPreviousLength = tagPartBlock.length tagCurrentLength = insertTag.length else if captureListStart # if this is a list we're manipulating if button.tagStart is "(" # if indenting tagPreviousLength = listTypeMatch.length + 2 tagCurrentLength = insertTag.length + listItemsAddition else if insertTag.match(/(\*|\#)/g) # if removing but still has bullets tagPreviousLength = insertTag.length + listItemsAddition tagCurrentLength = listTypeMatch.length else # if removing last bullet tagPreviousLength = insertTag.length + listItemsAddition tagCurrentLength = listTypeMatch.length - (3 * listItemsAddition) - 1 else # everything else tagPreviousLength = tagPartBlock.length + tagPartModifier.length tagCurrentLength = insertTag.length if tagCurrentLength > tagPreviousLength posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier * (tagCurrentLength - tagPreviousLength)) else posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier * (tagPreviousLength - tagCurrentLength)) else # for adding tags other then bullets (have their own statement) finalText = beginningText + newlineStart + insertTag + ". " + selectedText.replace(newlineReplaceRegexClean, button.tagEnd + "\n" + insertTag + ". ") + newlineFollowup + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffPos = insertTag.length + 2 + (mplier * 4) # swap in and out the simple tags around a selection like bold else mplier = 1 # the multiplier for the tag length re_start = new RegExp("^\\" + button.tagStart, "g") re_end = new RegExp("\\" + button.tagEnd + "$", "g") re_middle = new RegExp("\\" + button.tagEnd + newlineReplaceRegexDirty + "\\" + button.tagStart, "g") if selectedText.match(re_start) and selectedText.match(re_end) finalText = beginningText + newlineStart + selectedText.replace(re_start, "").replace(re_end, "").replace(re_middle, newlineReplaceClean) + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffNeg = button.tagStart.length * mplier + button.tagEnd.length * mplier else finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean, button.tagEnd + newlineReplaceClean + button.tagStart) + button.tagEnd + newlineEnd + followupText mplier = mplier + matches.length if matches = selectedText.match(newlineReplaceRegexClean) posDiffPos = (button.tagStart.length * mplier) + (button.tagEnd.length * mplier) cursorPos += button.tagStart.length + button.tagEnd.length # just swap in and out single values, e.g. someone clicks b they'll get a * else buttonStart = "" buttonEnd = "" re_p = new RegExp("(\\<|\\>|\\=|\\<\\>|\\(|\\))", "g") re_h = new RegExp("^(h1|h2|h3|h4|h5|h6|p|bq)", "g") if not @checkOpenTags(button) or button.tagEnd is "" # opening tag if button.tagStart.match(re_h) buttonStart = button.tagStart + ". " else buttonStart = button.tagStart if button.tagStart.match(re_p) # make sure that invoking block modifiers don't do anything finalText = beginningText + followupText cursorPos = startPos else finalText = beginningText + buttonStart + followupText @addTag button cursorPos = startPos + buttonStart.length else # closing tag if button.tagStart.match(re_p) buttonEnd = "\n\n" else if button.tagStart.match(re_h) buttonEnd = "\n\n" else buttonEnd = button.tagEnd finalText = beginningText + button.tagEnd + followupText @removeTag button cursorPos = startPos + button.tagEnd.length # set the appropriate DOM value with the final text if FF is true myField.value = finalText myField.scrollTop = scrollTop else sel.text = finalText if textSelected # build up the selection capture, doesn't work in IE myField.selectionStart = startPos + newlineStartPos myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos else myField.selectionStart = cursorPos myField.selectionEnd = cursorPos window.TextileEditor = TextileEditor
[ { "context": " parameters =\n method : method\n mail : \"javi.jimenez.villar@gmail.com\"\n password: \"password\"\n Test \"GET\", \"appnima\"", "end": 301, "score": 0.9999145269393921, "start": 272, "tag": "EMAIL", "value": "javi.jimenez.villar@gmail.com" }, { "context"...
test/appnima.coffee
soyjavi/zen
1
"use strict" Test = require("zenrequest").Test module.exports = -> tasks = [] tasks.push _appnima "login", 400 tasks.push _appnima "signup", 409 tasks # Private methods _appnima = (method, status) -> -> parameters = method : method mail : "javi.jimenez.villar@gmail.com" password: "password" Test "GET", "appnima", parameters, null, "Request #{method} to Appnima", status
105235
"use strict" Test = require("zenrequest").Test module.exports = -> tasks = [] tasks.push _appnima "login", 400 tasks.push _appnima "signup", 409 tasks # Private methods _appnima = (method, status) -> -> parameters = method : method mail : "<EMAIL>" password: "<PASSWORD>" Test "GET", "appnima", parameters, null, "Request #{method} to Appnima", status
true
"use strict" Test = require("zenrequest").Test module.exports = -> tasks = [] tasks.push _appnima "login", 400 tasks.push _appnima "signup", 409 tasks # Private methods _appnima = (method, status) -> -> parameters = method : method mail : "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" Test "GET", "appnima", parameters, null, "Request #{method} to Appnima", status
[ { "context": "= require 'property-expr'\n\ndata = \n boss: {name:\"John\"}\n employee: {name:\"Matt\"}\n\ntemplate = jref.reso", "end": 90, "score": 0.9998593330383301, "start": 86, "tag": "NAME", "value": "John" }, { "context": "\ndata = \n boss: {name:\"John\"}\n employee: {nam...
test/evaluate.coffee
pkarman/json-ref-lite
6
jref = require 'json-ref-lite' expr = require 'property-expr' data = boss: {name:"John"} employee: {name:"Matt"} template = jref.resolve boss: name: "{boss.name}" employee: name: "{#/employee/name}" names: [{"$ref":"#/boss/name"},{"$ref":"#/employee/name"}] # (optional) override evaluator # graph = jref.evaluate graph, data, (k,v) -> return v graph = jref.evaluate template, data console.log JSON.stringify graph, null, 2
161137
jref = require 'json-ref-lite' expr = require 'property-expr' data = boss: {name:"<NAME>"} employee: {name:"<NAME>"} template = jref.resolve boss: name: "{boss.name}" employee: name: "{#/employee/name}" names: [{"$ref":"#/boss/name"},{"$ref":"#/employee/name"}] # (optional) override evaluator # graph = jref.evaluate graph, data, (k,v) -> return v graph = jref.evaluate template, data console.log JSON.stringify graph, null, 2
true
jref = require 'json-ref-lite' expr = require 'property-expr' data = boss: {name:"PI:NAME:<NAME>END_PI"} employee: {name:"PI:NAME:<NAME>END_PI"} template = jref.resolve boss: name: "{boss.name}" employee: name: "{#/employee/name}" names: [{"$ref":"#/boss/name"},{"$ref":"#/employee/name"}] # (optional) override evaluator # graph = jref.evaluate graph, data, (k,v) -> return v graph = jref.evaluate template, data console.log JSON.stringify graph, null, 2
[ { "context": " <h5>Reset Password</h5>\n <input id='username' type='hidden' value='#{username}' name='username", "end": 814, "score": 0.9455429911613464, "start": 806, "tag": "USERNAME", "value": "username" }, { "context": " <input id='username' type='hidden' value=...
_attachments/app/views/ChangePasswordView.coffee
jongoz/coconut-analytice
3
$ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ Dialog = require './Dialog' User = require '../models/User' dialogPolyfill = require 'dialog-polyfill' CONST = require "../Constants" crypto = require('crypto') Config = require '../models/Config' class ChangePasswordView extends Backbone.View el: '#login-backgrd' events: "click button#btnSubmit": "ResetPassword" render: (username)=> $("#login-backgrd").show() @$el.html " <dialog id='loginDialog'> <form id='loginForm' method='dialog'> <div class='m-b-20'> <div class='f-left'><img src='images/cocoLogo.png' id='cslogo_xsm'></div> <div id='dialog-title'>#{Coconut.config.appName}</div> </div> <h5>Reset Password</h5> <input id='username' type='hidden' value='#{username}' name='username'> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='password' id='newPass' name='newPass' autofocus> <label class='mdl-textfield__label' for='newPass'>New Password*</label> </div> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='password' id='confirmPass' name='confirmPass'> <label class='mdl-textfield__label' for='confirmPass'>Confirm Password*</label> </div> <div class='coconut-mdl-card__title'></div> <div id='dialogActions'> <button class='mdl-button mdl-js-button mdl-button--primary' id='btnSubmit' type='submit' ><i class='mdi mdi-check-circle mdi-24px'></i> Submit</button> <button class='mdl-button mdl-js-button mdl-button--primary' id='toLogin' type='submit' ><i class='mdi mdi-login mdi-24px'></i> Back to Login</button> </div> </form> </dialog> " dialogPolyfill.registerDialog(loginDialog) componentHandler.upgradeAllRegistered() # Temporary hack for polyfill issue on non-chrome browsers if (Env.is_chrome) loginDialog.showModal() else loginDialog.show() componentHandler.upgradeDom() displayErrorMsg: (msg) -> errMsg = @$el.find('.coconut-mdl-card__title')[0] $(errMsg).html "<i class='mdi mdi-information-outline mdi-24px'></i> #{msg}" ResetPassword: () -> view = @ newPass = $("#newPass").val() confirmPass = $("#confirmPass").val() username = $("input#username").val() if newPass is "" or confirmPass is "" view.displayErrorMsg('Both passwords are required.') return false else if newPass != confirmPass view.displayErrorMsg('Passwords not matching. Please retry') return false else # TODO: codes to reset password in User model? id = "user.#{username}" #salt = Config.salt() salt = "" hashKey = (crypto.pbkdf2Sync newPass, salt, 1000, 256/8, 'sha256').toString('base64') Coconut.database.get id, include_docs: true .catch (error) => view.displayErrorMsg('Error encountered resetting password...') console.error error .then (user) => user.password = hashKey Coconut.database.put user .catch (error) -> console.error error .then => loginDialog.close() view.trigger "success" return false module.exports = ChangePasswordView
135252
$ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ Dialog = require './Dialog' User = require '../models/User' dialogPolyfill = require 'dialog-polyfill' CONST = require "../Constants" crypto = require('crypto') Config = require '../models/Config' class ChangePasswordView extends Backbone.View el: '#login-backgrd' events: "click button#btnSubmit": "ResetPassword" render: (username)=> $("#login-backgrd").show() @$el.html " <dialog id='loginDialog'> <form id='loginForm' method='dialog'> <div class='m-b-20'> <div class='f-left'><img src='images/cocoLogo.png' id='cslogo_xsm'></div> <div id='dialog-title'>#{Coconut.config.appName}</div> </div> <h5>Reset Password</h5> <input id='username' type='hidden' value='#{username}' name='username'> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='password' id='newPass' name='newPass' autofocus> <label class='mdl-textfield__label' for='newPass'>New Password*</label> </div> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='password' id='confirmPass' name='confirmPass'> <label class='mdl-textfield__label' for='confirmPass'>Confirm Password*</label> </div> <div class='coconut-mdl-card__title'></div> <div id='dialogActions'> <button class='mdl-button mdl-js-button mdl-button--primary' id='btnSubmit' type='submit' ><i class='mdi mdi-check-circle mdi-24px'></i> Submit</button> <button class='mdl-button mdl-js-button mdl-button--primary' id='toLogin' type='submit' ><i class='mdi mdi-login mdi-24px'></i> Back to Login</button> </div> </form> </dialog> " dialogPolyfill.registerDialog(loginDialog) componentHandler.upgradeAllRegistered() # Temporary hack for polyfill issue on non-chrome browsers if (Env.is_chrome) loginDialog.showModal() else loginDialog.show() componentHandler.upgradeDom() displayErrorMsg: (msg) -> errMsg = @$el.find('.coconut-mdl-card__title')[0] $(errMsg).html "<i class='mdi mdi-information-outline mdi-24px'></i> #{msg}" ResetPassword: () -> view = @ newPass = $("#newPass").val() confirmPass = $("#confirmPass").val() username = $("input#username").val() if newPass is "" or confirmPass is "" view.displayErrorMsg('Both passwords are required.') return false else if newPass != confirmPass view.displayErrorMsg('Passwords not matching. Please retry') return false else # TODO: codes to reset password in User model? id = "user.#{username}" #salt = Config.salt() salt = "" hashKey = (crypto.pbkdf2Sync newPass, salt, 1000, 256/8, 'sha256').toString('base64') Coconut.database.get id, include_docs: true .catch (error) => view.displayErrorMsg('Error encountered resetting password...') console.error error .then (user) => user.password = <PASSWORD> Coconut.database.put user .catch (error) -> console.error error .then => loginDialog.close() view.trigger "success" return false module.exports = ChangePasswordView
true
$ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ Dialog = require './Dialog' User = require '../models/User' dialogPolyfill = require 'dialog-polyfill' CONST = require "../Constants" crypto = require('crypto') Config = require '../models/Config' class ChangePasswordView extends Backbone.View el: '#login-backgrd' events: "click button#btnSubmit": "ResetPassword" render: (username)=> $("#login-backgrd").show() @$el.html " <dialog id='loginDialog'> <form id='loginForm' method='dialog'> <div class='m-b-20'> <div class='f-left'><img src='images/cocoLogo.png' id='cslogo_xsm'></div> <div id='dialog-title'>#{Coconut.config.appName}</div> </div> <h5>Reset Password</h5> <input id='username' type='hidden' value='#{username}' name='username'> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='password' id='newPass' name='newPass' autofocus> <label class='mdl-textfield__label' for='newPass'>New Password*</label> </div> <div class='mdl-textfield mdl-js-textfield mdl-textfield--floating-label'> <input class='mdl-textfield__input' type='password' id='confirmPass' name='confirmPass'> <label class='mdl-textfield__label' for='confirmPass'>Confirm Password*</label> </div> <div class='coconut-mdl-card__title'></div> <div id='dialogActions'> <button class='mdl-button mdl-js-button mdl-button--primary' id='btnSubmit' type='submit' ><i class='mdi mdi-check-circle mdi-24px'></i> Submit</button> <button class='mdl-button mdl-js-button mdl-button--primary' id='toLogin' type='submit' ><i class='mdi mdi-login mdi-24px'></i> Back to Login</button> </div> </form> </dialog> " dialogPolyfill.registerDialog(loginDialog) componentHandler.upgradeAllRegistered() # Temporary hack for polyfill issue on non-chrome browsers if (Env.is_chrome) loginDialog.showModal() else loginDialog.show() componentHandler.upgradeDom() displayErrorMsg: (msg) -> errMsg = @$el.find('.coconut-mdl-card__title')[0] $(errMsg).html "<i class='mdi mdi-information-outline mdi-24px'></i> #{msg}" ResetPassword: () -> view = @ newPass = $("#newPass").val() confirmPass = $("#confirmPass").val() username = $("input#username").val() if newPass is "" or confirmPass is "" view.displayErrorMsg('Both passwords are required.') return false else if newPass != confirmPass view.displayErrorMsg('Passwords not matching. Please retry') return false else # TODO: codes to reset password in User model? id = "user.#{username}" #salt = Config.salt() salt = "" hashKey = (crypto.pbkdf2Sync newPass, salt, 1000, 256/8, 'sha256').toString('base64') Coconut.database.get id, include_docs: true .catch (error) => view.displayErrorMsg('Error encountered resetting password...') console.error error .then (user) => user.password = PI:PASSWORD:<PASSWORD>END_PI Coconut.database.put user .catch (error) -> console.error error .then => loginDialog.close() view.trigger "success" return false module.exports = ChangePasswordView
[ { "context": "equire 'fs'\nrequest = require 'request'\n\ntoken = '207e2ec811c24123b8e483b784534d3c690084e5'\noutFilePfx = 'data/comments-'\n\nmodule.exports = ", "end": 97, "score": 0.998908519744873, "start": 57, "tag": "KEY", "value": "207e2ec811c24123b8e483b784534d3c690084e5" }, { ...
lib/issues.coffee
mark-hahn/issues
0
fs = require 'fs' request = require 'request' token = '207e2ec811c24123b8e483b784534d3c690084e5' outFilePfx = 'data/comments-' module.exports = activate: -> console.log 'start issues' # # atom.workspace.open('issues.txt').then (editor) -> firstPage = 1 lastPage = 100 page = firstPage - 1 padChars = (num, len, chr = ' ') -> num = '' + num while num.length < len then num = chr + num num do oneIssuesPage = -> if ++page > lastPage console.log 'issues done' return filePath = outFilePfx + padChars(page, 4, '0') + '.txt' if fs.existsSync filePath then oneIssuesPage(); return url = "https://api.github.com/repos/atom/atom/issues" + "?filter=all" + "&page=" + page options = url: url method: 'GET' headers: "User-Agent": "mark-hahn-issue-stats-app" Authorization: 'token ' + token json: true request options, (err, res, body) => if not body.length then oneIssuesPage(); return pageHdr = '\n# page: ' + page + ', date: ' + body[0].created_at[0...10] + ', count: ' + body.length + ', rateLimit: ' + res.headers['x-ratelimit-remaining'] + ' of ' + res.headers['x-ratelimit-limit'] + '\n\n' console.log pageHdr fs.appendFileSync filePath, pageHdr do oneIssue = -> if not (issue = body.shift()) process.nextTick oneIssuesPage return options.url = "https://api.github.com/repos/atom/atom/issues/#{issue.number}/comments" request options, (err, res, body) => if body.message then console.log 'comment error:', body.message else for comment in body fs.appendFileSync filePath, ' ' + padChars(comment.body.length, 4) + '-' + comment.id + '-' + issue.number + ' ' + comment.body[0..100].replace(/\s+/g, ' ') + '\n' process.nextTick oneIssue
62377
fs = require 'fs' request = require 'request' token = '<KEY>' outFilePfx = 'data/comments-' module.exports = activate: -> console.log 'start issues' # # atom.workspace.open('issues.txt').then (editor) -> firstPage = 1 lastPage = 100 page = firstPage - 1 padChars = (num, len, chr = ' ') -> num = '' + num while num.length < len then num = chr + num num do oneIssuesPage = -> if ++page > lastPage console.log 'issues done' return filePath = outFilePfx + padChars(page, 4, '0') + '.txt' if fs.existsSync filePath then oneIssuesPage(); return url = "https://api.github.com/repos/atom/atom/issues" + "?filter=all" + "&page=" + page options = url: url method: 'GET' headers: "User-Agent": "mark-hahn-issue-stats-app" Authorization: 'token ' + token json: true request options, (err, res, body) => if not body.length then oneIssuesPage(); return pageHdr = '\n# page: ' + page + ', date: ' + body[0].created_at[0...10] + ', count: ' + body.length + ', rateLimit: ' + res.headers['x-ratelimit-remaining'] + ' of ' + res.headers['x-ratelimit-limit'] + '\n\n' console.log pageHdr fs.appendFileSync filePath, pageHdr do oneIssue = -> if not (issue = body.shift()) process.nextTick oneIssuesPage return options.url = "https://api.github.com/repos/atom/atom/issues/#{issue.number}/comments" request options, (err, res, body) => if body.message then console.log 'comment error:', body.message else for comment in body fs.appendFileSync filePath, ' ' + padChars(comment.body.length, 4) + '-' + comment.id + '-' + issue.number + ' ' + comment.body[0..100].replace(/\s+/g, ' ') + '\n' process.nextTick oneIssue
true
fs = require 'fs' request = require 'request' token = 'PI:KEY:<KEY>END_PI' outFilePfx = 'data/comments-' module.exports = activate: -> console.log 'start issues' # # atom.workspace.open('issues.txt').then (editor) -> firstPage = 1 lastPage = 100 page = firstPage - 1 padChars = (num, len, chr = ' ') -> num = '' + num while num.length < len then num = chr + num num do oneIssuesPage = -> if ++page > lastPage console.log 'issues done' return filePath = outFilePfx + padChars(page, 4, '0') + '.txt' if fs.existsSync filePath then oneIssuesPage(); return url = "https://api.github.com/repos/atom/atom/issues" + "?filter=all" + "&page=" + page options = url: url method: 'GET' headers: "User-Agent": "mark-hahn-issue-stats-app" Authorization: 'token ' + token json: true request options, (err, res, body) => if not body.length then oneIssuesPage(); return pageHdr = '\n# page: ' + page + ', date: ' + body[0].created_at[0...10] + ', count: ' + body.length + ', rateLimit: ' + res.headers['x-ratelimit-remaining'] + ' of ' + res.headers['x-ratelimit-limit'] + '\n\n' console.log pageHdr fs.appendFileSync filePath, pageHdr do oneIssue = -> if not (issue = body.shift()) process.nextTick oneIssuesPage return options.url = "https://api.github.com/repos/atom/atom/issues/#{issue.number}/comments" request options, (err, res, body) => if body.message then console.log 'comment error:', body.message else for comment in body fs.appendFileSync filePath, ' ' + padChars(comment.body.length, 4) + '-' + comment.id + '-' + issue.number + ' ' + comment.body[0..100].replace(/\s+/g, ' ') + '\n' process.nextTick oneIssue
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.8465107083320618, "start": 16, "tag": "NAME", "value": "Konode" }, { "context": ".allow('')\n\t\t\tcolorKeyHex: Joi.string().regex(/^#[A-Fa-f0-9]{6}/)\n\t\t\tstatus: ['defa...
src/persist/dataModels.coffee
LogicalOutcomes/KoNote
1
# Copyright (c) Konode. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 Joi = require 'joi' ApiBuilder = require './apiBuilder' {IdSchema, TimestampFormat} = require './utils' dataModelDefinitions = [ { name: 'clientFile' collectionName: 'clientFiles' isMutable: true indexes: [ ['status'] ['clientName', 'first'] ['clientName', 'middle'] ['clientName', 'last'] ['recordId'] ] schema: Joi.object().keys({ clientName: Joi.object().keys({ first: Joi.string() middle: Joi.string().allow('') last: Joi.string() }) birthDate: Joi.date().format('YYYYMMMDD').raw().allow('') status: ['active', 'inactive', 'discharged'] statusReason: Joi.string().optional() recordId: [Joi.string(), ''] plan: Joi.object().keys({ sections: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() status: ['default', 'deactivated', 'completed'] statusReason: Joi.string().optional() programId: IdSchema.allow('') targetIds: Joi.array().items( IdSchema ) }) ) }) detailUnits: Joi.array().items( Joi.object().keys({ groupId: IdSchema fieldId: IdSchema value: Joi.string().allow('') }) ) }) children: [ { name: 'progEvent' collectionName: 'progEvents' isMutable: true indexes: [['status'], ['relatedProgNoteId']] schema: Joi.object().keys({ title: Joi.string().allow('') description: Joi.string().allow('') startTimestamp: Joi.date().format(TimestampFormat).raw() endTimestamp: Joi.date().format(TimestampFormat).raw().allow('') typeId: IdSchema.allow('') relatedProgNoteId: IdSchema authorProgramId: IdSchema.allow('') backdate: Joi.date().format(TimestampFormat).raw().allow('') status: ['default', 'cancelled'] statusReason: Joi.string().optional() }) } { name: 'planTarget' collectionName: 'planTargets' isMutable: true indexes: [['status']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') status: ['default', 'deactivated', 'completed'] statusReason: Joi.string().optional() metricIds: Joi.array().items( IdSchema ) }) } { name: 'progNote' collectionName: 'progNotes' isMutable: true indexes: [['status'], ['timestamp'], ['backdate']] schema: [ Joi.object().keys({ type: 'basic' # aka "Quick Notes" status: ['default', 'cancelled'] statusReason: Joi.string().optional() notes: Joi.string() backdate: Joi.date().format(TimestampFormat).raw().allow('') authorProgramId: IdSchema.allow('') beginTimestamp: Joi.date().format(TimestampFormat).raw().allow('') summary: Joi.string().allow('').optional() }) Joi.object().keys({ type: 'full' status: ['default', 'cancelled'] statusReason: Joi.string().optional() templateId: IdSchema backdate: Joi.date().format(TimestampFormat).raw().allow('') authorProgramId: IdSchema.allow('') beginTimestamp: Joi.date().format(TimestampFormat).raw().allow('') summary: Joi.string().allow('').optional() units: Joi.array().items( [ Joi.object().keys({ id: IdSchema type: 'basic' name: Joi.string() notes: Joi.string().allow('') metrics: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() definition: Joi.string() value: Joi.string().allow('') }) ) }) Joi.object().keys({ id: IdSchema type: 'plan' name: Joi.string() sections: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() targets: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() description: Joi.string().allow('') notes: Joi.string().allow('') metrics: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() definition: Joi.string() value: Joi.string().allow('') }) ) }) ) }) ) }) ] ) }) ] } { name: 'alert' collectionName: 'alerts' isMutable: true indexes: [['status']] schema: Joi.object().keys({ content: Joi.string().allow('') updateReason: Joi.string().optional() status: ['default', 'cancelled'] statusReason: Joi.string().optional() authorProgramId: IdSchema.allow('') }) } { name: 'attachment' collectionName: 'attachments' isMutable: true indexes: [['filename'], ['status'], ['relatedProgNoteId']] schema: Joi.object().keys({ filename: Joi.string() encodedData: Joi.string() status: ['default', 'cancelled'] statusReason: Joi.string().optional() relatedProgNoteId: IdSchema }) } ] } { name: 'clientDetailDefinitionGroup' collectionName: 'clientDetailDefinitionGroups' isMutable: true indexes: [['status']] schema: Joi.object().keys({ title: Joi.string() status: ['default', 'cancelled'] fields: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() inputType: ['input', 'textarea'] # height, width, max length? etc placeholder: Joi.string().allow('') }) ) }) } { name: 'progNoteTemplate' collectionName: 'progNoteTemplates' isMutable: true indexes: [['name']] schema: Joi.object().keys({ name: Joi.string() sections: Joi.array().items( [ Joi.object().keys({ type: 'basic' name: Joi.string() metricIds: Joi.array().items( IdSchema ) }) Joi.object().keys({ type: 'plan' name: Joi.string() }) ] ) }) } { name: 'planTemplate' collectionName: 'planTemplates' isMutable: true indexes: [['status'], ['name']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') status: ['default', 'cancelled'] sections: Joi.array().items( [ Joi.object().keys({ name: Joi.string() programId: IdSchema.allow('') targets: Joi.array().items( name: Joi.string() description: Joi.string().allow('') metricIds: Joi.array().items( IdSchema ) ) }) ] ) }) } { name: 'metric' collectionName: 'metrics' isMutable: true indexes: [['status'], ['name'], ['customId']] schema: Joi.object().keys({ name: Joi.string() definition: Joi.string() customId: Joi.string().allow('') status: ['default', 'deactivated'] }) } { name: 'program' collectionName: 'programs' isMutable: true indexes: [['status'], ['name'], ['colorKeyHex']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') colorKeyHex: Joi.string().regex(/^#[A-Fa-f0-9]{6}/) status: ['default', 'cancelled'] }) } { name: 'eventType' collectionName: 'eventTypes' isMutable: true indexes: [['status']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string() colorKeyHex: Joi.string().regex(/^#[A-Fa-f0-9]{6}/) status: ['default', 'cancelled'] }) } ## Program Links { name: 'clientFileProgramLink' collectionName: 'clientFileProgramLinks' isMutable: true indexes: [['status'], ['clientFileId'], ['programId']] schema: Joi.object().keys({ clientFileId: IdSchema programId: IdSchema status: ['enrolled', 'unenrolled'] }) } { name: 'userProgramLink' collectionName: 'userProgramLinks' isMutable: true indexes: [['status'], ['userName'], ['programId']] schema: Joi.object().keys({ userName: IdSchema programId: IdSchema status: ['assigned', 'unassigned'] }) } { name: 'globalEvent' collectionName: 'globalEvents' isMutable: true indexes: [['status'], ['backdate']] schema: Joi.object().keys({ title: Joi.string().allow('') description: Joi.string().allow('') startTimestamp: Joi.date().format(TimestampFormat).raw() endTimestamp: Joi.date().format(TimestampFormat).raw().allow('') typeId: IdSchema.allow('') clientFileId: IdSchema relatedProgNoteId: IdSchema.allow('') relatedProgEventId: IdSchema.allow('') programId: IdSchema.allow('') backdate: Joi.date().format(TimestampFormat).raw().allow('') status: ['default', 'cancelled'] statusReason: Joi.string().optional() }) } ] getApi = (backendConfig, session) -> return ApiBuilder.buildApi backendConfig, session, dataModelDefinitions module.exports = {dataModelDefinitions, getApi}
144662
# Copyright (c) <NAME>. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 Joi = require 'joi' ApiBuilder = require './apiBuilder' {IdSchema, TimestampFormat} = require './utils' dataModelDefinitions = [ { name: 'clientFile' collectionName: 'clientFiles' isMutable: true indexes: [ ['status'] ['clientName', 'first'] ['clientName', 'middle'] ['clientName', 'last'] ['recordId'] ] schema: Joi.object().keys({ clientName: Joi.object().keys({ first: Joi.string() middle: Joi.string().allow('') last: Joi.string() }) birthDate: Joi.date().format('YYYYMMMDD').raw().allow('') status: ['active', 'inactive', 'discharged'] statusReason: Joi.string().optional() recordId: [Joi.string(), ''] plan: Joi.object().keys({ sections: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() status: ['default', 'deactivated', 'completed'] statusReason: Joi.string().optional() programId: IdSchema.allow('') targetIds: Joi.array().items( IdSchema ) }) ) }) detailUnits: Joi.array().items( Joi.object().keys({ groupId: IdSchema fieldId: IdSchema value: Joi.string().allow('') }) ) }) children: [ { name: 'progEvent' collectionName: 'progEvents' isMutable: true indexes: [['status'], ['relatedProgNoteId']] schema: Joi.object().keys({ title: Joi.string().allow('') description: Joi.string().allow('') startTimestamp: Joi.date().format(TimestampFormat).raw() endTimestamp: Joi.date().format(TimestampFormat).raw().allow('') typeId: IdSchema.allow('') relatedProgNoteId: IdSchema authorProgramId: IdSchema.allow('') backdate: Joi.date().format(TimestampFormat).raw().allow('') status: ['default', 'cancelled'] statusReason: Joi.string().optional() }) } { name: 'planTarget' collectionName: 'planTargets' isMutable: true indexes: [['status']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') status: ['default', 'deactivated', 'completed'] statusReason: Joi.string().optional() metricIds: Joi.array().items( IdSchema ) }) } { name: 'progNote' collectionName: 'progNotes' isMutable: true indexes: [['status'], ['timestamp'], ['backdate']] schema: [ Joi.object().keys({ type: 'basic' # aka "Quick Notes" status: ['default', 'cancelled'] statusReason: Joi.string().optional() notes: Joi.string() backdate: Joi.date().format(TimestampFormat).raw().allow('') authorProgramId: IdSchema.allow('') beginTimestamp: Joi.date().format(TimestampFormat).raw().allow('') summary: Joi.string().allow('').optional() }) Joi.object().keys({ type: 'full' status: ['default', 'cancelled'] statusReason: Joi.string().optional() templateId: IdSchema backdate: Joi.date().format(TimestampFormat).raw().allow('') authorProgramId: IdSchema.allow('') beginTimestamp: Joi.date().format(TimestampFormat).raw().allow('') summary: Joi.string().allow('').optional() units: Joi.array().items( [ Joi.object().keys({ id: IdSchema type: 'basic' name: Joi.string() notes: Joi.string().allow('') metrics: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() definition: Joi.string() value: Joi.string().allow('') }) ) }) Joi.object().keys({ id: IdSchema type: 'plan' name: Joi.string() sections: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() targets: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() description: Joi.string().allow('') notes: Joi.string().allow('') metrics: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() definition: Joi.string() value: Joi.string().allow('') }) ) }) ) }) ) }) ] ) }) ] } { name: 'alert' collectionName: 'alerts' isMutable: true indexes: [['status']] schema: Joi.object().keys({ content: Joi.string().allow('') updateReason: Joi.string().optional() status: ['default', 'cancelled'] statusReason: Joi.string().optional() authorProgramId: IdSchema.allow('') }) } { name: 'attachment' collectionName: 'attachments' isMutable: true indexes: [['filename'], ['status'], ['relatedProgNoteId']] schema: Joi.object().keys({ filename: Joi.string() encodedData: Joi.string() status: ['default', 'cancelled'] statusReason: Joi.string().optional() relatedProgNoteId: IdSchema }) } ] } { name: 'clientDetailDefinitionGroup' collectionName: 'clientDetailDefinitionGroups' isMutable: true indexes: [['status']] schema: Joi.object().keys({ title: Joi.string() status: ['default', 'cancelled'] fields: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() inputType: ['input', 'textarea'] # height, width, max length? etc placeholder: Joi.string().allow('') }) ) }) } { name: 'progNoteTemplate' collectionName: 'progNoteTemplates' isMutable: true indexes: [['name']] schema: Joi.object().keys({ name: Joi.string() sections: Joi.array().items( [ Joi.object().keys({ type: 'basic' name: Joi.string() metricIds: Joi.array().items( IdSchema ) }) Joi.object().keys({ type: 'plan' name: Joi.string() }) ] ) }) } { name: 'planTemplate' collectionName: 'planTemplates' isMutable: true indexes: [['status'], ['name']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') status: ['default', 'cancelled'] sections: Joi.array().items( [ Joi.object().keys({ name: Joi.string() programId: IdSchema.allow('') targets: Joi.array().items( name: Joi.string() description: Joi.string().allow('') metricIds: Joi.array().items( IdSchema ) ) }) ] ) }) } { name: 'metric' collectionName: 'metrics' isMutable: true indexes: [['status'], ['name'], ['customId']] schema: Joi.object().keys({ name: Joi.string() definition: Joi.string() customId: Joi.string().allow('') status: ['default', 'deactivated'] }) } { name: 'program' collectionName: 'programs' isMutable: true indexes: [['status'], ['name'], ['colorKeyHex']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') colorKeyHex: Joi.string().regex(/^#[<KEY>]{6}/) status: ['default', 'cancelled'] }) } { name: 'eventType' collectionName: 'eventTypes' isMutable: true indexes: [['status']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string() colorKeyHex: Joi.string().regex(/^#[<KEY>]{6}/) status: ['default', 'cancelled'] }) } ## Program Links { name: 'clientFileProgramLink' collectionName: 'clientFileProgramLinks' isMutable: true indexes: [['status'], ['clientFileId'], ['programId']] schema: Joi.object().keys({ clientFileId: IdSchema programId: IdSchema status: ['enrolled', 'unenrolled'] }) } { name: 'userProgramLink' collectionName: 'userProgramLinks' isMutable: true indexes: [['status'], ['userName'], ['programId']] schema: Joi.object().keys({ userName: IdSchema programId: IdSchema status: ['assigned', 'unassigned'] }) } { name: 'globalEvent' collectionName: 'globalEvents' isMutable: true indexes: [['status'], ['backdate']] schema: Joi.object().keys({ title: Joi.string().allow('') description: Joi.string().allow('') startTimestamp: Joi.date().format(TimestampFormat).raw() endTimestamp: Joi.date().format(TimestampFormat).raw().allow('') typeId: IdSchema.allow('') clientFileId: IdSchema relatedProgNoteId: IdSchema.allow('') relatedProgEventId: IdSchema.allow('') programId: IdSchema.allow('') backdate: Joi.date().format(TimestampFormat).raw().allow('') status: ['default', 'cancelled'] statusReason: Joi.string().optional() }) } ] getApi = (backendConfig, session) -> return ApiBuilder.buildApi backendConfig, session, dataModelDefinitions module.exports = {dataModelDefinitions, getApi}
true
# Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 Joi = require 'joi' ApiBuilder = require './apiBuilder' {IdSchema, TimestampFormat} = require './utils' dataModelDefinitions = [ { name: 'clientFile' collectionName: 'clientFiles' isMutable: true indexes: [ ['status'] ['clientName', 'first'] ['clientName', 'middle'] ['clientName', 'last'] ['recordId'] ] schema: Joi.object().keys({ clientName: Joi.object().keys({ first: Joi.string() middle: Joi.string().allow('') last: Joi.string() }) birthDate: Joi.date().format('YYYYMMMDD').raw().allow('') status: ['active', 'inactive', 'discharged'] statusReason: Joi.string().optional() recordId: [Joi.string(), ''] plan: Joi.object().keys({ sections: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() status: ['default', 'deactivated', 'completed'] statusReason: Joi.string().optional() programId: IdSchema.allow('') targetIds: Joi.array().items( IdSchema ) }) ) }) detailUnits: Joi.array().items( Joi.object().keys({ groupId: IdSchema fieldId: IdSchema value: Joi.string().allow('') }) ) }) children: [ { name: 'progEvent' collectionName: 'progEvents' isMutable: true indexes: [['status'], ['relatedProgNoteId']] schema: Joi.object().keys({ title: Joi.string().allow('') description: Joi.string().allow('') startTimestamp: Joi.date().format(TimestampFormat).raw() endTimestamp: Joi.date().format(TimestampFormat).raw().allow('') typeId: IdSchema.allow('') relatedProgNoteId: IdSchema authorProgramId: IdSchema.allow('') backdate: Joi.date().format(TimestampFormat).raw().allow('') status: ['default', 'cancelled'] statusReason: Joi.string().optional() }) } { name: 'planTarget' collectionName: 'planTargets' isMutable: true indexes: [['status']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') status: ['default', 'deactivated', 'completed'] statusReason: Joi.string().optional() metricIds: Joi.array().items( IdSchema ) }) } { name: 'progNote' collectionName: 'progNotes' isMutable: true indexes: [['status'], ['timestamp'], ['backdate']] schema: [ Joi.object().keys({ type: 'basic' # aka "Quick Notes" status: ['default', 'cancelled'] statusReason: Joi.string().optional() notes: Joi.string() backdate: Joi.date().format(TimestampFormat).raw().allow('') authorProgramId: IdSchema.allow('') beginTimestamp: Joi.date().format(TimestampFormat).raw().allow('') summary: Joi.string().allow('').optional() }) Joi.object().keys({ type: 'full' status: ['default', 'cancelled'] statusReason: Joi.string().optional() templateId: IdSchema backdate: Joi.date().format(TimestampFormat).raw().allow('') authorProgramId: IdSchema.allow('') beginTimestamp: Joi.date().format(TimestampFormat).raw().allow('') summary: Joi.string().allow('').optional() units: Joi.array().items( [ Joi.object().keys({ id: IdSchema type: 'basic' name: Joi.string() notes: Joi.string().allow('') metrics: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() definition: Joi.string() value: Joi.string().allow('') }) ) }) Joi.object().keys({ id: IdSchema type: 'plan' name: Joi.string() sections: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() targets: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() description: Joi.string().allow('') notes: Joi.string().allow('') metrics: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() definition: Joi.string() value: Joi.string().allow('') }) ) }) ) }) ) }) ] ) }) ] } { name: 'alert' collectionName: 'alerts' isMutable: true indexes: [['status']] schema: Joi.object().keys({ content: Joi.string().allow('') updateReason: Joi.string().optional() status: ['default', 'cancelled'] statusReason: Joi.string().optional() authorProgramId: IdSchema.allow('') }) } { name: 'attachment' collectionName: 'attachments' isMutable: true indexes: [['filename'], ['status'], ['relatedProgNoteId']] schema: Joi.object().keys({ filename: Joi.string() encodedData: Joi.string() status: ['default', 'cancelled'] statusReason: Joi.string().optional() relatedProgNoteId: IdSchema }) } ] } { name: 'clientDetailDefinitionGroup' collectionName: 'clientDetailDefinitionGroups' isMutable: true indexes: [['status']] schema: Joi.object().keys({ title: Joi.string() status: ['default', 'cancelled'] fields: Joi.array().items( Joi.object().keys({ id: IdSchema name: Joi.string() inputType: ['input', 'textarea'] # height, width, max length? etc placeholder: Joi.string().allow('') }) ) }) } { name: 'progNoteTemplate' collectionName: 'progNoteTemplates' isMutable: true indexes: [['name']] schema: Joi.object().keys({ name: Joi.string() sections: Joi.array().items( [ Joi.object().keys({ type: 'basic' name: Joi.string() metricIds: Joi.array().items( IdSchema ) }) Joi.object().keys({ type: 'plan' name: Joi.string() }) ] ) }) } { name: 'planTemplate' collectionName: 'planTemplates' isMutable: true indexes: [['status'], ['name']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') status: ['default', 'cancelled'] sections: Joi.array().items( [ Joi.object().keys({ name: Joi.string() programId: IdSchema.allow('') targets: Joi.array().items( name: Joi.string() description: Joi.string().allow('') metricIds: Joi.array().items( IdSchema ) ) }) ] ) }) } { name: 'metric' collectionName: 'metrics' isMutable: true indexes: [['status'], ['name'], ['customId']] schema: Joi.object().keys({ name: Joi.string() definition: Joi.string() customId: Joi.string().allow('') status: ['default', 'deactivated'] }) } { name: 'program' collectionName: 'programs' isMutable: true indexes: [['status'], ['name'], ['colorKeyHex']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string().allow('') colorKeyHex: Joi.string().regex(/^#[PI:KEY:<KEY>END_PI]{6}/) status: ['default', 'cancelled'] }) } { name: 'eventType' collectionName: 'eventTypes' isMutable: true indexes: [['status']] schema: Joi.object().keys({ name: Joi.string() description: Joi.string() colorKeyHex: Joi.string().regex(/^#[PI:KEY:<KEY>END_PI]{6}/) status: ['default', 'cancelled'] }) } ## Program Links { name: 'clientFileProgramLink' collectionName: 'clientFileProgramLinks' isMutable: true indexes: [['status'], ['clientFileId'], ['programId']] schema: Joi.object().keys({ clientFileId: IdSchema programId: IdSchema status: ['enrolled', 'unenrolled'] }) } { name: 'userProgramLink' collectionName: 'userProgramLinks' isMutable: true indexes: [['status'], ['userName'], ['programId']] schema: Joi.object().keys({ userName: IdSchema programId: IdSchema status: ['assigned', 'unassigned'] }) } { name: 'globalEvent' collectionName: 'globalEvents' isMutable: true indexes: [['status'], ['backdate']] schema: Joi.object().keys({ title: Joi.string().allow('') description: Joi.string().allow('') startTimestamp: Joi.date().format(TimestampFormat).raw() endTimestamp: Joi.date().format(TimestampFormat).raw().allow('') typeId: IdSchema.allow('') clientFileId: IdSchema relatedProgNoteId: IdSchema.allow('') relatedProgEventId: IdSchema.allow('') programId: IdSchema.allow('') backdate: Joi.date().format(TimestampFormat).raw().allow('') status: ['default', 'cancelled'] statusReason: Joi.string().optional() }) } ] getApi = (backendConfig, session) -> return ApiBuilder.buildApi backendConfig, session, dataModelDefinitions module.exports = {dataModelDefinitions, getApi}
[ { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L", "end": 35, "score": 0.999875009059906, "start": 21, "tag": "NAME", "value": "JeongHoon Byun" }, { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.ou...
test/parser/csharp-parser.test.coffee
uppalapatisujitha/CodingConventionofCommitHistory
421
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/csharp-parser' describe 'C#-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'public String getName{}', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' public String getName{}', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' public String getName{}', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\tpublic String getName{}', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\tpublic String getName{}', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t public String getName{} ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \tpublic String getName{}', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'public String getName{}', {} convention.indent.tab.should.equal 0 describe 'blockstatement >', -> it 'check block statement with one space #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT) { return; }', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #2', -> convention = parser.blockstatement '} else if (height < MIN_HIGHT) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #3', -> convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #4', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #5', -> convention = parser.blockstatement 'if (height < MIN_HIGHT){ return; }', {} convention.blockstatement.onespace.should.equal 0 it 'check block statement with one space #6', -> convention = parser.blockstatement 'if (isTrue()) { return; }', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with no space #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT){ return (); }', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement with no space #2', -> convention = parser.blockstatement '}else if (height < MIN_HIGHT){', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement with no space #3', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)', {} convention.blockstatement.nospace.should.equal 0 it 'check block statement with no space #4', -> convention = parser.blockstatement '} else if(height < MIN_HIGHT) {', {} convention.blockstatement.nospace.should.equal 0 it 'check block statement with no space #5', -> convention = parser.blockstatement '} else if(isTrue()){', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement at new line #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #2', -> convention = parser.blockstatement 'if (height < MIN_HIGHT) // comment', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #3', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)/* */', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #4', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT)', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #5', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #6', -> convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {} convention.blockstatement.newline.should.equal 0 it 'check block statement at new line #7', -> convention = parser.blockstatement 'if ( isTrue() ) //{}', {} convention.blockstatement.newline.should.equal 1 describe 'constant >', -> it 'check constant is pascal #1', -> convention = parser.constant 'const string FooBar = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #2', -> convention = parser.constant 'const int Foo = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #3', -> convention = parser.constant 'public const int Foo = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #4', -> convention = parser.constant 'const string FOO_BAR = "baz";', {} convention.constant.pascal.should.equal 0 it 'check constant with all caps #1', -> convention = parser.constant 'const string FOO_BAR = "baz";', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #2', -> convention = parser.constant 'public const iint FOO_BAR = 1;', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #3', -> convention = parser.constant 'const iint X = 1;', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #4', -> convention = parser.constant 'const string fooBar = "baz";', {} convention.constant.allcaps.should.equal 0 it 'check constant with not all caps #1', -> convention = parser.constant ' const string foo_bar = "baz";', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #2', -> convention = parser.constant ' const string fooBar = "baz";', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #3', -> convention = parser.constant 'public const int fooBar = 1;', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #4', -> convention = parser.constant 'const int x=1;', {} convention.constant.notallcaps.should.equal 1 describe 'conditionstatement >', -> it 'check condition statement with one space #1', -> convention = parser.conditionstatement 'if ( a.equal("")) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #2', -> convention = parser.conditionstatement 'while ( isTrue() ) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #3', -> convention = parser.conditionstatement 'switch (name) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #4', -> convention = parser.conditionstatement 'if( isTrue()) {', {} convention.conditionstatement.onespace.should.equal 0 it 'check condition statement with no space #1', -> convention = parser.conditionstatement 'if( isTrue()) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #2', -> convention = parser.conditionstatement 'while( isTrue() ) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #3', -> convention = parser.conditionstatement 'switch(name) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #4', -> convention = parser.conditionstatement 'if ( a.equal("")) {', {} convention.conditionstatement.nospace.should.equal 0 describe 'argumentdef >', -> it 'check argument definition with one space #1', -> convention = parser.argumentdef 'public void SetName11( String name ) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #2', -> convention = parser.argumentdef ' public void SetName( String name ) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #3', -> convention = parser.argumentdef '\t\tpublic void SetName( String name, Sting age) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #4', -> convention = parser.argumentdef 'if ( isTrue() ) {}', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #5', -> convention = parser.argumentdef 'while ( isTrue() ) {}', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #6', -> convention = parser.argumentdef 'public void SetName11(String name ) {', {} convention.argumentdef.onespace.should.equal 0 it 'check argument definition with no space #1', -> convention = parser.argumentdef 'public void SetName(String name) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #2', -> convention = parser.argumentdef '\t\tpublic void SetName(String name) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #3', -> convention = parser.argumentdef 'public void SetName(String name, Sting age) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #4', -> convention = parser.argumentdef 'if (isTrue()) {}', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #5', -> convention = parser.argumentdef 'while (isTrue()) {}', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #6', -> convention = parser.argumentdef '/t/tpublic void SetName( String name) {', {} convention.argumentdef.nospace.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1
52720
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/csharp-parser' describe 'C#-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'public String getName{}', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' public String getName{}', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' public String getName{}', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\tpublic String getName{}', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\tpublic String getName{}', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t public String getName{} ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \tpublic String getName{}', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'public String getName{}', {} convention.indent.tab.should.equal 0 describe 'blockstatement >', -> it 'check block statement with one space #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT) { return; }', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #2', -> convention = parser.blockstatement '} else if (height < MIN_HIGHT) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #3', -> convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #4', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #5', -> convention = parser.blockstatement 'if (height < MIN_HIGHT){ return; }', {} convention.blockstatement.onespace.should.equal 0 it 'check block statement with one space #6', -> convention = parser.blockstatement 'if (isTrue()) { return; }', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with no space #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT){ return (); }', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement with no space #2', -> convention = parser.blockstatement '}else if (height < MIN_HIGHT){', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement with no space #3', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)', {} convention.blockstatement.nospace.should.equal 0 it 'check block statement with no space #4', -> convention = parser.blockstatement '} else if(height < MIN_HIGHT) {', {} convention.blockstatement.nospace.should.equal 0 it 'check block statement with no space #5', -> convention = parser.blockstatement '} else if(isTrue()){', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement at new line #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #2', -> convention = parser.blockstatement 'if (height < MIN_HIGHT) // comment', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #3', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)/* */', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #4', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT)', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #5', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #6', -> convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {} convention.blockstatement.newline.should.equal 0 it 'check block statement at new line #7', -> convention = parser.blockstatement 'if ( isTrue() ) //{}', {} convention.blockstatement.newline.should.equal 1 describe 'constant >', -> it 'check constant is pascal #1', -> convention = parser.constant 'const string FooBar = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #2', -> convention = parser.constant 'const int Foo = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #3', -> convention = parser.constant 'public const int Foo = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #4', -> convention = parser.constant 'const string FOO_BAR = "baz";', {} convention.constant.pascal.should.equal 0 it 'check constant with all caps #1', -> convention = parser.constant 'const string FOO_BAR = "baz";', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #2', -> convention = parser.constant 'public const iint FOO_BAR = 1;', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #3', -> convention = parser.constant 'const iint X = 1;', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #4', -> convention = parser.constant 'const string fooBar = "baz";', {} convention.constant.allcaps.should.equal 0 it 'check constant with not all caps #1', -> convention = parser.constant ' const string foo_bar = "baz";', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #2', -> convention = parser.constant ' const string fooBar = "baz";', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #3', -> convention = parser.constant 'public const int fooBar = 1;', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #4', -> convention = parser.constant 'const int x=1;', {} convention.constant.notallcaps.should.equal 1 describe 'conditionstatement >', -> it 'check condition statement with one space #1', -> convention = parser.conditionstatement 'if ( a.equal("")) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #2', -> convention = parser.conditionstatement 'while ( isTrue() ) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #3', -> convention = parser.conditionstatement 'switch (name) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #4', -> convention = parser.conditionstatement 'if( isTrue()) {', {} convention.conditionstatement.onespace.should.equal 0 it 'check condition statement with no space #1', -> convention = parser.conditionstatement 'if( isTrue()) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #2', -> convention = parser.conditionstatement 'while( isTrue() ) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #3', -> convention = parser.conditionstatement 'switch(name) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #4', -> convention = parser.conditionstatement 'if ( a.equal("")) {', {} convention.conditionstatement.nospace.should.equal 0 describe 'argumentdef >', -> it 'check argument definition with one space #1', -> convention = parser.argumentdef 'public void SetName11( String name ) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #2', -> convention = parser.argumentdef ' public void SetName( String name ) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #3', -> convention = parser.argumentdef '\t\tpublic void SetName( String name, Sting age) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #4', -> convention = parser.argumentdef 'if ( isTrue() ) {}', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #5', -> convention = parser.argumentdef 'while ( isTrue() ) {}', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #6', -> convention = parser.argumentdef 'public void SetName11(String name ) {', {} convention.argumentdef.onespace.should.equal 0 it 'check argument definition with no space #1', -> convention = parser.argumentdef 'public void SetName(String name) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #2', -> convention = parser.argumentdef '\t\tpublic void SetName(String name) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #3', -> convention = parser.argumentdef 'public void SetName(String name, Sting age) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #4', -> convention = parser.argumentdef 'if (isTrue()) {}', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #5', -> convention = parser.argumentdef 'while (isTrue()) {}', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #6', -> convention = parser.argumentdef '/t/tpublic void SetName( String name) {', {} convention.argumentdef.nospace.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1
true
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/csharp-parser' describe 'C#-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'public String getName{}', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' public String getName{}', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' public String getName{}', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\tpublic String getName{}', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\tpublic String getName{}', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t public String getName{} ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \tpublic String getName{}', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'public String getName{}', {} convention.indent.tab.should.equal 0 describe 'blockstatement >', -> it 'check block statement with one space #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT) { return; }', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #2', -> convention = parser.blockstatement '} else if (height < MIN_HIGHT) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #3', -> convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #4', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with one space #5', -> convention = parser.blockstatement 'if (height < MIN_HIGHT){ return; }', {} convention.blockstatement.onespace.should.equal 0 it 'check block statement with one space #6', -> convention = parser.blockstatement 'if (isTrue()) { return; }', {} convention.blockstatement.onespace.should.equal 1 it 'check block statement with no space #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT){ return (); }', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement with no space #2', -> convention = parser.blockstatement '}else if (height < MIN_HIGHT){', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement with no space #3', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)', {} convention.blockstatement.nospace.should.equal 0 it 'check block statement with no space #4', -> convention = parser.blockstatement '} else if(height < MIN_HIGHT) {', {} convention.blockstatement.nospace.should.equal 0 it 'check block statement with no space #5', -> convention = parser.blockstatement '} else if(isTrue()){', {} convention.blockstatement.nospace.should.equal 1 it 'check block statement at new line #1', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #2', -> convention = parser.blockstatement 'if (height < MIN_HIGHT) // comment', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #3', -> convention = parser.blockstatement 'if (height < MIN_HIGHT)/* */', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #4', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT)', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #5', -> convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {} convention.blockstatement.newline.should.equal 1 it 'check block statement at new line #6', -> convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {} convention.blockstatement.newline.should.equal 0 it 'check block statement at new line #7', -> convention = parser.blockstatement 'if ( isTrue() ) //{}', {} convention.blockstatement.newline.should.equal 1 describe 'constant >', -> it 'check constant is pascal #1', -> convention = parser.constant 'const string FooBar = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #2', -> convention = parser.constant 'const int Foo = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #3', -> convention = parser.constant 'public const int Foo = "baz";', {} convention.constant.pascal.should.equal 1 it 'check constant is pascal #4', -> convention = parser.constant 'const string FOO_BAR = "baz";', {} convention.constant.pascal.should.equal 0 it 'check constant with all caps #1', -> convention = parser.constant 'const string FOO_BAR = "baz";', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #2', -> convention = parser.constant 'public const iint FOO_BAR = 1;', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #3', -> convention = parser.constant 'const iint X = 1;', {} convention.constant.allcaps.should.equal 1 it 'check constant with all caps #4', -> convention = parser.constant 'const string fooBar = "baz";', {} convention.constant.allcaps.should.equal 0 it 'check constant with not all caps #1', -> convention = parser.constant ' const string foo_bar = "baz";', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #2', -> convention = parser.constant ' const string fooBar = "baz";', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #3', -> convention = parser.constant 'public const int fooBar = 1;', {} convention.constant.notallcaps.should.equal 1 it 'check constant with not all caps #4', -> convention = parser.constant 'const int x=1;', {} convention.constant.notallcaps.should.equal 1 describe 'conditionstatement >', -> it 'check condition statement with one space #1', -> convention = parser.conditionstatement 'if ( a.equal("")) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #2', -> convention = parser.conditionstatement 'while ( isTrue() ) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #3', -> convention = parser.conditionstatement 'switch (name) {', {} convention.conditionstatement.onespace.should.equal 1 it 'check condition statement with one space #4', -> convention = parser.conditionstatement 'if( isTrue()) {', {} convention.conditionstatement.onespace.should.equal 0 it 'check condition statement with no space #1', -> convention = parser.conditionstatement 'if( isTrue()) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #2', -> convention = parser.conditionstatement 'while( isTrue() ) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #3', -> convention = parser.conditionstatement 'switch(name) {', {} convention.conditionstatement.nospace.should.equal 1 it 'check condition statement with no space #4', -> convention = parser.conditionstatement 'if ( a.equal("")) {', {} convention.conditionstatement.nospace.should.equal 0 describe 'argumentdef >', -> it 'check argument definition with one space #1', -> convention = parser.argumentdef 'public void SetName11( String name ) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #2', -> convention = parser.argumentdef ' public void SetName( String name ) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #3', -> convention = parser.argumentdef '\t\tpublic void SetName( String name, Sting age) {', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #4', -> convention = parser.argumentdef 'if ( isTrue() ) {}', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #5', -> convention = parser.argumentdef 'while ( isTrue() ) {}', {} convention.argumentdef.onespace.should.equal 1 it 'check argument definition with one space #6', -> convention = parser.argumentdef 'public void SetName11(String name ) {', {} convention.argumentdef.onespace.should.equal 0 it 'check argument definition with no space #1', -> convention = parser.argumentdef 'public void SetName(String name) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #2', -> convention = parser.argumentdef '\t\tpublic void SetName(String name) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #3', -> convention = parser.argumentdef 'public void SetName(String name, Sting age) {', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #4', -> convention = parser.argumentdef 'if (isTrue()) {}', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #5', -> convention = parser.argumentdef 'while (isTrue()) {}', {} convention.argumentdef.nospace.should.equal 1 it 'check argument definition with no space #6', -> convention = parser.argumentdef '/t/tpublic void SetName( String name) {', {} convention.argumentdef.nospace.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1
[ { "context": "ainer\n\n data = [\n key: 'line1'\n type: 'line'\n val", "end": 358, "score": 0.9758151769638062, "start": 353, "tag": "KEY", "value": "line1" }, { "context": " ]\n ,\n key: 'li...
test/guideline.coffee
robinfhu/forest-d3
58
describe 'Chart', -> describe 'Guideline', -> chart = null container = null beforeEach -> container = document.createElement 'div' container.style.width = '500px' container.style.height = '400px' document.body.appendChild container data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,2] ] , key: 'line2' type: 'line' values: [ [0,2] [1,4] [2,6] ] ] chart = new ForestD3.Chart container chart .showGuideline(true) .data(data) .render() afterEach -> chart.destroy() it 'can render a guideline', -> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] line = $(container).find('g.canvas line.guideline') line.length.should.equal 1, 'line exists' line = line.get(0) line.getAttribute('x1').should.not.equal '0' line.getAttribute('x1').should.equal line.getAttribute('x2') it 'renders guideline marker circles along the guideline', -> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] markerContainer = $(container).find('g.canvas g.guideline-markers') markerContainer.length.should.equal 1, 'container exists' markers = markerContainer.find('circle.marker') markers.length.should.equal 2, 'two markers' it 'can hide guideline', (done)-> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] chart.updateTooltip hide: true setTimeout -> line = $(container).find('line.guideline') line.css('opacity').should.equal '0' done() , 1000
118028
describe 'Chart', -> describe 'Guideline', -> chart = null container = null beforeEach -> container = document.createElement 'div' container.style.width = '500px' container.style.height = '400px' document.body.appendChild container data = [ key: '<KEY>' type: 'line' values: [ [0,0] [1,1] [2,2] ] , key: '<KEY>' type: 'line' values: [ [0,2] [1,4] [2,6] ] ] chart = new ForestD3.Chart container chart .showGuideline(true) .data(data) .render() afterEach -> chart.destroy() it 'can render a guideline', -> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] line = $(container).find('g.canvas line.guideline') line.length.should.equal 1, 'line exists' line = line.get(0) line.getAttribute('x1').should.not.equal '0' line.getAttribute('x1').should.equal line.getAttribute('x2') it 'renders guideline marker circles along the guideline', -> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] markerContainer = $(container).find('g.canvas g.guideline-markers') markerContainer.length.should.equal 1, 'container exists' markers = markerContainer.find('circle.marker') markers.length.should.equal 2, 'two markers' it 'can hide guideline', (done)-> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] chart.updateTooltip hide: true setTimeout -> line = $(container).find('line.guideline') line.css('opacity').should.equal '0' done() , 1000
true
describe 'Chart', -> describe 'Guideline', -> chart = null container = null beforeEach -> container = document.createElement 'div' container.style.width = '500px' container.style.height = '400px' document.body.appendChild container data = [ key: 'PI:KEY:<KEY>END_PI' type: 'line' values: [ [0,0] [1,1] [2,2] ] , key: 'PI:KEY:<KEY>END_PI' type: 'line' values: [ [0,2] [1,4] [2,6] ] ] chart = new ForestD3.Chart container chart .showGuideline(true) .data(data) .render() afterEach -> chart.destroy() it 'can render a guideline', -> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] line = $(container).find('g.canvas line.guideline') line.length.should.equal 1, 'line exists' line = line.get(0) line.getAttribute('x1').should.not.equal '0' line.getAttribute('x1').should.equal line.getAttribute('x2') it 'renders guideline marker circles along the guideline', -> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] markerContainer = $(container).find('g.canvas g.guideline-markers') markerContainer.length.should.equal 1, 'container exists' markers = markerContainer.find('circle.marker') markers.length.should.equal 2, 'two markers' it 'can hide guideline', (done)-> chart.updateTooltip canvasMouse: [250, 200] clientMouse: [0,0] chart.updateTooltip hide: true setTimeout -> line = $(container).find('line.guideline') line.css('opacity').should.equal '0' done() , 1000
[ { "context": "he canvas\n #\n # @example\n # @drawImage(key: 'corb')\n # @drawImage(key: 'template')\n #\n drawIma", "end": 2965, "score": 0.9960185289382935, "start": 2961, "tag": "KEY", "value": "corb" } ]
src/3d/extra/ArtGenerator.coffee
mess110/coffee-engine
1
# Used to overlay stuff on a canvas. The canvas can be later used to create # a material. # # @see Helper.materialFromCanvas # # @example # @drawImage(key: 'corb') # @drawImage(key: 'template') # # @drawText(text: 'foo', y: 60, strokeStyle: 'black') # @drawBezier( # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # ) class ArtGenerator # @nodoc constructor: (options) -> @options = options @tm = TextureManager.get() @canvas = document.createElement( 'canvas' ) @canvas.width = options.width @canvas.height = options.height @ctx = @canvas.getContext( '2d' ) # @example # @art = new ArtGenerator( # width: 340 # height: 473 # ) # @art.fromJson items: [ # { # type: 'image' # key: 'corb' # } # { # type: 'image' # key: 'template' # } # { # type: 'text' # text: 'foo' # y: 60 # strokeStyle: 'black' # } # { # type: 'bezier' # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # } # ] fromJson: (json) -> @clear() for item in json.items if item.asset? && item.asset.key? item.key = item.asset.key if item.type == 'image' @drawImage(item) if item.type == 'text' @drawText(item) if item.type == 'bezier' @drawBezier(item) # Used to overlay a bezier curve on a canvas # # @see StackOverflow.drawBezier # @see draw bezier tool # # @example # @drawBezier( # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # ) drawBezier: (options) -> StackOverflow.drawBezier(options, @ctx) # Overlay text on a canvas # # @example # @drawText(text: 'foo', y: 60, strokeStyle: 'black') drawText: (options = {}) -> throw 'options.text missing' unless options.text? options.fillStyle ?= 'white' options.fillLineWidth ?= 1 options.strokeLineWidth ?= 7 options.strokeStyle ?= undefined # lol options.font ?= '40px Helvetica' options.x ?= 0 options.y ?= 0 options.angle ?= 0 @ctx.save() @ctx.font = options.font if options.angle != 0 @ctx.rotate(options.angle * Math.PI / 180) if options.strokeStyle? @ctx.miterLimit = 2 @ctx.lineJoin = 'circle' @ctx.strokeStyle = options.strokeStyle @ctx.lineWidth = options.strokeLineWidth @ctx.strokeText options.text, options.x, options.y @ctx.lineWidth = options.fillLineWidth @ctx.fillStyle = options.fillStyle @ctx.fillText options.text, options.x, options.y @ctx.restore() # Used to overlay an image on the canvas # # @example # @drawImage(key: 'corb') # @drawImage(key: 'template') # drawImage: (options = {}) -> throw 'key not found' unless options.key? options.x ?= 0 options.y ?= 0 options.angle ?= 0 x = options.x y = options.y image = @tm.items[options.key].image if options.angle != 0 @ctx.save() @ctx.translate(options.x + image.width / 2, options.y + image.height / 2) @ctx.rotate(options.angle * Math.PI / 180) x = -(image.width / 2) y = -(image.height / 2) @ctx.drawImage(image, x, y) if options.angle != 0 @ctx.restore() # clear the canvas context clear: -> @ctx.clearRect(0, 0, @options.width, @options.height)
205500
# Used to overlay stuff on a canvas. The canvas can be later used to create # a material. # # @see Helper.materialFromCanvas # # @example # @drawImage(key: 'corb') # @drawImage(key: 'template') # # @drawText(text: 'foo', y: 60, strokeStyle: 'black') # @drawBezier( # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # ) class ArtGenerator # @nodoc constructor: (options) -> @options = options @tm = TextureManager.get() @canvas = document.createElement( 'canvas' ) @canvas.width = options.width @canvas.height = options.height @ctx = @canvas.getContext( '2d' ) # @example # @art = new ArtGenerator( # width: 340 # height: 473 # ) # @art.fromJson items: [ # { # type: 'image' # key: 'corb' # } # { # type: 'image' # key: 'template' # } # { # type: 'text' # text: 'foo' # y: 60 # strokeStyle: 'black' # } # { # type: 'bezier' # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # } # ] fromJson: (json) -> @clear() for item in json.items if item.asset? && item.asset.key? item.key = item.asset.key if item.type == 'image' @drawImage(item) if item.type == 'text' @drawText(item) if item.type == 'bezier' @drawBezier(item) # Used to overlay a bezier curve on a canvas # # @see StackOverflow.drawBezier # @see draw bezier tool # # @example # @drawBezier( # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # ) drawBezier: (options) -> StackOverflow.drawBezier(options, @ctx) # Overlay text on a canvas # # @example # @drawText(text: 'foo', y: 60, strokeStyle: 'black') drawText: (options = {}) -> throw 'options.text missing' unless options.text? options.fillStyle ?= 'white' options.fillLineWidth ?= 1 options.strokeLineWidth ?= 7 options.strokeStyle ?= undefined # lol options.font ?= '40px Helvetica' options.x ?= 0 options.y ?= 0 options.angle ?= 0 @ctx.save() @ctx.font = options.font if options.angle != 0 @ctx.rotate(options.angle * Math.PI / 180) if options.strokeStyle? @ctx.miterLimit = 2 @ctx.lineJoin = 'circle' @ctx.strokeStyle = options.strokeStyle @ctx.lineWidth = options.strokeLineWidth @ctx.strokeText options.text, options.x, options.y @ctx.lineWidth = options.fillLineWidth @ctx.fillStyle = options.fillStyle @ctx.fillText options.text, options.x, options.y @ctx.restore() # Used to overlay an image on the canvas # # @example # @drawImage(key: '<KEY>') # @drawImage(key: 'template') # drawImage: (options = {}) -> throw 'key not found' unless options.key? options.x ?= 0 options.y ?= 0 options.angle ?= 0 x = options.x y = options.y image = @tm.items[options.key].image if options.angle != 0 @ctx.save() @ctx.translate(options.x + image.width / 2, options.y + image.height / 2) @ctx.rotate(options.angle * Math.PI / 180) x = -(image.width / 2) y = -(image.height / 2) @ctx.drawImage(image, x, y) if options.angle != 0 @ctx.restore() # clear the canvas context clear: -> @ctx.clearRect(0, 0, @options.width, @options.height)
true
# Used to overlay stuff on a canvas. The canvas can be later used to create # a material. # # @see Helper.materialFromCanvas # # @example # @drawImage(key: 'corb') # @drawImage(key: 'template') # # @drawText(text: 'foo', y: 60, strokeStyle: 'black') # @drawBezier( # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # ) class ArtGenerator # @nodoc constructor: (options) -> @options = options @tm = TextureManager.get() @canvas = document.createElement( 'canvas' ) @canvas.width = options.width @canvas.height = options.height @ctx = @canvas.getContext( '2d' ) # @example # @art = new ArtGenerator( # width: 340 # height: 473 # ) # @art.fromJson items: [ # { # type: 'image' # key: 'corb' # } # { # type: 'image' # key: 'template' # } # { # type: 'text' # text: 'foo' # y: 60 # strokeStyle: 'black' # } # { # type: 'bezier' # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # } # ] fromJson: (json) -> @clear() for item in json.items if item.asset? && item.asset.key? item.key = item.asset.key if item.type == 'image' @drawImage(item) if item.type == 'text' @drawText(item) if item.type == 'bezier' @drawBezier(item) # Used to overlay a bezier curve on a canvas # # @see StackOverflow.drawBezier # @see draw bezier tool # # @example # @drawBezier( # curve: '99.2,207.2,130.02,60.0,300.5,276.2,300.7,176.2' # text: 'hello world' # strokeStyle: 'black' # letterPadding: 4 # ) drawBezier: (options) -> StackOverflow.drawBezier(options, @ctx) # Overlay text on a canvas # # @example # @drawText(text: 'foo', y: 60, strokeStyle: 'black') drawText: (options = {}) -> throw 'options.text missing' unless options.text? options.fillStyle ?= 'white' options.fillLineWidth ?= 1 options.strokeLineWidth ?= 7 options.strokeStyle ?= undefined # lol options.font ?= '40px Helvetica' options.x ?= 0 options.y ?= 0 options.angle ?= 0 @ctx.save() @ctx.font = options.font if options.angle != 0 @ctx.rotate(options.angle * Math.PI / 180) if options.strokeStyle? @ctx.miterLimit = 2 @ctx.lineJoin = 'circle' @ctx.strokeStyle = options.strokeStyle @ctx.lineWidth = options.strokeLineWidth @ctx.strokeText options.text, options.x, options.y @ctx.lineWidth = options.fillLineWidth @ctx.fillStyle = options.fillStyle @ctx.fillText options.text, options.x, options.y @ctx.restore() # Used to overlay an image on the canvas # # @example # @drawImage(key: 'PI:KEY:<KEY>END_PI') # @drawImage(key: 'template') # drawImage: (options = {}) -> throw 'key not found' unless options.key? options.x ?= 0 options.y ?= 0 options.angle ?= 0 x = options.x y = options.y image = @tm.items[options.key].image if options.angle != 0 @ctx.save() @ctx.translate(options.x + image.width / 2, options.y + image.height / 2) @ctx.rotate(options.angle * Math.PI / 180) x = -(image.width / 2) y = -(image.height / 2) @ctx.drawImage(image, x, y) if options.angle != 0 @ctx.restore() # clear the canvas context clear: -> @ctx.clearRect(0, 0, @options.width, @options.height)
[ { "context": ">\n\nexports.getOptions = () ->\n\treturn [\n\t\t{ key: \"twitter\" }\n\t]\nexports.getName = () ->\n\treturn 'twitter'\n\n", "end": 161, "score": 0.7538250088691711, "start": 154, "tag": "KEY", "value": "twitter" } ]
web/src/cs/sources/twitter.coffee
nthitz/dreamlastnight
1
EventEmitter = require('events').EventEmitter exports = new EventEmitter() exports.requestDreams = () -> exports.getOptions = () -> return [ { key: "twitter" } ] exports.getName = () -> return 'twitter' exports.twitter = () -> console.log('twitter') module.exports = exports
36142
EventEmitter = require('events').EventEmitter exports = new EventEmitter() exports.requestDreams = () -> exports.getOptions = () -> return [ { key: "<KEY>" } ] exports.getName = () -> return 'twitter' exports.twitter = () -> console.log('twitter') module.exports = exports
true
EventEmitter = require('events').EventEmitter exports = new EventEmitter() exports.requestDreams = () -> exports.getOptions = () -> return [ { key: "PI:KEY:<KEY>END_PI" } ] exports.getName = () -> return 'twitter' exports.twitter = () -> console.log('twitter') module.exports = exports
[ { "context": "createSDP: (opts) ->\n mandatoryOpts = [\n 'username'\n 'sessionID'\n 'sessionVersion'\n '", "end": 1697, "score": 0.9253345131874084, "start": 1689, "tag": "USERNAME", "value": "username" }, { "context": "g like this...\n #\n # v=0\n # o=-...
sdp.coffee
jonathan-casarrubias/node-rtsp-rtmp-server
1
# SDP spec: # RFC 4566 https://tools.ietf.org/html/rfc4566 aac = require './aac' logger = require './logger' api = # opts: # username (string): Username or '-' # sessionID (string): Session ID (numeric string) # sessionVersion (string): Session version number # addressType (string): 'IP4' or 'IP6' # unicastAddress (string): Address of the machine from which the session # was created. A local IP address MUST NOT be # used in any context where the SDP description # might leave the scope in which the address is # meaningful. # hasAudio (boolean): true if the stream contains audio # audioPayloadType (number): payload type for audio # audioEncodingName (string): encoding name for audio # audioClockRate (number): clock rate for audio # audioChannels (number): number of audio channels # audioSampleRate (number): audio sample rate # audioObjectType (number): audio object type # hasVideo (boolean): true if the stream contains video # videoPayloadType (number): payload type for video # videoEncodingName (string): encoding name for video # videoClockRate (number): clock rate for video # videoProfileLevelId (string): profile-level-id for video # videoSpropParameterSets (string): sprop-parameter-sets for video # videoHeight (number): video frame height # videoWidth (number): video frame width # videoFrameRate (string): video frame rate. Either <integer> or # <integer>.<fraction> is allowed. createSDP: (opts) -> mandatoryOpts = [ 'username' 'sessionID' 'sessionVersion' 'addressType' 'unicastAddress' ] if opts.hasAudio mandatoryOpts = mandatoryOpts.concat [ 'audioPayloadType' 'audioEncodingName' 'audioClockRate' ] if opts.hasVideo mandatoryOpts = mandatoryOpts.concat [ 'videoPayloadType' 'videoEncodingName' 'videoClockRate' ] for prop in mandatoryOpts if not opts?[prop]? throw new Error "createSDP: property #{prop} is required" # SDP parameters are defined in RFC 4566. # sizeLength, indexLength, indexDeltaLength are defined by # RFC 3640 or RFC 5691. # # packetization-mode: (see Section 5.4 of RFC 6184 for details) # 0: Single NAL Unit Mode # 1: Non-Interleaved Mode (for STAP-A, FU-A) # 2: Interleaved Mode (for STAP-B, MTAP16, MTAP24, FU-A, FU-B) # # rtpmap:96 mpeg4-generic/<audio clock rate>/<audio channels> # # TODO: Use appropriate profile-level-id sdpBody = """ v=0 o=#{opts.username} #{opts.sessionID} #{opts.sessionVersion} IN #{opts.addressType} #{opts.unicastAddress} s= c=IN #{opts.addressType} #{opts.unicastAddress} t=0 0 a=sdplang:en a=range:npt=0.0- a=control:* """ if opts.hasAudio # configspec: for MPEG-4 Audio streams, use hexstring of AudioSpecificConfig() # see 1.6.2.1 of ISO/IEC 14496-3 for the details of AudioSpecificConfig if opts.audioSpecificConfig? configspec = opts.audioSpecificConfig.toString 'hex' else if opts.audioObjectType? and opts.audioSampleRate? and opts.audioChannels? configspec = new Buffer aac.createAudioSpecificConfig audioObjectType: opts.audioObjectType samplingFrequency: opts.audioSampleRate channels: opts.audioChannels frameLength: 1024 # TODO: How to detect 960? configspec = configspec.toString 'hex' else logger.warn "[sdp] warn: audio configspec is not available" configspec = null rtpmap = "#{opts.audioPayloadType} #{opts.audioEncodingName}/#{opts.audioClockRate}" if opts.audioChannels? rtpmap += "/#{opts.audioChannels}" profileLevelId = 1 # TODO: Set this value according to audio config fmtp = "#{opts.audioPayloadType} profile-level-id=#{profileLevelId};mode=AAC-hbr;sizeLength=13;indexLength=3;indexDeltaLength=3" if configspec? fmtp += ";config=#{configspec}" # profile-level-id=1: Main Profile Level 1 sdpBody += """ m=audio 0 RTP/AVP #{opts.audioPayloadType} a=rtpmap:#{rtpmap} a=fmtp:#{fmtp} a=control:trackID=1 """ if opts.hasVideo fmtp = "#{opts.videoPayloadType} packetization-mode=1" if opts.videoProfileLevelId? fmtp += ";profile-level-id=#{opts.videoProfileLevelId}" if opts.videoSpropParameterSets? fmtp += ";sprop-parameter-sets=#{opts.videoSpropParameterSets}" sdpBody += """ m=video 0 RTP/AVP #{opts.videoPayloadType} a=rtpmap:#{opts.videoPayloadType} #{opts.videoEncodingName}/#{opts.videoClockRate} a=fmtp:#{fmtp} """ if opts.videoHeight? and opts.videoWidth? sdpBody += """ a=cliprect:0,0,#{opts.videoHeight},#{opts.videoWidth} a=framesize:#{opts.videoPayloadType} #{opts.videoWidth}-#{opts.videoHeight} """ if opts.videoFrameRate? sdpBody += "a=framerate:#{opts.videoFrameRate}\n" sdpBody += """ a=control:trackID=2 """ return sdpBody.replace /\n/g, "\r\n" # Turn an SDP string like this... # # v=0 # o=- 0 0 IN IP4 127.0.0.1 # s=No Name # c=IN IP4 127.0.0.1 # t=0 0 # a=tool:libavformat 56.15.102 # m=video 0 RTP/AVP 96 # b=AS:501 # a=rtpmap:96 H264/90000 # a=fmtp:96 packetization-mode=1; sprop-parameter-sets=Z0IAFbtA8F/y4CA8IBCo,aM4HDs # g=; profile-level-id=420015 # a=control:streamid=0 # m=audio 0 RTP/AVP 97 # b=AS:125 # a=rtpmap:97 MPEG4-GENERIC/44100/2 # a=fmtp:97 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdelta # length=3; config=1210 # a=control:streamid=1 # # ...into an object like this. # # { version: '0', # origin: # { username: '-', # sessId: '0', # sessVersion: '0', # nettype: 'IN', # addrtype: 'IP4', # unicastAddress: '127.0.0.1' }, # sessionName: 'No Name', # connectionData: # { nettype: 'IN', # addrtype: 'IP4', # connectionAddress: '127.0.0.1' }, # timing: { startTime: '0', stopTime: '0' }, # attributes: { tool: 'libavformat 56.15.102' }, # media: # [ { media: 'video', # port: '0', # proto: 'RTP/AVP', # fmt: 96, # bandwidth: { bwtype: 'AS', bandwidth: '501' }, # attributes: # { rtpmap: '96 H264/90000', # fmtp: '96 packetization-mode=1; sprop-parameter-sets=Z0IAFbtA8F/y4CA8IBCo,aM4HDsg=; profile-level-id=420015', # control: 'streamid=0' }, # clockRate: 90000, # fmtpParams: # { 'packetization-mode': '1', # 'sprop-parameter-sets': 'Z0IAFbtA8F/y4CA8IBCo,aM4HDsg=', # 'profile-level-id': '420015' } }, # { media: 'audio', # port: '0', # proto: 'RTP/AVP', # fmt: 97, # bandwidth: { bwtype: 'AS', bandwidth: '125' }, # attributes: # { rtpmap: '97 MPEG4-GENERIC/44100/2', # fmtp: '97 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3; config=1210', # control: 'streamid=1' }, # clockRate: 44100, # audioChannels: 2, # fmtpParams: # { 'profile-level-id': '1', # mode: 'AAC-hbr', # sizelength: '13', # indexlength: '3', # indexdeltalength: '3', # config: '1210' } } ] } parse: (str) -> session = {} origParams = [] currentMedia = null for line in str.split /\r?\n/ if line isnt '' if (match = /^(.*?)=(.*)$/.exec line)? key = match[1] value = match[2] else throw new Error "Invalid SDP line: #{line}" obj = {} obj[ key ] = value origParams.push obj switch key when 'v' # Version session.version = value when 'o' # Origin params = value.split /\s+/ if params.length > 6 logger.warn "SDP: Origin has too many parameters: #{line}" session.origin = username: params[0] sessId: params[1] sessVersion: params[2] nettype: params[3] addrtype: params[4] unicastAddress: params[5] when 's' # Session Name session.sessionName = value when 'c' # Connection Data params = value.split /\s+/ if params.length > 3 logger.warn "SDP: Connection Data has too many parameters: #{line}" session.connectionData = nettype: params[0] addrtype: params[1] connectionAddress: params[2] when 't' # Timing params = value.split /\s+/ if params.length > 2 logger.warn "SDP: Timing has too many parameters: #{line}" session.timing = startTime: params[0] stopTime: params[1] when 'a' # Attributes target = currentMedia ? session if not target.attributes? target.attributes = {} if (match = /^(.*?):(.*)$/.exec value)? # a=<attribute>:<value> attrKey = match[1] attrValue = match[2] target.attributes[attrKey] = attrValue if attrKey is 'rtpmap' if (match = /\d+\s+.*?\/(\d+)(?:\/(\d+))?/.exec attrValue)? target.clockRate = parseInt match[1] if match[2]? target.audioChannels = parseInt match[2] else if attrKey is 'fmtp' if (match = /^\d+\s+(.*)$/.exec attrValue)? target.fmtpParams = {} for pair in match[1].split /;\s*/ if (match = /^(.*?)=(.*)$/.exec pair)? target.fmtpParams[ match[1].toLowerCase() ] = match[2] else # a=<flag> target.attributes[ value ] = true when 'm' # Media Descriptions params = value.split /\s+/ currentMedia = media: params[0] port: params[1] proto: params[2] fmt: params[3] if (currentMedia.proto is 'RTP/AVP') or (currentMedia.proto is 'RTP/SAVP') currentMedia.fmt = parseInt currentMedia.fmt if params.length >= 5 currentMedia.others = params[4] if not session.media? session.media = [] session.media.push currentMedia when 'b' # Bandwidth params = value.split ':' if params.length > 2 logger.warn "SDP: Bandwidth has too many parameters: #{line}" target = currentMedia ? session target.bandwidth = bwtype: params[0] bandwidth: params[1] else logger.warn "Unknown (not implemented) SDP: #{line}" return session module.exports = api
209167
# SDP spec: # RFC 4566 https://tools.ietf.org/html/rfc4566 aac = require './aac' logger = require './logger' api = # opts: # username (string): Username or '-' # sessionID (string): Session ID (numeric string) # sessionVersion (string): Session version number # addressType (string): 'IP4' or 'IP6' # unicastAddress (string): Address of the machine from which the session # was created. A local IP address MUST NOT be # used in any context where the SDP description # might leave the scope in which the address is # meaningful. # hasAudio (boolean): true if the stream contains audio # audioPayloadType (number): payload type for audio # audioEncodingName (string): encoding name for audio # audioClockRate (number): clock rate for audio # audioChannels (number): number of audio channels # audioSampleRate (number): audio sample rate # audioObjectType (number): audio object type # hasVideo (boolean): true if the stream contains video # videoPayloadType (number): payload type for video # videoEncodingName (string): encoding name for video # videoClockRate (number): clock rate for video # videoProfileLevelId (string): profile-level-id for video # videoSpropParameterSets (string): sprop-parameter-sets for video # videoHeight (number): video frame height # videoWidth (number): video frame width # videoFrameRate (string): video frame rate. Either <integer> or # <integer>.<fraction> is allowed. createSDP: (opts) -> mandatoryOpts = [ 'username' 'sessionID' 'sessionVersion' 'addressType' 'unicastAddress' ] if opts.hasAudio mandatoryOpts = mandatoryOpts.concat [ 'audioPayloadType' 'audioEncodingName' 'audioClockRate' ] if opts.hasVideo mandatoryOpts = mandatoryOpts.concat [ 'videoPayloadType' 'videoEncodingName' 'videoClockRate' ] for prop in mandatoryOpts if not opts?[prop]? throw new Error "createSDP: property #{prop} is required" # SDP parameters are defined in RFC 4566. # sizeLength, indexLength, indexDeltaLength are defined by # RFC 3640 or RFC 5691. # # packetization-mode: (see Section 5.4 of RFC 6184 for details) # 0: Single NAL Unit Mode # 1: Non-Interleaved Mode (for STAP-A, FU-A) # 2: Interleaved Mode (for STAP-B, MTAP16, MTAP24, FU-A, FU-B) # # rtpmap:96 mpeg4-generic/<audio clock rate>/<audio channels> # # TODO: Use appropriate profile-level-id sdpBody = """ v=0 o=#{opts.username} #{opts.sessionID} #{opts.sessionVersion} IN #{opts.addressType} #{opts.unicastAddress} s= c=IN #{opts.addressType} #{opts.unicastAddress} t=0 0 a=sdplang:en a=range:npt=0.0- a=control:* """ if opts.hasAudio # configspec: for MPEG-4 Audio streams, use hexstring of AudioSpecificConfig() # see 1.6.2.1 of ISO/IEC 14496-3 for the details of AudioSpecificConfig if opts.audioSpecificConfig? configspec = opts.audioSpecificConfig.toString 'hex' else if opts.audioObjectType? and opts.audioSampleRate? and opts.audioChannels? configspec = new Buffer aac.createAudioSpecificConfig audioObjectType: opts.audioObjectType samplingFrequency: opts.audioSampleRate channels: opts.audioChannels frameLength: 1024 # TODO: How to detect 960? configspec = configspec.toString 'hex' else logger.warn "[sdp] warn: audio configspec is not available" configspec = null rtpmap = "#{opts.audioPayloadType} #{opts.audioEncodingName}/#{opts.audioClockRate}" if opts.audioChannels? rtpmap += "/#{opts.audioChannels}" profileLevelId = 1 # TODO: Set this value according to audio config fmtp = "#{opts.audioPayloadType} profile-level-id=#{profileLevelId};mode=AAC-hbr;sizeLength=13;indexLength=3;indexDeltaLength=3" if configspec? fmtp += ";config=#{configspec}" # profile-level-id=1: Main Profile Level 1 sdpBody += """ m=audio 0 RTP/AVP #{opts.audioPayloadType} a=rtpmap:#{rtpmap} a=fmtp:#{fmtp} a=control:trackID=1 """ if opts.hasVideo fmtp = "#{opts.videoPayloadType} packetization-mode=1" if opts.videoProfileLevelId? fmtp += ";profile-level-id=#{opts.videoProfileLevelId}" if opts.videoSpropParameterSets? fmtp += ";sprop-parameter-sets=#{opts.videoSpropParameterSets}" sdpBody += """ m=video 0 RTP/AVP #{opts.videoPayloadType} a=rtpmap:#{opts.videoPayloadType} #{opts.videoEncodingName}/#{opts.videoClockRate} a=fmtp:#{fmtp} """ if opts.videoHeight? and opts.videoWidth? sdpBody += """ a=cliprect:0,0,#{opts.videoHeight},#{opts.videoWidth} a=framesize:#{opts.videoPayloadType} #{opts.videoWidth}-#{opts.videoHeight} """ if opts.videoFrameRate? sdpBody += "a=framerate:#{opts.videoFrameRate}\n" sdpBody += """ a=control:trackID=2 """ return sdpBody.replace /\n/g, "\r\n" # Turn an SDP string like this... # # v=0 # o=- 0 0 IN IP4 127.0.0.1 # s=No Name # c=IN IP4 127.0.0.1 # t=0 0 # a=tool:libavformat 56.15.102 # m=video 0 RTP/AVP 96 # b=AS:501 # a=rtpmap:96 H264/90000 # a=fmtp:96 packetization-mode=1; sprop-parameter-sets=Z0IAFbtA8F/y4CA8IBCo,aM4HDs # g=; profile-level-id=420015 # a=control:streamid=0 # m=audio 0 RTP/AVP 97 # b=AS:125 # a=rtpmap:97 MPEG4-GENERIC/44100/2 # a=fmtp:97 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdelta # length=3; config=1210 # a=control:streamid=1 # # ...into an object like this. # # { version: '0', # origin: # { username: '-', # sessId: '0', # sessVersion: '0', # nettype: 'IN', # addrtype: 'IP4', # unicastAddress: '127.0.0.1' }, # sessionName: '<NAME>', # connectionData: # { nettype: 'IN', # addrtype: 'IP4', # connectionAddress: '127.0.0.1' }, # timing: { startTime: '0', stopTime: '0' }, # attributes: { tool: 'libavformat 56.15.102' }, # media: # [ { media: 'video', # port: '0', # proto: 'RTP/AVP', # fmt: 96, # bandwidth: { bwtype: 'AS', bandwidth: '501' }, # attributes: # { rtpmap: '96 H264/90000', # fmtp: '96 packetization-mode=1; sprop-parameter-sets=Z0IAFbtA8F/y4CA8IBCo,aM4HDsg=; profile-level-id=420015', # control: 'streamid=0' }, # clockRate: 90000, # fmtpParams: # { 'packetization-mode': '1', # 'sprop-parameter-sets': 'Z0IAFbtA8F/y4CA8IBCo,aM4HDsg=', # 'profile-level-id': '420015' } }, # { media: 'audio', # port: '0', # proto: 'RTP/AVP', # fmt: 97, # bandwidth: { bwtype: 'AS', bandwidth: '125' }, # attributes: # { rtpmap: '97 MPEG4-GENERIC/44100/2', # fmtp: '97 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3; config=1210', # control: 'streamid=1' }, # clockRate: 44100, # audioChannels: 2, # fmtpParams: # { 'profile-level-id': '1', # mode: 'AAC-hbr', # sizelength: '13', # indexlength: '3', # indexdeltalength: '3', # config: '1210' } } ] } parse: (str) -> session = {} origParams = [] currentMedia = null for line in str.split /\r?\n/ if line isnt '' if (match = /^(.*?)=(.*)$/.exec line)? key = match[1] value = match[2] else throw new Error "Invalid SDP line: #{line}" obj = {} obj[ key ] = value origParams.push obj switch key when 'v' # Version session.version = value when 'o' # Origin params = value.split /\s+/ if params.length > 6 logger.warn "SDP: Origin has too many parameters: #{line}" session.origin = username: params[0] sessId: params[1] sessVersion: params[2] nettype: params[3] addrtype: params[4] unicastAddress: params[5] when 's' # Session Name session.sessionName = value when 'c' # Connection Data params = value.split /\s+/ if params.length > 3 logger.warn "SDP: Connection Data has too many parameters: #{line}" session.connectionData = nettype: params[0] addrtype: params[1] connectionAddress: params[2] when 't' # Timing params = value.split /\s+/ if params.length > 2 logger.warn "SDP: Timing has too many parameters: #{line}" session.timing = startTime: params[0] stopTime: params[1] when 'a' # Attributes target = currentMedia ? session if not target.attributes? target.attributes = {} if (match = /^(.*?):(.*)$/.exec value)? # a=<attribute>:<value> attrKey = match[1] attrValue = match[2] target.attributes[attrKey] = attrValue if attrKey is 'rtpmap' if (match = /\d+\s+.*?\/(\d+)(?:\/(\d+))?/.exec attrValue)? target.clockRate = parseInt match[1] if match[2]? target.audioChannels = parseInt match[2] else if attrKey is 'fmtp' if (match = /^\d+\s+(.*)$/.exec attrValue)? target.fmtpParams = {} for pair in match[1].split /;\s*/ if (match = /^(.*?)=(.*)$/.exec pair)? target.fmtpParams[ match[1].toLowerCase() ] = match[2] else # a=<flag> target.attributes[ value ] = true when 'm' # Media Descriptions params = value.split /\s+/ currentMedia = media: params[0] port: params[1] proto: params[2] fmt: params[3] if (currentMedia.proto is 'RTP/AVP') or (currentMedia.proto is 'RTP/SAVP') currentMedia.fmt = parseInt currentMedia.fmt if params.length >= 5 currentMedia.others = params[4] if not session.media? session.media = [] session.media.push currentMedia when 'b' # Bandwidth params = value.split ':' if params.length > 2 logger.warn "SDP: Bandwidth has too many parameters: #{line}" target = currentMedia ? session target.bandwidth = bwtype: params[0] bandwidth: params[1] else logger.warn "Unknown (not implemented) SDP: #{line}" return session module.exports = api
true
# SDP spec: # RFC 4566 https://tools.ietf.org/html/rfc4566 aac = require './aac' logger = require './logger' api = # opts: # username (string): Username or '-' # sessionID (string): Session ID (numeric string) # sessionVersion (string): Session version number # addressType (string): 'IP4' or 'IP6' # unicastAddress (string): Address of the machine from which the session # was created. A local IP address MUST NOT be # used in any context where the SDP description # might leave the scope in which the address is # meaningful. # hasAudio (boolean): true if the stream contains audio # audioPayloadType (number): payload type for audio # audioEncodingName (string): encoding name for audio # audioClockRate (number): clock rate for audio # audioChannels (number): number of audio channels # audioSampleRate (number): audio sample rate # audioObjectType (number): audio object type # hasVideo (boolean): true if the stream contains video # videoPayloadType (number): payload type for video # videoEncodingName (string): encoding name for video # videoClockRate (number): clock rate for video # videoProfileLevelId (string): profile-level-id for video # videoSpropParameterSets (string): sprop-parameter-sets for video # videoHeight (number): video frame height # videoWidth (number): video frame width # videoFrameRate (string): video frame rate. Either <integer> or # <integer>.<fraction> is allowed. createSDP: (opts) -> mandatoryOpts = [ 'username' 'sessionID' 'sessionVersion' 'addressType' 'unicastAddress' ] if opts.hasAudio mandatoryOpts = mandatoryOpts.concat [ 'audioPayloadType' 'audioEncodingName' 'audioClockRate' ] if opts.hasVideo mandatoryOpts = mandatoryOpts.concat [ 'videoPayloadType' 'videoEncodingName' 'videoClockRate' ] for prop in mandatoryOpts if not opts?[prop]? throw new Error "createSDP: property #{prop} is required" # SDP parameters are defined in RFC 4566. # sizeLength, indexLength, indexDeltaLength are defined by # RFC 3640 or RFC 5691. # # packetization-mode: (see Section 5.4 of RFC 6184 for details) # 0: Single NAL Unit Mode # 1: Non-Interleaved Mode (for STAP-A, FU-A) # 2: Interleaved Mode (for STAP-B, MTAP16, MTAP24, FU-A, FU-B) # # rtpmap:96 mpeg4-generic/<audio clock rate>/<audio channels> # # TODO: Use appropriate profile-level-id sdpBody = """ v=0 o=#{opts.username} #{opts.sessionID} #{opts.sessionVersion} IN #{opts.addressType} #{opts.unicastAddress} s= c=IN #{opts.addressType} #{opts.unicastAddress} t=0 0 a=sdplang:en a=range:npt=0.0- a=control:* """ if opts.hasAudio # configspec: for MPEG-4 Audio streams, use hexstring of AudioSpecificConfig() # see 1.6.2.1 of ISO/IEC 14496-3 for the details of AudioSpecificConfig if opts.audioSpecificConfig? configspec = opts.audioSpecificConfig.toString 'hex' else if opts.audioObjectType? and opts.audioSampleRate? and opts.audioChannels? configspec = new Buffer aac.createAudioSpecificConfig audioObjectType: opts.audioObjectType samplingFrequency: opts.audioSampleRate channels: opts.audioChannels frameLength: 1024 # TODO: How to detect 960? configspec = configspec.toString 'hex' else logger.warn "[sdp] warn: audio configspec is not available" configspec = null rtpmap = "#{opts.audioPayloadType} #{opts.audioEncodingName}/#{opts.audioClockRate}" if opts.audioChannels? rtpmap += "/#{opts.audioChannels}" profileLevelId = 1 # TODO: Set this value according to audio config fmtp = "#{opts.audioPayloadType} profile-level-id=#{profileLevelId};mode=AAC-hbr;sizeLength=13;indexLength=3;indexDeltaLength=3" if configspec? fmtp += ";config=#{configspec}" # profile-level-id=1: Main Profile Level 1 sdpBody += """ m=audio 0 RTP/AVP #{opts.audioPayloadType} a=rtpmap:#{rtpmap} a=fmtp:#{fmtp} a=control:trackID=1 """ if opts.hasVideo fmtp = "#{opts.videoPayloadType} packetization-mode=1" if opts.videoProfileLevelId? fmtp += ";profile-level-id=#{opts.videoProfileLevelId}" if opts.videoSpropParameterSets? fmtp += ";sprop-parameter-sets=#{opts.videoSpropParameterSets}" sdpBody += """ m=video 0 RTP/AVP #{opts.videoPayloadType} a=rtpmap:#{opts.videoPayloadType} #{opts.videoEncodingName}/#{opts.videoClockRate} a=fmtp:#{fmtp} """ if opts.videoHeight? and opts.videoWidth? sdpBody += """ a=cliprect:0,0,#{opts.videoHeight},#{opts.videoWidth} a=framesize:#{opts.videoPayloadType} #{opts.videoWidth}-#{opts.videoHeight} """ if opts.videoFrameRate? sdpBody += "a=framerate:#{opts.videoFrameRate}\n" sdpBody += """ a=control:trackID=2 """ return sdpBody.replace /\n/g, "\r\n" # Turn an SDP string like this... # # v=0 # o=- 0 0 IN IP4 127.0.0.1 # s=No Name # c=IN IP4 127.0.0.1 # t=0 0 # a=tool:libavformat 56.15.102 # m=video 0 RTP/AVP 96 # b=AS:501 # a=rtpmap:96 H264/90000 # a=fmtp:96 packetization-mode=1; sprop-parameter-sets=Z0IAFbtA8F/y4CA8IBCo,aM4HDs # g=; profile-level-id=420015 # a=control:streamid=0 # m=audio 0 RTP/AVP 97 # b=AS:125 # a=rtpmap:97 MPEG4-GENERIC/44100/2 # a=fmtp:97 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdelta # length=3; config=1210 # a=control:streamid=1 # # ...into an object like this. # # { version: '0', # origin: # { username: '-', # sessId: '0', # sessVersion: '0', # nettype: 'IN', # addrtype: 'IP4', # unicastAddress: '127.0.0.1' }, # sessionName: 'PI:NAME:<NAME>END_PI', # connectionData: # { nettype: 'IN', # addrtype: 'IP4', # connectionAddress: '127.0.0.1' }, # timing: { startTime: '0', stopTime: '0' }, # attributes: { tool: 'libavformat 56.15.102' }, # media: # [ { media: 'video', # port: '0', # proto: 'RTP/AVP', # fmt: 96, # bandwidth: { bwtype: 'AS', bandwidth: '501' }, # attributes: # { rtpmap: '96 H264/90000', # fmtp: '96 packetization-mode=1; sprop-parameter-sets=Z0IAFbtA8F/y4CA8IBCo,aM4HDsg=; profile-level-id=420015', # control: 'streamid=0' }, # clockRate: 90000, # fmtpParams: # { 'packetization-mode': '1', # 'sprop-parameter-sets': 'Z0IAFbtA8F/y4CA8IBCo,aM4HDsg=', # 'profile-level-id': '420015' } }, # { media: 'audio', # port: '0', # proto: 'RTP/AVP', # fmt: 97, # bandwidth: { bwtype: 'AS', bandwidth: '125' }, # attributes: # { rtpmap: '97 MPEG4-GENERIC/44100/2', # fmtp: '97 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3; config=1210', # control: 'streamid=1' }, # clockRate: 44100, # audioChannels: 2, # fmtpParams: # { 'profile-level-id': '1', # mode: 'AAC-hbr', # sizelength: '13', # indexlength: '3', # indexdeltalength: '3', # config: '1210' } } ] } parse: (str) -> session = {} origParams = [] currentMedia = null for line in str.split /\r?\n/ if line isnt '' if (match = /^(.*?)=(.*)$/.exec line)? key = match[1] value = match[2] else throw new Error "Invalid SDP line: #{line}" obj = {} obj[ key ] = value origParams.push obj switch key when 'v' # Version session.version = value when 'o' # Origin params = value.split /\s+/ if params.length > 6 logger.warn "SDP: Origin has too many parameters: #{line}" session.origin = username: params[0] sessId: params[1] sessVersion: params[2] nettype: params[3] addrtype: params[4] unicastAddress: params[5] when 's' # Session Name session.sessionName = value when 'c' # Connection Data params = value.split /\s+/ if params.length > 3 logger.warn "SDP: Connection Data has too many parameters: #{line}" session.connectionData = nettype: params[0] addrtype: params[1] connectionAddress: params[2] when 't' # Timing params = value.split /\s+/ if params.length > 2 logger.warn "SDP: Timing has too many parameters: #{line}" session.timing = startTime: params[0] stopTime: params[1] when 'a' # Attributes target = currentMedia ? session if not target.attributes? target.attributes = {} if (match = /^(.*?):(.*)$/.exec value)? # a=<attribute>:<value> attrKey = match[1] attrValue = match[2] target.attributes[attrKey] = attrValue if attrKey is 'rtpmap' if (match = /\d+\s+.*?\/(\d+)(?:\/(\d+))?/.exec attrValue)? target.clockRate = parseInt match[1] if match[2]? target.audioChannels = parseInt match[2] else if attrKey is 'fmtp' if (match = /^\d+\s+(.*)$/.exec attrValue)? target.fmtpParams = {} for pair in match[1].split /;\s*/ if (match = /^(.*?)=(.*)$/.exec pair)? target.fmtpParams[ match[1].toLowerCase() ] = match[2] else # a=<flag> target.attributes[ value ] = true when 'm' # Media Descriptions params = value.split /\s+/ currentMedia = media: params[0] port: params[1] proto: params[2] fmt: params[3] if (currentMedia.proto is 'RTP/AVP') or (currentMedia.proto is 'RTP/SAVP') currentMedia.fmt = parseInt currentMedia.fmt if params.length >= 5 currentMedia.others = params[4] if not session.media? session.media = [] session.media.push currentMedia when 'b' # Bandwidth params = value.split ':' if params.length > 2 logger.warn "SDP: Bandwidth has too many parameters: #{line}" target = currentMedia ? session target.bandwidth = bwtype: params[0] bandwidth: params[1] else logger.warn "Unknown (not implemented) SDP: #{line}" return session module.exports = api
[ { "context": "rview Test for no-underscore-dangle rule\n# @author Matt DuVall <http://www.mattduvall.com>\n###\n\n'use strict'\n\n#-", "end": 77, "score": 0.9997995495796204, "start": 66, "tag": "NAME", "value": "Matt DuVall" } ]
src/tests/rules/no-underscore-dangle.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Test for no-underscore-dangle rule # @author Matt DuVall <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-underscore-dangle' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-underscore-dangle', rule, valid: [ 'foo_bar = 1' 'foo_bar = ->' 'foo.bar.__proto__' ''' console.log(__filename) console.log(__dirname) ''' "_ = require('underscore')" 'a = b._' 'export default ->' , code: '_foo = 1', options: [allow: ['_foo']] , code: '__proto__ = 1', options: [allow: ['__proto__']] , code: 'foo._bar', options: [allow: ['_bar']] , code: '_foo = ->', options: [allow: ['_foo']] , code: 'this._bar', options: [allowAfterThis: yes] , code: '@_bar', options: [allowAfterThis: yes] , code: ''' class foo constructor: -> super._bar ''' options: [allowAfterSuper: yes] , code: ''' class foo _onClick: -> ''' , code: 'o = _onClick: ->' , code: "o = { _foo: 'bar' }" , code: "o = { foo_: 'bar' }" ] invalid: [ code: '_foo = 1' errors: [message: "Unexpected dangling '_' in '_foo'.", type: 'Identifier'] , code: 'foo_ = 1' errors: [message: "Unexpected dangling '_' in 'foo_'.", type: 'Identifier'] , code: '_foo = ->' errors: [message: "Unexpected dangling '_' in '_foo'.", type: 'Identifier'] , code: 'foo_ = ->' errors: [message: "Unexpected dangling '_' in 'foo_'.", type: 'Identifier'] , code: '__proto__ = 1' errors: [ message: "Unexpected dangling '_' in '__proto__'." type: 'Identifier' ] , code: 'foo._bar' errors: [ message: "Unexpected dangling '_' in '_bar'.", type: 'MemberExpression' ] , code: 'this._prop' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: '@_prop' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo constructor: -> super._prop ''' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo constructor: -> this._prop ''' options: [allowAfterSuper: yes] errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo _onClick: -> ''' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in '_onClick'." type: 'MethodDefinition' ] , code: ''' class foo onClick_: -> ''' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in 'onClick_'." type: 'MethodDefinition' ] , code: 'o = _onClick: ->' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in '_onClick'.", type: 'Property' ] , code: 'o = { onClick_: -> }' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in 'onClick_'.", type: 'Property' ] ]
213833
###* # @fileoverview Test for no-underscore-dangle rule # @author <NAME> <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-underscore-dangle' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-underscore-dangle', rule, valid: [ 'foo_bar = 1' 'foo_bar = ->' 'foo.bar.__proto__' ''' console.log(__filename) console.log(__dirname) ''' "_ = require('underscore')" 'a = b._' 'export default ->' , code: '_foo = 1', options: [allow: ['_foo']] , code: '__proto__ = 1', options: [allow: ['__proto__']] , code: 'foo._bar', options: [allow: ['_bar']] , code: '_foo = ->', options: [allow: ['_foo']] , code: 'this._bar', options: [allowAfterThis: yes] , code: '@_bar', options: [allowAfterThis: yes] , code: ''' class foo constructor: -> super._bar ''' options: [allowAfterSuper: yes] , code: ''' class foo _onClick: -> ''' , code: 'o = _onClick: ->' , code: "o = { _foo: 'bar' }" , code: "o = { foo_: 'bar' }" ] invalid: [ code: '_foo = 1' errors: [message: "Unexpected dangling '_' in '_foo'.", type: 'Identifier'] , code: 'foo_ = 1' errors: [message: "Unexpected dangling '_' in 'foo_'.", type: 'Identifier'] , code: '_foo = ->' errors: [message: "Unexpected dangling '_' in '_foo'.", type: 'Identifier'] , code: 'foo_ = ->' errors: [message: "Unexpected dangling '_' in 'foo_'.", type: 'Identifier'] , code: '__proto__ = 1' errors: [ message: "Unexpected dangling '_' in '__proto__'." type: 'Identifier' ] , code: 'foo._bar' errors: [ message: "Unexpected dangling '_' in '_bar'.", type: 'MemberExpression' ] , code: 'this._prop' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: '@_prop' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo constructor: -> super._prop ''' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo constructor: -> this._prop ''' options: [allowAfterSuper: yes] errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo _onClick: -> ''' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in '_onClick'." type: 'MethodDefinition' ] , code: ''' class foo onClick_: -> ''' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in 'onClick_'." type: 'MethodDefinition' ] , code: 'o = _onClick: ->' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in '_onClick'.", type: 'Property' ] , code: 'o = { onClick_: -> }' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in 'onClick_'.", type: 'Property' ] ]
true
###* # @fileoverview Test for no-underscore-dangle rule # @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-underscore-dangle' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-underscore-dangle', rule, valid: [ 'foo_bar = 1' 'foo_bar = ->' 'foo.bar.__proto__' ''' console.log(__filename) console.log(__dirname) ''' "_ = require('underscore')" 'a = b._' 'export default ->' , code: '_foo = 1', options: [allow: ['_foo']] , code: '__proto__ = 1', options: [allow: ['__proto__']] , code: 'foo._bar', options: [allow: ['_bar']] , code: '_foo = ->', options: [allow: ['_foo']] , code: 'this._bar', options: [allowAfterThis: yes] , code: '@_bar', options: [allowAfterThis: yes] , code: ''' class foo constructor: -> super._bar ''' options: [allowAfterSuper: yes] , code: ''' class foo _onClick: -> ''' , code: 'o = _onClick: ->' , code: "o = { _foo: 'bar' }" , code: "o = { foo_: 'bar' }" ] invalid: [ code: '_foo = 1' errors: [message: "Unexpected dangling '_' in '_foo'.", type: 'Identifier'] , code: 'foo_ = 1' errors: [message: "Unexpected dangling '_' in 'foo_'.", type: 'Identifier'] , code: '_foo = ->' errors: [message: "Unexpected dangling '_' in '_foo'.", type: 'Identifier'] , code: 'foo_ = ->' errors: [message: "Unexpected dangling '_' in 'foo_'.", type: 'Identifier'] , code: '__proto__ = 1' errors: [ message: "Unexpected dangling '_' in '__proto__'." type: 'Identifier' ] , code: 'foo._bar' errors: [ message: "Unexpected dangling '_' in '_bar'.", type: 'MemberExpression' ] , code: 'this._prop' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: '@_prop' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo constructor: -> super._prop ''' errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo constructor: -> this._prop ''' options: [allowAfterSuper: yes] errors: [ message: "Unexpected dangling '_' in '_prop'.", type: 'MemberExpression' ] , code: ''' class foo _onClick: -> ''' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in '_onClick'." type: 'MethodDefinition' ] , code: ''' class foo onClick_: -> ''' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in 'onClick_'." type: 'MethodDefinition' ] , code: 'o = _onClick: ->' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in '_onClick'.", type: 'Property' ] , code: 'o = { onClick_: -> }' options: [enforceInMethodNames: yes] errors: [ message: "Unexpected dangling '_' in 'onClick_'.", type: 'Property' ] ]
[ { "context": "use strict\"\n\n# colorNicks from https://github.com/hbang/Sapientia-Modifications\n# * (based on https://git", "end": 56, "score": 0.9996146559715271, "start": 51, "tag": "USERNAME", "value": "hbang" }, { "context": "ia-Modifications\n# * (based on https://github.com/k...
src/scripts/color-nicks.coffee
bd808/Textual-Theme-bd808
1
"use strict" # colorNicks from https://github.com/hbang/Sapientia-Modifications # * (based on https://github.com/kirbylover4000/irccloud-colornicks # * (based on https://github.com/avidal/irccloud-colornicks # * (based on http://userscripts.org/scripts/show/88258 # * (based on http://chatlogs.musicbrainz.org/mb_chatlogger.user.js)))) # class NickColorizer constructor: () -> @key = 'textual.colorNicks' @css = document.createElement('style') @css.id = 'textual-colorNicks' @css.type = 'text/css' @css.media = 'all' # register callbacks Textual.bind 'messageAddedToView', (line) => @newMessagePostedToView line Textual.bind 'viewBodyDidLoad', => @viewFinishedLoading() load: -> val = localStorage.getItem @key #console.log val if val return JSON.parse val else return {} save: (obj) -> localStorage.setItem(@key, JSON.stringify obj) return cleanNick: (nick) -> # attempts to clean up a nickname # by removing alternate characters from the end # nc_ becomes nc, avidal` becomes avidal nick = nick.toLowerCase() # typically ` and _ are used on the end alone nick = nick.replace(/[`_]+$/, '') # remove |<anything> from the end nick = nick.replace(/\|.*$/, '') # remove [<anything>] or {<anything>} from the end nick.replace(/^(!\[|!\{)(.*)(\[.*\]|\{.*\})$/, '$2') getHash: (nick) -> cleaned = @cleanNick nick #console.log cleaned hash = 0 i = 0 while i < cleaned.length hash = cleaned.charCodeAt(i) + (hash << 6) + (hash << 16) - hash i++ hash getColor: (nick) -> nickHash = @getHash nick #console.log "#{nick} -> #{nickHash}" # get a positive value for the hue deg = nickHash % 360 h = (if deg < 0 then 360 + deg else deg) # default L is 50 l = 50 # half of the hues are too light, for those we # decrease lightness l = 30 if h >= 30 and h <= 210 # keep saturation above 20 s = 20 + Math.abs(nickHash) % 80 "hsl(#{h}, #{s}%, #{l}%)" addNick: (nick) -> #console.log "addNick" #console.log this c = @load() return if nick of c color = @getColor nick c[nick] = color @save c @addCss nick, color #console.log c return viewFinishedLoading: -> c = @load() for nick of c @addCss nick, c[nick] document.head.appendChild @css return newMessagePostedToView: (line) -> for e in line.querySelectorAll(".sender, .inline_nickname") do (e) => nick = false if e.className is "inline_nickname" nick = e.innerText e.setAttribute "data-nickname", e.innerText else nick = e.getAttribute "data-nickname" @addNick nick if nick return return addCss: (nick, color) -> @css.textContent += "\n.sender[data-nickname='#{nick}'], " + ".inline_nickname[data-nickname='#{nick}']" + "{ color: #{color} !important; }" return colorNicks = new NickColorizer()
101100
"use strict" # colorNicks from https://github.com/hbang/Sapientia-Modifications # * (based on https://github.com/kirbylover4000/irccloud-colornicks # * (based on https://github.com/avidal/irccloud-colornicks # * (based on http://userscripts.org/scripts/show/88258 # * (based on http://chatlogs.musicbrainz.org/mb_chatlogger.user.js)))) # class NickColorizer constructor: () -> @key = '<KEY>' @css = document.createElement('style') @css.id = 'textual-colorNicks' @css.type = 'text/css' @css.media = 'all' # register callbacks Textual.bind 'messageAddedToView', (line) => @newMessagePostedToView line Textual.bind 'viewBodyDidLoad', => @viewFinishedLoading() load: -> val = localStorage.getItem @key #console.log val if val return JSON.parse val else return {} save: (obj) -> localStorage.setItem(@key, JSON.stringify obj) return cleanNick: (nick) -> # attempts to clean up a nickname # by removing alternate characters from the end # nc_ becomes nc, avidal` becomes avidal nick = nick.toLowerCase() # typically ` and _ are used on the end alone nick = nick.replace(/[`_]+$/, '') # remove |<anything> from the end nick = nick.replace(/\|.*$/, '') # remove [<anything>] or {<anything>} from the end nick.replace(/^(!\[|!\{)(.*)(\[.*\]|\{.*\})$/, '$2') getHash: (nick) -> cleaned = @cleanNick nick #console.log cleaned hash = 0 i = 0 while i < cleaned.length hash = cleaned.charCodeAt(i) + (hash << 6) + (hash << 16) - hash i++ hash getColor: (nick) -> nickHash = @getHash nick #console.log "#{nick} -> #{nickHash}" # get a positive value for the hue deg = nickHash % 360 h = (if deg < 0 then 360 + deg else deg) # default L is 50 l = 50 # half of the hues are too light, for those we # decrease lightness l = 30 if h >= 30 and h <= 210 # keep saturation above 20 s = 20 + Math.abs(nickHash) % 80 "hsl(#{h}, #{s}%, #{l}%)" addNick: (nick) -> #console.log "addNick" #console.log this c = @load() return if nick of c color = @getColor nick c[nick] = color @save c @addCss nick, color #console.log c return viewFinishedLoading: -> c = @load() for nick of c @addCss nick, c[nick] document.head.appendChild @css return newMessagePostedToView: (line) -> for e in line.querySelectorAll(".sender, .inline_nickname") do (e) => nick = false if e.className is "inline_nickname" nick = e.innerText e.setAttribute "data-nickname", e.innerText else nick = e.getAttribute "data-nickname" @addNick nick if nick return return addCss: (nick, color) -> @css.textContent += "\n.sender[data-nickname='#{nick}'], " + ".inline_nickname[data-nickname='#{nick}']" + "{ color: #{color} !important; }" return colorNicks = new NickColorizer()
true
"use strict" # colorNicks from https://github.com/hbang/Sapientia-Modifications # * (based on https://github.com/kirbylover4000/irccloud-colornicks # * (based on https://github.com/avidal/irccloud-colornicks # * (based on http://userscripts.org/scripts/show/88258 # * (based on http://chatlogs.musicbrainz.org/mb_chatlogger.user.js)))) # class NickColorizer constructor: () -> @key = 'PI:KEY:<KEY>END_PI' @css = document.createElement('style') @css.id = 'textual-colorNicks' @css.type = 'text/css' @css.media = 'all' # register callbacks Textual.bind 'messageAddedToView', (line) => @newMessagePostedToView line Textual.bind 'viewBodyDidLoad', => @viewFinishedLoading() load: -> val = localStorage.getItem @key #console.log val if val return JSON.parse val else return {} save: (obj) -> localStorage.setItem(@key, JSON.stringify obj) return cleanNick: (nick) -> # attempts to clean up a nickname # by removing alternate characters from the end # nc_ becomes nc, avidal` becomes avidal nick = nick.toLowerCase() # typically ` and _ are used on the end alone nick = nick.replace(/[`_]+$/, '') # remove |<anything> from the end nick = nick.replace(/\|.*$/, '') # remove [<anything>] or {<anything>} from the end nick.replace(/^(!\[|!\{)(.*)(\[.*\]|\{.*\})$/, '$2') getHash: (nick) -> cleaned = @cleanNick nick #console.log cleaned hash = 0 i = 0 while i < cleaned.length hash = cleaned.charCodeAt(i) + (hash << 6) + (hash << 16) - hash i++ hash getColor: (nick) -> nickHash = @getHash nick #console.log "#{nick} -> #{nickHash}" # get a positive value for the hue deg = nickHash % 360 h = (if deg < 0 then 360 + deg else deg) # default L is 50 l = 50 # half of the hues are too light, for those we # decrease lightness l = 30 if h >= 30 and h <= 210 # keep saturation above 20 s = 20 + Math.abs(nickHash) % 80 "hsl(#{h}, #{s}%, #{l}%)" addNick: (nick) -> #console.log "addNick" #console.log this c = @load() return if nick of c color = @getColor nick c[nick] = color @save c @addCss nick, color #console.log c return viewFinishedLoading: -> c = @load() for nick of c @addCss nick, c[nick] document.head.appendChild @css return newMessagePostedToView: (line) -> for e in line.querySelectorAll(".sender, .inline_nickname") do (e) => nick = false if e.className is "inline_nickname" nick = e.innerText e.setAttribute "data-nickname", e.innerText else nick = e.getAttribute "data-nickname" @addNick nick if nick return return addCss: (nick, color) -> @css.textContent += "\n.sender[data-nickname='#{nick}'], " + ".inline_nickname[data-nickname='#{nick}']" + "{ color: #{color} !important; }" return colorNicks = new NickColorizer()
[ { "context": "# Copyright 2013 Jive Software\n#\n# Licensed under the Apache License, Version ", "end": 32, "score": 0.978607714176178, "start": 19, "tag": "NAME", "value": "Jive Software" } ]
applications/props/props-server/lib/db_postgres.coffee
yingjieg/jiveapps
13
# Copyright 2013 Jive Software # # 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. # # DB Abstraction Layer # # # Require Libraries # $ = require 'jquery' util = require './util.js' pg = require 'pg' log = require 'util' fs = require 'fs' # Return a date N days ago daysAgo = (n=0) -> date = new Date() date.setDate date.getDate() - parseInt(n, 10) date # string escape function e = (str) -> str.replace(/'/g, "''") DB = # Standard Callback that will log any db errors and call passed callback, then call done() to return the postgres client to the pool. standardCallback: (callback, query, done) -> (error, result) -> if error log.debug " Postgres error on query #{query}: "+ JSON.stringify error callback error, null done(); callback error, result # padNumber: (number, length) -> # str = '' + (number || 0) # while str.length < length # str = '0' + str # str # Pull a postgres client from the client pool, and use it to run the query. query: (query, callback) -> console.log " Postgres Query " + query pg.connect(util.DB_LOCATION, (err, client, done) -> if err log.debug("connect error: "+JSON.stringify(err)) callback(err); else client.query(query, DB.standardCallback(callback, query, done)); ); parametrizedQuery: (query, params, callback) -> console.log " Postgres Query " + query pg.connect util.DB_LOCATION, (err, client, done) -> if err log.debug "connect error: "+JSON.stringify err else client.query(query, params, DB.standardCallback(callback, query, done)); ## Models Instances: tableName: () -> "jiveinstances" checkRegistration: (jiveInstanceid, callback) -> queryStr = "SELECT EXISTS (SELECT * FROM #{DB.Instances.tableName()} WHERE instanceid='#{jiveInstanceid}');" DB.query queryStr, (err, res) -> if err console.log("Error querying table of jive instances: #{err}") else if (!res.rows[0].exists) DB.Instances.register(jiveInstanceid, callback); else callback(); register: (jiveInstanceid, callback) -> queryStr = "INSERT INTO #{DB.Instances.tableName()} values('#{jiveInstanceid}');" DB.query(queryStr, (err) -> if err && err.code != '23505' log.debug("error registering new instance: #{JSON.stringify err}") callback(err) else if err && err.code == '23505' log.log("jive instance is already registered. resetting...") DB.PropType.resetTable(jiveInstanceid, callback) else log.log("registered new jive instance into props app") DB.PropType.populateTable(jiveInstanceid, callback) ); PropType: tableName: () -> "proptypes" fixtures: () -> require('./defproptypes.js').propTypes; #fill the prop types table with the default prop types populateTable: (jiveInstanceid, callback) -> iterator = (types, done) -> if (types.length == 0) done(); else type = types[0]; DB.PropType.insert jiveInstanceid, type, (err, result) -> if (err) console.log "Error initializing data into PropTypes table: "+ JSON.stringify err else console.log "Adding default prop type: " + JSON.stringify result iterator(types.slice(1), done); iterator(DB.PropType.fixtures().slice(), callback); resetTable: (jiveInstanceid, callback) -> console.log("resetting for instance id:", jiveInstanceid); DB.PropType.delete jiveInstanceid, null, (err) -> if err log.debug "error resetting table: could not delete existing prop types: #{JSON.stringify err}" callback(); else DB.PropType.populateTable(jiveInstanceid, callback) propTypeObjFromRow: (row) -> { $ItemName:row.id, title: row.title, definition: row.definition, image_url: row.image_url, reflection_image_url: row.image_url, level: row.level } findAllByLevel: (jiveInstanceid, level, callback) -> # level = DB.padNumber(level, 4) console.log("getting types for instance id: ", jiveInstanceid); query = "SELECT id, title, definition, level, image_url, jiveInstanceId FROM "+DB.PropType.tableName()+" WHERE jiveInstanceId='#{jiveInstanceid}'" query += " AND level <= '#{e(level)}';" if level DB.query query, (err, result) -> if err callback(err,result) else types = [] for row in result.rows types.push DB.PropType.propTypeObjFromRow row callback(err, types) # find a prop type by its title. Calculates the hash (based on title and instance id) and finds that entry in the DB. findByName: (jiveInstanceid, name, callback) -> id = util.stringHash(name+jiveInstanceid) DB.PropType.findById(jiveInstanceid, id, callback) findById: (jiveInstanceid, id, callback) -> query = "SELECT id, title, definition, level, image_url, jiveInstanceId FROM #{DB.PropType.tableName()} WHERE id='#{id}';"; DB.query query, (err, result) -> if (err) log.debug("findbyname error: "+JSON.stringify err); callback(err) else if(result.rows[0]) callback(null, DB.PropType.propTypeObjFromRow(result.rows[0])); else callback(null, null) fetchImage: (jiveInstanceid, type_id, callback) -> query = "SELECT image FROM #{DB.PropType.tableName()} WHERE jiveinstanceid='#{jiveInstanceid}' AND id='#{type_id}'" DB.query query, (err, result) -> if (err) console.log("error getting image from DB: ", err); callback(404); else if (!(result.rows[0])) console.log("image not found in DB:", result); callback(404); else # console.log("db result: ", result); fs.writeFile 'public/img/prop_types/'+type_id+'.png', result.rows[0].image, () -> callback(200); imageURLWithTimestamp: (jiveInstanceid, id) -> util.BASE_URL+"/props/types/image/"+jiveInstanceid+"/"+id+'/'+((new Date().getTime()/1000) | 0); modify: (jiveInstanceid, body, callback) -> id = util.stringHash(body.title+jiveInstanceid); DB.PropType.findById jiveInstanceid, id, (err, res) -> if err console.log "error finding if this is an edit:", err else if (res) query = "UPDATE #{DB.PropType.tableName()} SET "; if (res.title != e(body.title)) query += "title = '#{e(body.title)}'," if (res.definition != e(body.definition)) query += "definition = '#{e(body.definition)}'," if (res.level != body.level) query += "level = #{body.level}," if (res.image_url != body.image_url) util.download body.image_url, id, () -> filename ="public/img/#{id}.png"; fs.readFile filename, 'hex', (err, img) -> img = '\\x'+img; query += "image = $1,image_url='#{DB.PropType.imageURLWithTimestamp(jiveInstanceid, id)}' WHERE id='#{id}' RETURNING (id,title,definition,level,image_url,jiveInstanceId)"; DB.parametrizedQuery(query, [img], callback) else query = query.slice(0,-1); query += " WHERE id='#{id}' RETURNING (id,title,definition,level,image_url,jiveInstanceId);"; DB.query query, callback else DB.PropType.insert jiveInstanceid, body, (err1, res) -> if err1 callback err1 else callback null, DB.PropType.propTypeObjFromRow res.rows[0] insert: (jiveInstanceid, body, callback) -> id = util.stringHash(body.title+jiveInstanceid) filename = "public/img/#{id}.png" util.download body.image_url, id, () -> fs.readFile filename, 'hex', (err, img) -> img = '\\x'+img; queryStr = "INSERT INTO #{DB.PropType.tableName()} values "; queryStr += "('#{id}','#{e(body.title)}','#{e(body.definition)}','#{body.level}','#{jiveInstanceid}',$1,'#{DB.PropType.imageURLWithTimestamp(jiveInstanceid, id)}')" queryStr += " RETURNING (id,title,definition,level,image_url,jiveInstanceId);"; DB.parametrizedQuery queryStr, [img], callback delete: (jiveInstanceid, id, callback) -> queryStr = "DELETE FROM #{DB.Prop.tableName()} WHERE jiveInstanceId='#{jiveInstanceid}' " #first delete props of the prop type (or all props if this is a reset). if id queryStr += " AND prop_type='#{id}'" queryStr += ";" DB.query queryStr,(err, res) -> if err log.debug("Error deleting props of deleted prop types: #{err}") callback(err, res) else queryStr = "DELETE FROM "+DB.PropType.tableName() queryStr += " WHERE jiveInstanceId='#{jiveInstanceid}'" if id queryStr += " AND id='#{id}'" queryStr += ";" DB.query queryStr, (err1, res1) -> if err1 callback err1, res1 else callback null, res1 Prop: tableName: () -> "props" contentTableName: () -> "linkedcontent" sanitizeOutputCallback: (err, res, callback) -> if res && res.rows for row in res.rows for k,v of row if $.trim(v)=='NULL' row[k]='' callback err, res.rows else callback err, res findAll: (options, callback) -> filters = [] filters.push "user_id = '#{if options.user_id then options.user_id else options.ownerId}'" filters.push "giver_id = '#{options.giver_id}'" if options.giver_id filters.push "prop_type = '#{options.prop_type}'" if options.prop_type filters.push "message = '#{e(options.message)}'" if options.message filters.push "stream_entry_url = '#{e(options.stream_entry_url)}'" if options.stream_entry_url filters.push "created_at IS NOT NULL" query = "SELECT * FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{options.jiveInstanceId}' AND #{filters.join(' AND ')} " query += "ORDER BY created_at desc" DB.query query, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) #find prop by id find: (jiveInstanceId, id, callback) -> queryStr = "SELECT * FROM "+DB.Prop.tableName()+" WHERE jiveInstanceId='#{jiveInstanceId}' AND id='"+id+"';" DB.query queryStr, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) count: (jiveInstanceId, options={}, callback) -> filters = [] filters.push "user_id = '#{e(options.user_id)}'" if options.user_id filters.push "giver_id = '#{e(options.giver_id)}'" if options.giver_id filters.push "prop_type = '#{e(options.prop_type)}'" if options.prop_type and options.prop_type != '@all' filters.push "created_at >= '#{daysAgo(options.days_ago).toISOString()}'" if options.days_ago query = "SELECT count(*) FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{jiveInstanceId}' " query += "AND #{filters.join(' AND ')}" if filters.length > 0 DB.query query, (err, res) -> callback(err, res) #get props for the last 14 days stream: (jiveInstanceId, options={}, callback) -> query = "SELECT * FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{jiveInstanceId}' AND created_at IS NOT NULL AND created_at >= '#{daysAgo(14).toISOString()}' " query += "ORDER BY created_at desc" DB.query query, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) validate: (jiveInstanceId, attrs={}, callback) -> errors = [] # Check for blank fields fields = 'user_id giver_id prop_type message'.split ' ' for field in fields do (field) -> errors.push [field, 'cannot be blank'] if not attrs[field] # Check for duplicates DB.Prop.findAll $.extend(attrs, {jiveInstanceId: jiveInstanceId}), (error, result) -> if error callback [error] else if result.length > 0 errors.push ["prop", "already exists"] callback errors else callback errors initObj: (attrs={}) -> obj = {} content_obj={} obj.user_id = attrs.user_id || 'NULL' # who received the prop obj.giver_id = attrs.giver_id || 'NULL' # who gave the prop obj.prop_type = attrs.prop_type || 'NULL' # the type of prop given (Beer/Genius/CrushedIt/etc) obj.message = attrs.message || 'NULL' # the message the giver said when giving the prop obj.stream_entry_url = attrs.stream_entry_url || 'NULL' # the stream entry associated for this activity obj.original_id = attrs.original_id || 'NULL' # if this is a pile on of an existing prop, the id of the original prop obj.content_id = attrs.content_id || 'NULL' # if associated with a piece of jive content, it's id obj.created_at = 'now' # postgres will interpret this with its timestamp data type content_obj.content_id = attrs.content_id || 'NULL' # if associated with a piece of jive content, it's id content_obj.content_type = attrs.content_type || 'NULL' # if associated with a piece of jive content, it's type content_obj.content_link = attrs.content_link || 'NULL' # if associated with a piece of jive content, it's link content_obj.content_title = attrs.content_title || 'NULL' # if associated with a piece of jive content, it's title return [obj, content_obj] createProp: (jiveInstanceId, attrs, callback) -> DB.Prop.validate jiveInstanceId, attrs, (errors) -> if errors.length > 0 callback errors, null else id = attrs['$ItemName'] or util.guid() obj = DB.Prop.initObj(attrs) makeProp = (hasContent) -> prop = obj[0] queryStr = "INSERT INTO #{DB.Prop.tableName()} " queryStr += " VALUES ('#{e(id)}','#{prop.user_id}','#{prop.giver_id}','#{prop.prop_type}','#{e(prop.message)}','#{e(prop.stream_entry_url)}','#{e(prop.original_id)}','#{e(jiveInstanceId)}','#{prop.created_at}',"; if hasContent queryStr += "'#{e(prop.content_id)}');"; else queryStr += "NULL);"; DB.query queryStr, (err, res) -> if err log.debug("Error creating item: ", JSON.stringify err) callback err, null else log.log("Put new prop into DB: ", JSON.stringify res) callback null, res linkedcontent = obj[1] if linkedcontent.content_id != 'NULL' queryStr = "INSERT INTO #{DB.Prop.contentTableName()} " queryStr = " VALUES ('#{e(linkedcontent.content_id)}','#{e(linkedcontent.content_type)}','#{e(linkedcontent.content_link)}','#{e(linkedcontent.content_title)}','#{jiveInstanceId}'" DB.query queryStr, (err) -> if err log.debug "error putting linked content" else makeProp(true) else makeProp(false) exports.env = DB.env exports.standardCallback = DB.standardCallback exports.init = DB.init exports.PropType = DB.PropType exports.Prop = DB.Prop exports.Instances = DB.Instances
170855
# Copyright 2013 <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. # # DB Abstraction Layer # # # Require Libraries # $ = require 'jquery' util = require './util.js' pg = require 'pg' log = require 'util' fs = require 'fs' # Return a date N days ago daysAgo = (n=0) -> date = new Date() date.setDate date.getDate() - parseInt(n, 10) date # string escape function e = (str) -> str.replace(/'/g, "''") DB = # Standard Callback that will log any db errors and call passed callback, then call done() to return the postgres client to the pool. standardCallback: (callback, query, done) -> (error, result) -> if error log.debug " Postgres error on query #{query}: "+ JSON.stringify error callback error, null done(); callback error, result # padNumber: (number, length) -> # str = '' + (number || 0) # while str.length < length # str = '0' + str # str # Pull a postgres client from the client pool, and use it to run the query. query: (query, callback) -> console.log " Postgres Query " + query pg.connect(util.DB_LOCATION, (err, client, done) -> if err log.debug("connect error: "+JSON.stringify(err)) callback(err); else client.query(query, DB.standardCallback(callback, query, done)); ); parametrizedQuery: (query, params, callback) -> console.log " Postgres Query " + query pg.connect util.DB_LOCATION, (err, client, done) -> if err log.debug "connect error: "+JSON.stringify err else client.query(query, params, DB.standardCallback(callback, query, done)); ## Models Instances: tableName: () -> "jiveinstances" checkRegistration: (jiveInstanceid, callback) -> queryStr = "SELECT EXISTS (SELECT * FROM #{DB.Instances.tableName()} WHERE instanceid='#{jiveInstanceid}');" DB.query queryStr, (err, res) -> if err console.log("Error querying table of jive instances: #{err}") else if (!res.rows[0].exists) DB.Instances.register(jiveInstanceid, callback); else callback(); register: (jiveInstanceid, callback) -> queryStr = "INSERT INTO #{DB.Instances.tableName()} values('#{jiveInstanceid}');" DB.query(queryStr, (err) -> if err && err.code != '23505' log.debug("error registering new instance: #{JSON.stringify err}") callback(err) else if err && err.code == '23505' log.log("jive instance is already registered. resetting...") DB.PropType.resetTable(jiveInstanceid, callback) else log.log("registered new jive instance into props app") DB.PropType.populateTable(jiveInstanceid, callback) ); PropType: tableName: () -> "proptypes" fixtures: () -> require('./defproptypes.js').propTypes; #fill the prop types table with the default prop types populateTable: (jiveInstanceid, callback) -> iterator = (types, done) -> if (types.length == 0) done(); else type = types[0]; DB.PropType.insert jiveInstanceid, type, (err, result) -> if (err) console.log "Error initializing data into PropTypes table: "+ JSON.stringify err else console.log "Adding default prop type: " + JSON.stringify result iterator(types.slice(1), done); iterator(DB.PropType.fixtures().slice(), callback); resetTable: (jiveInstanceid, callback) -> console.log("resetting for instance id:", jiveInstanceid); DB.PropType.delete jiveInstanceid, null, (err) -> if err log.debug "error resetting table: could not delete existing prop types: #{JSON.stringify err}" callback(); else DB.PropType.populateTable(jiveInstanceid, callback) propTypeObjFromRow: (row) -> { $ItemName:row.id, title: row.title, definition: row.definition, image_url: row.image_url, reflection_image_url: row.image_url, level: row.level } findAllByLevel: (jiveInstanceid, level, callback) -> # level = DB.padNumber(level, 4) console.log("getting types for instance id: ", jiveInstanceid); query = "SELECT id, title, definition, level, image_url, jiveInstanceId FROM "+DB.PropType.tableName()+" WHERE jiveInstanceId='#{jiveInstanceid}'" query += " AND level <= '#{e(level)}';" if level DB.query query, (err, result) -> if err callback(err,result) else types = [] for row in result.rows types.push DB.PropType.propTypeObjFromRow row callback(err, types) # find a prop type by its title. Calculates the hash (based on title and instance id) and finds that entry in the DB. findByName: (jiveInstanceid, name, callback) -> id = util.stringHash(name+jiveInstanceid) DB.PropType.findById(jiveInstanceid, id, callback) findById: (jiveInstanceid, id, callback) -> query = "SELECT id, title, definition, level, image_url, jiveInstanceId FROM #{DB.PropType.tableName()} WHERE id='#{id}';"; DB.query query, (err, result) -> if (err) log.debug("findbyname error: "+JSON.stringify err); callback(err) else if(result.rows[0]) callback(null, DB.PropType.propTypeObjFromRow(result.rows[0])); else callback(null, null) fetchImage: (jiveInstanceid, type_id, callback) -> query = "SELECT image FROM #{DB.PropType.tableName()} WHERE jiveinstanceid='#{jiveInstanceid}' AND id='#{type_id}'" DB.query query, (err, result) -> if (err) console.log("error getting image from DB: ", err); callback(404); else if (!(result.rows[0])) console.log("image not found in DB:", result); callback(404); else # console.log("db result: ", result); fs.writeFile 'public/img/prop_types/'+type_id+'.png', result.rows[0].image, () -> callback(200); imageURLWithTimestamp: (jiveInstanceid, id) -> util.BASE_URL+"/props/types/image/"+jiveInstanceid+"/"+id+'/'+((new Date().getTime()/1000) | 0); modify: (jiveInstanceid, body, callback) -> id = util.stringHash(body.title+jiveInstanceid); DB.PropType.findById jiveInstanceid, id, (err, res) -> if err console.log "error finding if this is an edit:", err else if (res) query = "UPDATE #{DB.PropType.tableName()} SET "; if (res.title != e(body.title)) query += "title = '#{e(body.title)}'," if (res.definition != e(body.definition)) query += "definition = '#{e(body.definition)}'," if (res.level != body.level) query += "level = #{body.level}," if (res.image_url != body.image_url) util.download body.image_url, id, () -> filename ="public/img/#{id}.png"; fs.readFile filename, 'hex', (err, img) -> img = '\\x'+img; query += "image = $1,image_url='#{DB.PropType.imageURLWithTimestamp(jiveInstanceid, id)}' WHERE id='#{id}' RETURNING (id,title,definition,level,image_url,jiveInstanceId)"; DB.parametrizedQuery(query, [img], callback) else query = query.slice(0,-1); query += " WHERE id='#{id}' RETURNING (id,title,definition,level,image_url,jiveInstanceId);"; DB.query query, callback else DB.PropType.insert jiveInstanceid, body, (err1, res) -> if err1 callback err1 else callback null, DB.PropType.propTypeObjFromRow res.rows[0] insert: (jiveInstanceid, body, callback) -> id = util.stringHash(body.title+jiveInstanceid) filename = "public/img/#{id}.png" util.download body.image_url, id, () -> fs.readFile filename, 'hex', (err, img) -> img = '\\x'+img; queryStr = "INSERT INTO #{DB.PropType.tableName()} values "; queryStr += "('#{id}','#{e(body.title)}','#{e(body.definition)}','#{body.level}','#{jiveInstanceid}',$1,'#{DB.PropType.imageURLWithTimestamp(jiveInstanceid, id)}')" queryStr += " RETURNING (id,title,definition,level,image_url,jiveInstanceId);"; DB.parametrizedQuery queryStr, [img], callback delete: (jiveInstanceid, id, callback) -> queryStr = "DELETE FROM #{DB.Prop.tableName()} WHERE jiveInstanceId='#{jiveInstanceid}' " #first delete props of the prop type (or all props if this is a reset). if id queryStr += " AND prop_type='#{id}'" queryStr += ";" DB.query queryStr,(err, res) -> if err log.debug("Error deleting props of deleted prop types: #{err}") callback(err, res) else queryStr = "DELETE FROM "+DB.PropType.tableName() queryStr += " WHERE jiveInstanceId='#{jiveInstanceid}'" if id queryStr += " AND id='#{id}'" queryStr += ";" DB.query queryStr, (err1, res1) -> if err1 callback err1, res1 else callback null, res1 Prop: tableName: () -> "props" contentTableName: () -> "linkedcontent" sanitizeOutputCallback: (err, res, callback) -> if res && res.rows for row in res.rows for k,v of row if $.trim(v)=='NULL' row[k]='' callback err, res.rows else callback err, res findAll: (options, callback) -> filters = [] filters.push "user_id = '#{if options.user_id then options.user_id else options.ownerId}'" filters.push "giver_id = '#{options.giver_id}'" if options.giver_id filters.push "prop_type = '#{options.prop_type}'" if options.prop_type filters.push "message = '#{e(options.message)}'" if options.message filters.push "stream_entry_url = '#{e(options.stream_entry_url)}'" if options.stream_entry_url filters.push "created_at IS NOT NULL" query = "SELECT * FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{options.jiveInstanceId}' AND #{filters.join(' AND ')} " query += "ORDER BY created_at desc" DB.query query, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) #find prop by id find: (jiveInstanceId, id, callback) -> queryStr = "SELECT * FROM "+DB.Prop.tableName()+" WHERE jiveInstanceId='#{jiveInstanceId}' AND id='"+id+"';" DB.query queryStr, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) count: (jiveInstanceId, options={}, callback) -> filters = [] filters.push "user_id = '#{e(options.user_id)}'" if options.user_id filters.push "giver_id = '#{e(options.giver_id)}'" if options.giver_id filters.push "prop_type = '#{e(options.prop_type)}'" if options.prop_type and options.prop_type != '@all' filters.push "created_at >= '#{daysAgo(options.days_ago).toISOString()}'" if options.days_ago query = "SELECT count(*) FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{jiveInstanceId}' " query += "AND #{filters.join(' AND ')}" if filters.length > 0 DB.query query, (err, res) -> callback(err, res) #get props for the last 14 days stream: (jiveInstanceId, options={}, callback) -> query = "SELECT * FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{jiveInstanceId}' AND created_at IS NOT NULL AND created_at >= '#{daysAgo(14).toISOString()}' " query += "ORDER BY created_at desc" DB.query query, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) validate: (jiveInstanceId, attrs={}, callback) -> errors = [] # Check for blank fields fields = 'user_id giver_id prop_type message'.split ' ' for field in fields do (field) -> errors.push [field, 'cannot be blank'] if not attrs[field] # Check for duplicates DB.Prop.findAll $.extend(attrs, {jiveInstanceId: jiveInstanceId}), (error, result) -> if error callback [error] else if result.length > 0 errors.push ["prop", "already exists"] callback errors else callback errors initObj: (attrs={}) -> obj = {} content_obj={} obj.user_id = attrs.user_id || 'NULL' # who received the prop obj.giver_id = attrs.giver_id || 'NULL' # who gave the prop obj.prop_type = attrs.prop_type || 'NULL' # the type of prop given (Beer/Genius/CrushedIt/etc) obj.message = attrs.message || 'NULL' # the message the giver said when giving the prop obj.stream_entry_url = attrs.stream_entry_url || 'NULL' # the stream entry associated for this activity obj.original_id = attrs.original_id || 'NULL' # if this is a pile on of an existing prop, the id of the original prop obj.content_id = attrs.content_id || 'NULL' # if associated with a piece of jive content, it's id obj.created_at = 'now' # postgres will interpret this with its timestamp data type content_obj.content_id = attrs.content_id || 'NULL' # if associated with a piece of jive content, it's id content_obj.content_type = attrs.content_type || 'NULL' # if associated with a piece of jive content, it's type content_obj.content_link = attrs.content_link || 'NULL' # if associated with a piece of jive content, it's link content_obj.content_title = attrs.content_title || 'NULL' # if associated with a piece of jive content, it's title return [obj, content_obj] createProp: (jiveInstanceId, attrs, callback) -> DB.Prop.validate jiveInstanceId, attrs, (errors) -> if errors.length > 0 callback errors, null else id = attrs['$ItemName'] or util.guid() obj = DB.Prop.initObj(attrs) makeProp = (hasContent) -> prop = obj[0] queryStr = "INSERT INTO #{DB.Prop.tableName()} " queryStr += " VALUES ('#{e(id)}','#{prop.user_id}','#{prop.giver_id}','#{prop.prop_type}','#{e(prop.message)}','#{e(prop.stream_entry_url)}','#{e(prop.original_id)}','#{e(jiveInstanceId)}','#{prop.created_at}',"; if hasContent queryStr += "'#{e(prop.content_id)}');"; else queryStr += "NULL);"; DB.query queryStr, (err, res) -> if err log.debug("Error creating item: ", JSON.stringify err) callback err, null else log.log("Put new prop into DB: ", JSON.stringify res) callback null, res linkedcontent = obj[1] if linkedcontent.content_id != 'NULL' queryStr = "INSERT INTO #{DB.Prop.contentTableName()} " queryStr = " VALUES ('#{e(linkedcontent.content_id)}','#{e(linkedcontent.content_type)}','#{e(linkedcontent.content_link)}','#{e(linkedcontent.content_title)}','#{jiveInstanceId}'" DB.query queryStr, (err) -> if err log.debug "error putting linked content" else makeProp(true) else makeProp(false) exports.env = DB.env exports.standardCallback = DB.standardCallback exports.init = DB.init exports.PropType = DB.PropType exports.Prop = DB.Prop exports.Instances = DB.Instances
true
# Copyright 2013 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. # # DB Abstraction Layer # # # Require Libraries # $ = require 'jquery' util = require './util.js' pg = require 'pg' log = require 'util' fs = require 'fs' # Return a date N days ago daysAgo = (n=0) -> date = new Date() date.setDate date.getDate() - parseInt(n, 10) date # string escape function e = (str) -> str.replace(/'/g, "''") DB = # Standard Callback that will log any db errors and call passed callback, then call done() to return the postgres client to the pool. standardCallback: (callback, query, done) -> (error, result) -> if error log.debug " Postgres error on query #{query}: "+ JSON.stringify error callback error, null done(); callback error, result # padNumber: (number, length) -> # str = '' + (number || 0) # while str.length < length # str = '0' + str # str # Pull a postgres client from the client pool, and use it to run the query. query: (query, callback) -> console.log " Postgres Query " + query pg.connect(util.DB_LOCATION, (err, client, done) -> if err log.debug("connect error: "+JSON.stringify(err)) callback(err); else client.query(query, DB.standardCallback(callback, query, done)); ); parametrizedQuery: (query, params, callback) -> console.log " Postgres Query " + query pg.connect util.DB_LOCATION, (err, client, done) -> if err log.debug "connect error: "+JSON.stringify err else client.query(query, params, DB.standardCallback(callback, query, done)); ## Models Instances: tableName: () -> "jiveinstances" checkRegistration: (jiveInstanceid, callback) -> queryStr = "SELECT EXISTS (SELECT * FROM #{DB.Instances.tableName()} WHERE instanceid='#{jiveInstanceid}');" DB.query queryStr, (err, res) -> if err console.log("Error querying table of jive instances: #{err}") else if (!res.rows[0].exists) DB.Instances.register(jiveInstanceid, callback); else callback(); register: (jiveInstanceid, callback) -> queryStr = "INSERT INTO #{DB.Instances.tableName()} values('#{jiveInstanceid}');" DB.query(queryStr, (err) -> if err && err.code != '23505' log.debug("error registering new instance: #{JSON.stringify err}") callback(err) else if err && err.code == '23505' log.log("jive instance is already registered. resetting...") DB.PropType.resetTable(jiveInstanceid, callback) else log.log("registered new jive instance into props app") DB.PropType.populateTable(jiveInstanceid, callback) ); PropType: tableName: () -> "proptypes" fixtures: () -> require('./defproptypes.js').propTypes; #fill the prop types table with the default prop types populateTable: (jiveInstanceid, callback) -> iterator = (types, done) -> if (types.length == 0) done(); else type = types[0]; DB.PropType.insert jiveInstanceid, type, (err, result) -> if (err) console.log "Error initializing data into PropTypes table: "+ JSON.stringify err else console.log "Adding default prop type: " + JSON.stringify result iterator(types.slice(1), done); iterator(DB.PropType.fixtures().slice(), callback); resetTable: (jiveInstanceid, callback) -> console.log("resetting for instance id:", jiveInstanceid); DB.PropType.delete jiveInstanceid, null, (err) -> if err log.debug "error resetting table: could not delete existing prop types: #{JSON.stringify err}" callback(); else DB.PropType.populateTable(jiveInstanceid, callback) propTypeObjFromRow: (row) -> { $ItemName:row.id, title: row.title, definition: row.definition, image_url: row.image_url, reflection_image_url: row.image_url, level: row.level } findAllByLevel: (jiveInstanceid, level, callback) -> # level = DB.padNumber(level, 4) console.log("getting types for instance id: ", jiveInstanceid); query = "SELECT id, title, definition, level, image_url, jiveInstanceId FROM "+DB.PropType.tableName()+" WHERE jiveInstanceId='#{jiveInstanceid}'" query += " AND level <= '#{e(level)}';" if level DB.query query, (err, result) -> if err callback(err,result) else types = [] for row in result.rows types.push DB.PropType.propTypeObjFromRow row callback(err, types) # find a prop type by its title. Calculates the hash (based on title and instance id) and finds that entry in the DB. findByName: (jiveInstanceid, name, callback) -> id = util.stringHash(name+jiveInstanceid) DB.PropType.findById(jiveInstanceid, id, callback) findById: (jiveInstanceid, id, callback) -> query = "SELECT id, title, definition, level, image_url, jiveInstanceId FROM #{DB.PropType.tableName()} WHERE id='#{id}';"; DB.query query, (err, result) -> if (err) log.debug("findbyname error: "+JSON.stringify err); callback(err) else if(result.rows[0]) callback(null, DB.PropType.propTypeObjFromRow(result.rows[0])); else callback(null, null) fetchImage: (jiveInstanceid, type_id, callback) -> query = "SELECT image FROM #{DB.PropType.tableName()} WHERE jiveinstanceid='#{jiveInstanceid}' AND id='#{type_id}'" DB.query query, (err, result) -> if (err) console.log("error getting image from DB: ", err); callback(404); else if (!(result.rows[0])) console.log("image not found in DB:", result); callback(404); else # console.log("db result: ", result); fs.writeFile 'public/img/prop_types/'+type_id+'.png', result.rows[0].image, () -> callback(200); imageURLWithTimestamp: (jiveInstanceid, id) -> util.BASE_URL+"/props/types/image/"+jiveInstanceid+"/"+id+'/'+((new Date().getTime()/1000) | 0); modify: (jiveInstanceid, body, callback) -> id = util.stringHash(body.title+jiveInstanceid); DB.PropType.findById jiveInstanceid, id, (err, res) -> if err console.log "error finding if this is an edit:", err else if (res) query = "UPDATE #{DB.PropType.tableName()} SET "; if (res.title != e(body.title)) query += "title = '#{e(body.title)}'," if (res.definition != e(body.definition)) query += "definition = '#{e(body.definition)}'," if (res.level != body.level) query += "level = #{body.level}," if (res.image_url != body.image_url) util.download body.image_url, id, () -> filename ="public/img/#{id}.png"; fs.readFile filename, 'hex', (err, img) -> img = '\\x'+img; query += "image = $1,image_url='#{DB.PropType.imageURLWithTimestamp(jiveInstanceid, id)}' WHERE id='#{id}' RETURNING (id,title,definition,level,image_url,jiveInstanceId)"; DB.parametrizedQuery(query, [img], callback) else query = query.slice(0,-1); query += " WHERE id='#{id}' RETURNING (id,title,definition,level,image_url,jiveInstanceId);"; DB.query query, callback else DB.PropType.insert jiveInstanceid, body, (err1, res) -> if err1 callback err1 else callback null, DB.PropType.propTypeObjFromRow res.rows[0] insert: (jiveInstanceid, body, callback) -> id = util.stringHash(body.title+jiveInstanceid) filename = "public/img/#{id}.png" util.download body.image_url, id, () -> fs.readFile filename, 'hex', (err, img) -> img = '\\x'+img; queryStr = "INSERT INTO #{DB.PropType.tableName()} values "; queryStr += "('#{id}','#{e(body.title)}','#{e(body.definition)}','#{body.level}','#{jiveInstanceid}',$1,'#{DB.PropType.imageURLWithTimestamp(jiveInstanceid, id)}')" queryStr += " RETURNING (id,title,definition,level,image_url,jiveInstanceId);"; DB.parametrizedQuery queryStr, [img], callback delete: (jiveInstanceid, id, callback) -> queryStr = "DELETE FROM #{DB.Prop.tableName()} WHERE jiveInstanceId='#{jiveInstanceid}' " #first delete props of the prop type (or all props if this is a reset). if id queryStr += " AND prop_type='#{id}'" queryStr += ";" DB.query queryStr,(err, res) -> if err log.debug("Error deleting props of deleted prop types: #{err}") callback(err, res) else queryStr = "DELETE FROM "+DB.PropType.tableName() queryStr += " WHERE jiveInstanceId='#{jiveInstanceid}'" if id queryStr += " AND id='#{id}'" queryStr += ";" DB.query queryStr, (err1, res1) -> if err1 callback err1, res1 else callback null, res1 Prop: tableName: () -> "props" contentTableName: () -> "linkedcontent" sanitizeOutputCallback: (err, res, callback) -> if res && res.rows for row in res.rows for k,v of row if $.trim(v)=='NULL' row[k]='' callback err, res.rows else callback err, res findAll: (options, callback) -> filters = [] filters.push "user_id = '#{if options.user_id then options.user_id else options.ownerId}'" filters.push "giver_id = '#{options.giver_id}'" if options.giver_id filters.push "prop_type = '#{options.prop_type}'" if options.prop_type filters.push "message = '#{e(options.message)}'" if options.message filters.push "stream_entry_url = '#{e(options.stream_entry_url)}'" if options.stream_entry_url filters.push "created_at IS NOT NULL" query = "SELECT * FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{options.jiveInstanceId}' AND #{filters.join(' AND ')} " query += "ORDER BY created_at desc" DB.query query, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) #find prop by id find: (jiveInstanceId, id, callback) -> queryStr = "SELECT * FROM "+DB.Prop.tableName()+" WHERE jiveInstanceId='#{jiveInstanceId}' AND id='"+id+"';" DB.query queryStr, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) count: (jiveInstanceId, options={}, callback) -> filters = [] filters.push "user_id = '#{e(options.user_id)}'" if options.user_id filters.push "giver_id = '#{e(options.giver_id)}'" if options.giver_id filters.push "prop_type = '#{e(options.prop_type)}'" if options.prop_type and options.prop_type != '@all' filters.push "created_at >= '#{daysAgo(options.days_ago).toISOString()}'" if options.days_ago query = "SELECT count(*) FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{jiveInstanceId}' " query += "AND #{filters.join(' AND ')}" if filters.length > 0 DB.query query, (err, res) -> callback(err, res) #get props for the last 14 days stream: (jiveInstanceId, options={}, callback) -> query = "SELECT * FROM #{DB.Prop.tableName()} " query += "WHERE jiveInstanceId='#{jiveInstanceId}' AND created_at IS NOT NULL AND created_at >= '#{daysAgo(14).toISOString()}' " query += "ORDER BY created_at desc" DB.query query, (err, res) -> DB.Prop.sanitizeOutputCallback(err, res, callback) validate: (jiveInstanceId, attrs={}, callback) -> errors = [] # Check for blank fields fields = 'user_id giver_id prop_type message'.split ' ' for field in fields do (field) -> errors.push [field, 'cannot be blank'] if not attrs[field] # Check for duplicates DB.Prop.findAll $.extend(attrs, {jiveInstanceId: jiveInstanceId}), (error, result) -> if error callback [error] else if result.length > 0 errors.push ["prop", "already exists"] callback errors else callback errors initObj: (attrs={}) -> obj = {} content_obj={} obj.user_id = attrs.user_id || 'NULL' # who received the prop obj.giver_id = attrs.giver_id || 'NULL' # who gave the prop obj.prop_type = attrs.prop_type || 'NULL' # the type of prop given (Beer/Genius/CrushedIt/etc) obj.message = attrs.message || 'NULL' # the message the giver said when giving the prop obj.stream_entry_url = attrs.stream_entry_url || 'NULL' # the stream entry associated for this activity obj.original_id = attrs.original_id || 'NULL' # if this is a pile on of an existing prop, the id of the original prop obj.content_id = attrs.content_id || 'NULL' # if associated with a piece of jive content, it's id obj.created_at = 'now' # postgres will interpret this with its timestamp data type content_obj.content_id = attrs.content_id || 'NULL' # if associated with a piece of jive content, it's id content_obj.content_type = attrs.content_type || 'NULL' # if associated with a piece of jive content, it's type content_obj.content_link = attrs.content_link || 'NULL' # if associated with a piece of jive content, it's link content_obj.content_title = attrs.content_title || 'NULL' # if associated with a piece of jive content, it's title return [obj, content_obj] createProp: (jiveInstanceId, attrs, callback) -> DB.Prop.validate jiveInstanceId, attrs, (errors) -> if errors.length > 0 callback errors, null else id = attrs['$ItemName'] or util.guid() obj = DB.Prop.initObj(attrs) makeProp = (hasContent) -> prop = obj[0] queryStr = "INSERT INTO #{DB.Prop.tableName()} " queryStr += " VALUES ('#{e(id)}','#{prop.user_id}','#{prop.giver_id}','#{prop.prop_type}','#{e(prop.message)}','#{e(prop.stream_entry_url)}','#{e(prop.original_id)}','#{e(jiveInstanceId)}','#{prop.created_at}',"; if hasContent queryStr += "'#{e(prop.content_id)}');"; else queryStr += "NULL);"; DB.query queryStr, (err, res) -> if err log.debug("Error creating item: ", JSON.stringify err) callback err, null else log.log("Put new prop into DB: ", JSON.stringify res) callback null, res linkedcontent = obj[1] if linkedcontent.content_id != 'NULL' queryStr = "INSERT INTO #{DB.Prop.contentTableName()} " queryStr = " VALUES ('#{e(linkedcontent.content_id)}','#{e(linkedcontent.content_type)}','#{e(linkedcontent.content_link)}','#{e(linkedcontent.content_title)}','#{jiveInstanceId}'" DB.query queryStr, (err) -> if err log.debug "error putting linked content" else makeProp(true) else makeProp(false) exports.env = DB.env exports.standardCallback = DB.standardCallback exports.init = DB.init exports.PropType = DB.PropType exports.Prop = DB.Prop exports.Instances = DB.Instances
[ { "context": "eld2\"]\n\n enter: ->\n @submitWith({field1: \"myEmail@gmail.com\"})\n", "end": 228, "score": 0.9999163150787354, "start": 211, "tag": "EMAIL", "value": "myEmail@gmail.com" } ]
test/integration/widgets/form.coffee
piretmadrus/newPioneer
203
module.exports = -> this.Widgets = this.Widgets || {} return this.Widgets.SimpleForm = this.Widget.Form.extend root: '#form', fields: ["field1", "field2"] enter: -> @submitWith({field1: "myEmail@gmail.com"})
112747
module.exports = -> this.Widgets = this.Widgets || {} return this.Widgets.SimpleForm = this.Widget.Form.extend root: '#form', fields: ["field1", "field2"] enter: -> @submitWith({field1: "<EMAIL>"})
true
module.exports = -> this.Widgets = this.Widgets || {} return this.Widgets.SimpleForm = this.Widget.Form.extend root: '#form', fields: ["field1", "field2"] enter: -> @submitWith({field1: "PI:EMAIL:<EMAIL>END_PI"})
[ { "context": "nc 'save', callback\n # sync 'exists', { name: 'test' }, callback\n sync: (method, rest...) ->\n ", "end": 2270, "score": 0.5561822056770325, "start": 2266, "tag": "NAME", "value": "test" } ]
views/coffee/app/model.coffee
cncolder/vcvs
0
Backbone = require 'backbone' io = require '../io.coffee' # Thanks for moment.js isoRegex = /^\s*\d{4}-\d\d-\d\d(T(\d\d(:\d\d(:\d\d)?)?)?([\+\-]\d\d:?\d\d)?)?/ class Model extends Backbone.Model @connect = (path) -> @prototype.socket = io.conn path constructor: (args) -> @idAttribute = '_id' super args parse: (resp, xhr) -> for key, value of resp resp[key] = date if (isoRegex.test value) and (date = new Date value) and (not isNaN date) resp load: (data) -> data = @parse data @set data, silent: true silentSet: (args...) -> if _.isObject(args[0]) or not args[0]? args[1] ?= {} args[1].silent = true else args[2] ?= {} args[2].silent = true @set args... silentUnset: (args...) -> args[1] ?= {} args[1].silent = true @unset args... toTemplateJSON: -> json = @toJSON() json.createdMoment = moment @get 'createdAt' json.updatedMoment = moment @get 'updatedAt' json # Set a hash of model attributes, and sync the model to the server. # If the server returns an attributes hash that differs, the model's state will be `set` again. save: (callback) -> callback 'invalid' unless @isValid() method = if @isNew() then 'create' else 'update' return callback null, {} if method is 'update' and not @hasChanged() @sync method, (err, data) => unless err? @load data @trigger 'sync', @, data callback err, data # Destroy this model on the server if it was already persisted. # Optimistically removes the model from its collection, if it has one. destroy: (callback) -> if @isNew() callback null @trigger 'destroy', @, @collection else @sync 'destroy', (err, data) -> unless err? @trigger 'destroy', @, @collection callback err, data # Socket.io emit helper. # sync 'hi' # sync 'save', callback # sync 'exists', { name: 'test' }, callback sync: (method, rest...) -> [ data, callback ] = rest if typeof rest[1] is 'function' [ callback ] = rest if typeof rest[0] is 'function' callback ?= ->; data = @changed if method is 'update' data ?= @toJSON?() ? {} # data.id ?= @id if @id? delete data[key] for key in 'createdAt updatedAt'.split /\s+/ socket = @socket ? @constructor.socket socket.emit method, data, callback return module.exports = Model
9401
Backbone = require 'backbone' io = require '../io.coffee' # Thanks for moment.js isoRegex = /^\s*\d{4}-\d\d-\d\d(T(\d\d(:\d\d(:\d\d)?)?)?([\+\-]\d\d:?\d\d)?)?/ class Model extends Backbone.Model @connect = (path) -> @prototype.socket = io.conn path constructor: (args) -> @idAttribute = '_id' super args parse: (resp, xhr) -> for key, value of resp resp[key] = date if (isoRegex.test value) and (date = new Date value) and (not isNaN date) resp load: (data) -> data = @parse data @set data, silent: true silentSet: (args...) -> if _.isObject(args[0]) or not args[0]? args[1] ?= {} args[1].silent = true else args[2] ?= {} args[2].silent = true @set args... silentUnset: (args...) -> args[1] ?= {} args[1].silent = true @unset args... toTemplateJSON: -> json = @toJSON() json.createdMoment = moment @get 'createdAt' json.updatedMoment = moment @get 'updatedAt' json # Set a hash of model attributes, and sync the model to the server. # If the server returns an attributes hash that differs, the model's state will be `set` again. save: (callback) -> callback 'invalid' unless @isValid() method = if @isNew() then 'create' else 'update' return callback null, {} if method is 'update' and not @hasChanged() @sync method, (err, data) => unless err? @load data @trigger 'sync', @, data callback err, data # Destroy this model on the server if it was already persisted. # Optimistically removes the model from its collection, if it has one. destroy: (callback) -> if @isNew() callback null @trigger 'destroy', @, @collection else @sync 'destroy', (err, data) -> unless err? @trigger 'destroy', @, @collection callback err, data # Socket.io emit helper. # sync 'hi' # sync 'save', callback # sync 'exists', { name: '<NAME>' }, callback sync: (method, rest...) -> [ data, callback ] = rest if typeof rest[1] is 'function' [ callback ] = rest if typeof rest[0] is 'function' callback ?= ->; data = @changed if method is 'update' data ?= @toJSON?() ? {} # data.id ?= @id if @id? delete data[key] for key in 'createdAt updatedAt'.split /\s+/ socket = @socket ? @constructor.socket socket.emit method, data, callback return module.exports = Model
true
Backbone = require 'backbone' io = require '../io.coffee' # Thanks for moment.js isoRegex = /^\s*\d{4}-\d\d-\d\d(T(\d\d(:\d\d(:\d\d)?)?)?([\+\-]\d\d:?\d\d)?)?/ class Model extends Backbone.Model @connect = (path) -> @prototype.socket = io.conn path constructor: (args) -> @idAttribute = '_id' super args parse: (resp, xhr) -> for key, value of resp resp[key] = date if (isoRegex.test value) and (date = new Date value) and (not isNaN date) resp load: (data) -> data = @parse data @set data, silent: true silentSet: (args...) -> if _.isObject(args[0]) or not args[0]? args[1] ?= {} args[1].silent = true else args[2] ?= {} args[2].silent = true @set args... silentUnset: (args...) -> args[1] ?= {} args[1].silent = true @unset args... toTemplateJSON: -> json = @toJSON() json.createdMoment = moment @get 'createdAt' json.updatedMoment = moment @get 'updatedAt' json # Set a hash of model attributes, and sync the model to the server. # If the server returns an attributes hash that differs, the model's state will be `set` again. save: (callback) -> callback 'invalid' unless @isValid() method = if @isNew() then 'create' else 'update' return callback null, {} if method is 'update' and not @hasChanged() @sync method, (err, data) => unless err? @load data @trigger 'sync', @, data callback err, data # Destroy this model on the server if it was already persisted. # Optimistically removes the model from its collection, if it has one. destroy: (callback) -> if @isNew() callback null @trigger 'destroy', @, @collection else @sync 'destroy', (err, data) -> unless err? @trigger 'destroy', @, @collection callback err, data # Socket.io emit helper. # sync 'hi' # sync 'save', callback # sync 'exists', { name: 'PI:NAME:<NAME>END_PI' }, callback sync: (method, rest...) -> [ data, callback ] = rest if typeof rest[1] is 'function' [ callback ] = rest if typeof rest[0] is 'function' callback ?= ->; data = @changed if method is 'update' data ?= @toJSON?() ? {} # data.id ?= @id if @id? delete data[key] for key in 'createdAt updatedAt'.split /\s+/ socket = @socket ? @constructor.socket socket.emit method, data, callback return module.exports = Model
[ { "context": "e.js 1.8.3 http://underscorejs.org\n# (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Edit", "end": 1330, "score": 0.9998748302459717, "start": 1315, "tag": "NAME", "value": "Jeremy Ashkenas" } ]
src/lib/Utils.coffee
automata/noflo
1
# NoFlo - Flow-Based Programming for JavaScript # (c) 2014 TheGrid (Rituwall Inc.) # NoFlo may be freely distributed under the MIT license # # Generic object clone. From CS cookbook clone = (obj) -> if not obj? or typeof obj isnt 'object' return obj if obj instanceof Date return new Date(obj.getTime()) if obj instanceof RegExp flags = '' flags += 'g' if obj.global? flags += 'i' if obj.ignoreCase? flags += 'm' if obj.multiline? flags += 'y' if obj.sticky? return new RegExp(obj.source, flags) newInstance = new obj.constructor() for key of obj newInstance[key] = clone obj[key] return newInstance # Guess language from filename guessLanguageFromFilename = (filename) -> return 'coffeescript' if /.*\.coffee$/.test filename return 'javascript' isArray = (obj) -> return Array.isArray(obj) if Array.isArray return Object.prototype.toString.call(arg) == '[object Array]' isObject = (obj) -> type = typeof(obj) type == 'function' or type == 'object' and ! !obj unique = (array) -> output = {} output[array[key]] = array[key] for key in [0...array.length] value for key, value of output # the following functions are from http://underscorejs.org/docs/underscore.html # Underscore.js 1.8.3 http://underscorejs.org # (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors # Underscore may be freely distributed under the MIT license. # Internal function that returns an efficient (for current engines) # version of the passed-in callback, # to be repeatedly applied in other Underscore functions. optimizeCb = (func, context, argCount) -> if context == undefined return func switch (if argCount == null then 3 else argCount) when 1 return (value) -> func.call context, value when 2 return (value, other) -> func.call context, value, other when 3 return (value, index, collection) -> func.call context, value, index, collection when 4 return (accumulator, value, index, collection) -> func.call context, accumulator, value, index, collection -> func.apply context, arguments # Create a reducing function iterating left or right. # Optimized iterator function as using arguments.length in the main function # will deoptimize the, see #1991. createReduce = (dir) -> iterator = (obj, iteratee, memo, keys, index, length) -> while index >= 0 and index < length currentKey = if keys then keys[index] else index memo = iteratee(memo, obj[currentKey], currentKey, obj) index += dir memo return (obj, iteratee, memo, context) -> iteratee = optimizeCb(iteratee, context, 4) keys = Object.keys obj length = (keys or obj).length index = if dir > 0 then 0 else length - 1 if arguments.length < 3 memo = obj[if keys then keys[index] else index] index += dir iterator obj, iteratee, memo, keys, index, length reduceRight = createReduce(-1) # Returns a function, that, as long as it continues to be invoked, # will not be triggered. # The function will be called after it stops being called for N milliseconds. # If immediate is passed, trigger the function on the leading edge, # instead of the trailing. debounce = (func, wait, immediate) -> timeout = undefined args = undefined context = undefined timestamp = undefined result = undefined later = -> last = Date.now - timestamp if last < wait and last >= 0 timeout = setTimeout(later, wait - last) else timeout = null if !immediate result = func.apply(context, args) if !timeout context = args = null return -> context = this args = arguments timestamp = Date.now callNow = immediate and !timeout if !timeout timeout = setTimeout(later, wait) if callNow result = func.apply(context, args) context = args = null result # Retrieve the names of an object’s own properties. # Delegates to ECMAScript 5‘s native Object.keys getKeys = (obj) -> if !isObject obj return [] if Object.keys return Object.keys(obj) keys = [] for key of obj if obj.has key keys.push key keys # Retrieve the values of an object’s properties. getValues = (obj) -> keys = getKeys obj length = keys.length values = Array(length) i = 0 while i < length values[i] = obj[keys[i]] i++ values # Determine if the array or object contains a given item (using ===). # Aliased as includes and include. contains = (obj, item, fromIndex) -> if !isArray obj obj = getValues obj if typeof fromIndex != 'number' or guard fromIndex = 0 obj.indexOf(item) >= 0 # Produce an array that contains every item # shared between all the passed-in arrays. intersection = (array) -> result = [] argsLength = arguments.length for i in [0..array.length] item = array[i] continue if contains result, item for j in [1..argsLength] break if !contains arguments[j], item result.push item if j is argsLength result exports.clone = clone exports.guessLanguageFromFilename = guessLanguageFromFilename exports.optimizeCb = optimizeCb exports.reduceRight = reduceRight exports.debounce = debounce exports.unique = unique exports.intersection = intersection exports.getValues = getValues
83092
# NoFlo - Flow-Based Programming for JavaScript # (c) 2014 TheGrid (Rituwall Inc.) # NoFlo may be freely distributed under the MIT license # # Generic object clone. From CS cookbook clone = (obj) -> if not obj? or typeof obj isnt 'object' return obj if obj instanceof Date return new Date(obj.getTime()) if obj instanceof RegExp flags = '' flags += 'g' if obj.global? flags += 'i' if obj.ignoreCase? flags += 'm' if obj.multiline? flags += 'y' if obj.sticky? return new RegExp(obj.source, flags) newInstance = new obj.constructor() for key of obj newInstance[key] = clone obj[key] return newInstance # Guess language from filename guessLanguageFromFilename = (filename) -> return 'coffeescript' if /.*\.coffee$/.test filename return 'javascript' isArray = (obj) -> return Array.isArray(obj) if Array.isArray return Object.prototype.toString.call(arg) == '[object Array]' isObject = (obj) -> type = typeof(obj) type == 'function' or type == 'object' and ! !obj unique = (array) -> output = {} output[array[key]] = array[key] for key in [0...array.length] value for key, value of output # the following functions are from http://underscorejs.org/docs/underscore.html # Underscore.js 1.8.3 http://underscorejs.org # (c) 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors # Underscore may be freely distributed under the MIT license. # Internal function that returns an efficient (for current engines) # version of the passed-in callback, # to be repeatedly applied in other Underscore functions. optimizeCb = (func, context, argCount) -> if context == undefined return func switch (if argCount == null then 3 else argCount) when 1 return (value) -> func.call context, value when 2 return (value, other) -> func.call context, value, other when 3 return (value, index, collection) -> func.call context, value, index, collection when 4 return (accumulator, value, index, collection) -> func.call context, accumulator, value, index, collection -> func.apply context, arguments # Create a reducing function iterating left or right. # Optimized iterator function as using arguments.length in the main function # will deoptimize the, see #1991. createReduce = (dir) -> iterator = (obj, iteratee, memo, keys, index, length) -> while index >= 0 and index < length currentKey = if keys then keys[index] else index memo = iteratee(memo, obj[currentKey], currentKey, obj) index += dir memo return (obj, iteratee, memo, context) -> iteratee = optimizeCb(iteratee, context, 4) keys = Object.keys obj length = (keys or obj).length index = if dir > 0 then 0 else length - 1 if arguments.length < 3 memo = obj[if keys then keys[index] else index] index += dir iterator obj, iteratee, memo, keys, index, length reduceRight = createReduce(-1) # Returns a function, that, as long as it continues to be invoked, # will not be triggered. # The function will be called after it stops being called for N milliseconds. # If immediate is passed, trigger the function on the leading edge, # instead of the trailing. debounce = (func, wait, immediate) -> timeout = undefined args = undefined context = undefined timestamp = undefined result = undefined later = -> last = Date.now - timestamp if last < wait and last >= 0 timeout = setTimeout(later, wait - last) else timeout = null if !immediate result = func.apply(context, args) if !timeout context = args = null return -> context = this args = arguments timestamp = Date.now callNow = immediate and !timeout if !timeout timeout = setTimeout(later, wait) if callNow result = func.apply(context, args) context = args = null result # Retrieve the names of an object’s own properties. # Delegates to ECMAScript 5‘s native Object.keys getKeys = (obj) -> if !isObject obj return [] if Object.keys return Object.keys(obj) keys = [] for key of obj if obj.has key keys.push key keys # Retrieve the values of an object’s properties. getValues = (obj) -> keys = getKeys obj length = keys.length values = Array(length) i = 0 while i < length values[i] = obj[keys[i]] i++ values # Determine if the array or object contains a given item (using ===). # Aliased as includes and include. contains = (obj, item, fromIndex) -> if !isArray obj obj = getValues obj if typeof fromIndex != 'number' or guard fromIndex = 0 obj.indexOf(item) >= 0 # Produce an array that contains every item # shared between all the passed-in arrays. intersection = (array) -> result = [] argsLength = arguments.length for i in [0..array.length] item = array[i] continue if contains result, item for j in [1..argsLength] break if !contains arguments[j], item result.push item if j is argsLength result exports.clone = clone exports.guessLanguageFromFilename = guessLanguageFromFilename exports.optimizeCb = optimizeCb exports.reduceRight = reduceRight exports.debounce = debounce exports.unique = unique exports.intersection = intersection exports.getValues = getValues
true
# NoFlo - Flow-Based Programming for JavaScript # (c) 2014 TheGrid (Rituwall Inc.) # NoFlo may be freely distributed under the MIT license # # Generic object clone. From CS cookbook clone = (obj) -> if not obj? or typeof obj isnt 'object' return obj if obj instanceof Date return new Date(obj.getTime()) if obj instanceof RegExp flags = '' flags += 'g' if obj.global? flags += 'i' if obj.ignoreCase? flags += 'm' if obj.multiline? flags += 'y' if obj.sticky? return new RegExp(obj.source, flags) newInstance = new obj.constructor() for key of obj newInstance[key] = clone obj[key] return newInstance # Guess language from filename guessLanguageFromFilename = (filename) -> return 'coffeescript' if /.*\.coffee$/.test filename return 'javascript' isArray = (obj) -> return Array.isArray(obj) if Array.isArray return Object.prototype.toString.call(arg) == '[object Array]' isObject = (obj) -> type = typeof(obj) type == 'function' or type == 'object' and ! !obj unique = (array) -> output = {} output[array[key]] = array[key] for key in [0...array.length] value for key, value of output # the following functions are from http://underscorejs.org/docs/underscore.html # Underscore.js 1.8.3 http://underscorejs.org # (c) 2009-2015 PI:NAME:<NAME>END_PI, DocumentCloud and Investigative Reporters & Editors # Underscore may be freely distributed under the MIT license. # Internal function that returns an efficient (for current engines) # version of the passed-in callback, # to be repeatedly applied in other Underscore functions. optimizeCb = (func, context, argCount) -> if context == undefined return func switch (if argCount == null then 3 else argCount) when 1 return (value) -> func.call context, value when 2 return (value, other) -> func.call context, value, other when 3 return (value, index, collection) -> func.call context, value, index, collection when 4 return (accumulator, value, index, collection) -> func.call context, accumulator, value, index, collection -> func.apply context, arguments # Create a reducing function iterating left or right. # Optimized iterator function as using arguments.length in the main function # will deoptimize the, see #1991. createReduce = (dir) -> iterator = (obj, iteratee, memo, keys, index, length) -> while index >= 0 and index < length currentKey = if keys then keys[index] else index memo = iteratee(memo, obj[currentKey], currentKey, obj) index += dir memo return (obj, iteratee, memo, context) -> iteratee = optimizeCb(iteratee, context, 4) keys = Object.keys obj length = (keys or obj).length index = if dir > 0 then 0 else length - 1 if arguments.length < 3 memo = obj[if keys then keys[index] else index] index += dir iterator obj, iteratee, memo, keys, index, length reduceRight = createReduce(-1) # Returns a function, that, as long as it continues to be invoked, # will not be triggered. # The function will be called after it stops being called for N milliseconds. # If immediate is passed, trigger the function on the leading edge, # instead of the trailing. debounce = (func, wait, immediate) -> timeout = undefined args = undefined context = undefined timestamp = undefined result = undefined later = -> last = Date.now - timestamp if last < wait and last >= 0 timeout = setTimeout(later, wait - last) else timeout = null if !immediate result = func.apply(context, args) if !timeout context = args = null return -> context = this args = arguments timestamp = Date.now callNow = immediate and !timeout if !timeout timeout = setTimeout(later, wait) if callNow result = func.apply(context, args) context = args = null result # Retrieve the names of an object’s own properties. # Delegates to ECMAScript 5‘s native Object.keys getKeys = (obj) -> if !isObject obj return [] if Object.keys return Object.keys(obj) keys = [] for key of obj if obj.has key keys.push key keys # Retrieve the values of an object’s properties. getValues = (obj) -> keys = getKeys obj length = keys.length values = Array(length) i = 0 while i < length values[i] = obj[keys[i]] i++ values # Determine if the array or object contains a given item (using ===). # Aliased as includes and include. contains = (obj, item, fromIndex) -> if !isArray obj obj = getValues obj if typeof fromIndex != 'number' or guard fromIndex = 0 obj.indexOf(item) >= 0 # Produce an array that contains every item # shared between all the passed-in arrays. intersection = (array) -> result = [] argsLength = arguments.length for i in [0..array.length] item = array[i] continue if contains result, item for j in [1..argsLength] break if !contains arguments[j], item result.push item if j is argsLength result exports.clone = clone exports.guessLanguageFromFilename = guessLanguageFromFilename exports.optimizeCb = optimizeCb exports.reduceRight = reduceRight exports.debounce = debounce exports.unique = unique exports.intersection = intersection exports.getValues = getValues
[ { "context": "e-break-on-single-newline': ->\n keyPath = 'markdown-preview-kramdown.breakOnSingleNewline'\n atom.config.set(keyPath, not atom.config", "end": 4092, "score": 0.9993647336959839, "start": 4046, "tag": "KEY", "value": "markdown-preview-kramdown.breakOnSingleNewline...
lib/markdown-preview-view.coffee
grimmer0125/markdown-preview-kramdown
4
path = require 'path' {Emitter, Disposable, CompositeDisposable, File} = require 'atom' _ = require 'underscore-plus' fs = require 'fs-plus' renderer = require './renderer' module.exports = class MarkdownPreviewView @deserialize: (params) -> new MarkdownPreviewView(params) constructor: ({@editorId, @filePath}) -> @element = document.createElement('div') @element.classList.add('markdown-preview-kramdown') @element.tabIndex = -1 @emitter = new Emitter @loaded = false @disposables = new CompositeDisposable @registerScrollCommands() if @editorId? @resolveEditor(@editorId) else if atom.packages.hasActivatedInitialPackages() @subscribeToFilePath(@filePath) else @disposables.add atom.packages.onDidActivateInitialPackages => @subscribeToFilePath(@filePath) serialize: -> deserializer: 'MarkdownPreviewView' filePath: @getPath() ? @filePath editorId: @editorId copy: -> new MarkdownPreviewView({@editorId, filePath: @getPath() ? @filePath}) destroy: -> @disposables.dispose() @element.remove() registerScrollCommands: -> @disposables.add(atom.commands.add(@element, { 'core:move-up': => @element.scrollTop -= document.body.offsetHeight / 20 return 'core:move-down': => @element.scrollTop += document.body.offsetHeight / 20 return 'core:page-up': => @element.scrollTop -= @element.offsetHeight return 'core:page-down': => @element.scrollTop += @element.offsetHeight return 'core:move-to-top': => @element.scrollTop = 0 return 'core:move-to-bottom': => @element.scrollTop = @element.scrollHeight return })) return onDidChangeTitle: (callback) -> @emitter.on 'did-change-title', callback onDidChangeModified: (callback) -> # No op to suppress deprecation warning new Disposable onDidChangeMarkdown: (callback) -> @emitter.on 'did-change-markdown', callback subscribeToFilePath: (filePath) -> @file = new File(filePath) @emitter.emit 'did-change-title' @disposables.add @file.onDidRename => @emitter.emit 'did-change-title' @handleEvents() @renderMarkdown() resolveEditor: (editorId) -> resolve = => @editor = @editorForId(editorId) if @editor? @emitter.emit 'did-change-title' @disposables.add @editor.onDidDestroy => @subscribeToFilePath(@getPath()) @handleEvents() @renderMarkdown() else @subscribeToFilePath(@filePath) if atom.packages.hasActivatedInitialPackages() resolve() else @disposables.add atom.packages.onDidActivateInitialPackages(resolve) editorForId: (editorId) -> for editor in atom.workspace.getTextEditors() return editor if editor.id?.toString() is editorId.toString() null handleEvents: -> lazyRenderMarkdown = _.debounce((=> @renderMarkdown()), 250) @disposables.add atom.grammars.onDidAddGrammar -> lazyRenderMarkdown() if typeof atom.grammars.onDidRemoveGrammar is 'function' @disposables.add atom.grammars.onDidRemoveGrammar -> lazyRenderMarkdown() else # TODO: Remove onDidUpdateGrammar hook once onDidRemoveGrammar is released @disposables.add atom.grammars.onDidUpdateGrammar -> lazyRenderMarkdown() atom.commands.add @element, 'core:copy': (event) => event.stopPropagation() @copyToClipboard() 'markdown-preview-kramdown:select-all': => @selectAll() 'markdown-preview-kramdown:zoom-in': => zoomLevel = parseFloat(getComputedStyle(@element).zoom) @element.style.zoom = zoomLevel + 0.1 'markdown-preview-kramdown:zoom-out': => zoomLevel = parseFloat(getComputedStyle(@element).zoom) @element.style.zoom = zoomLevel - 0.1 'markdown-preview-kramdown:reset-zoom': => @element.style.zoom = 1 'markdown-preview-kramdown:toggle-break-on-single-newline': -> keyPath = 'markdown-preview-kramdown.breakOnSingleNewline' atom.config.set(keyPath, not atom.config.get(keyPath)) 'markdown-preview-kramdown:toggle-github-style': -> keyPath = 'markdown-preview-kramdown.useGitHubStyle' atom.config.set(keyPath, not atom.config.get(keyPath)) changeHandler = => @renderMarkdown() pane = atom.workspace.paneForItem(this) if pane? and pane isnt atom.workspace.getActivePane() pane.activateItem(this) if @file? @disposables.add @file.onDidChange(changeHandler) else if @editor? @disposables.add @editor.getBuffer().onDidStopChanging -> changeHandler() if atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add @editor.onDidChangePath => @emitter.emit 'did-change-title' @disposables.add @editor.getBuffer().onDidSave -> changeHandler() unless atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add @editor.getBuffer().onDidReload -> changeHandler() unless atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add atom.config.onDidChange 'markdown-preview-kramdown.breakOnSingleNewline', changeHandler @disposables.add atom.config.observe 'markdown-preview-kramdown.useGitHubStyle', (useGitHubStyle) => if useGitHubStyle @element.setAttribute('data-use-github-style', '') else @element.removeAttribute('data-use-github-style') document.onselectionchange = => selection = window.getSelection() selectedNode = selection.baseNode if selectedNode is null or @element is selectedNode or @element.contains(selectedNode) if selection.isCollapsed @element.classList.remove('has-selection') else @element.classList.add('has-selection') renderMarkdown: -> @showLoading() unless @loaded @getMarkdownSource() .then (source) => @renderMarkdownText(source) if source? .catch (reason) => @showError({message: reason}) getMarkdownSource: -> if @file?.getPath() @file.read().then (source) => if source is null Promise.reject("#{@file.getBaseName()} could not be found") else Promise.resolve(source) .catch (reason) -> Promise.reject(reason) else if @editor? Promise.resolve(@editor.getText()) else Promise.reject() getHTML: (callback) -> @getMarkdownSource().then (source) => return unless source? renderer.toHTML source, @getPath(), @getGrammar(), callback renderMarkdownText: (text) -> scrollTop = @element.scrollTop renderer.toDOMFragment text, @getPath(), @getGrammar(), (error, domFragment) => if error @showError(error) else @loading = false @loaded = true @element.textContent = '' @element.appendChild(domFragment) @emitter.emit 'did-change-markdown' @element.scrollTop = scrollTop getTitle: -> if @file? and @getPath()? "#{path.basename(@getPath())} Preview" else if @editor? "#{@editor.getTitle()} Preview" else "Markdown Preview" getIconName: -> "markdown" getURI: -> if @file? "markdown-preview-kramdown://#{@getPath()}" else "markdown-preview-kramdown://editor/#{@editorId}" getPath: -> if @file? @file.getPath() else if @editor? @editor.getPath() getGrammar: -> @editor?.getGrammar() getDocumentStyleSheets: -> # This function exists so we can stub it document.styleSheets getTextEditorStyles: -> textEditorStyles = document.createElement("atom-styles") textEditorStyles.initialize(atom.styles) textEditorStyles.setAttribute "context", "atom-text-editor" document.body.appendChild textEditorStyles # Extract style elements content Array.prototype.slice.apply(textEditorStyles.childNodes).map (styleElement) -> styleElement.innerText getMarkdownPreviewCSS: -> markdownPreviewRules = [] ruleRegExp = /\.markdown-preview-kramdown/ cssUrlRegExp = /url\(atom:\/\/markdown-preview-kramdown\/assets\/(.*)\)/ for stylesheet in @getDocumentStyleSheets() if stylesheet.rules? for rule in stylesheet.rules # We only need `.markdown-review` css markdownPreviewRules.push(rule.cssText) if rule.selectorText?.match(ruleRegExp)? markdownPreviewRules .concat(@getTextEditorStyles()) .join('\n') .replace(/atom-text-editor/g, 'pre.editor-colors') .replace(/:host/g, '.host') # Remove shadow-dom :host selector causing problem on FF .replace cssUrlRegExp, (match, assetsName, offset, string) -> # base64 encode assets assetPath = path.join __dirname, '../assets', assetsName originalData = fs.readFileSync assetPath, 'binary' base64Data = new Buffer(originalData, 'binary').toString('base64') "url('data:image/jpeg;base64,#{base64Data}')" showError: (result) -> @element.textContent = '' h2 = document.createElement('h2') h2.textContent = 'Previewing Markdown Failed' @element.appendChild(h2) if failureMessage = result?.message h3 = document.createElement('h3') h3.textContent = failureMessage @element.appendChild(h3) showLoading: -> @loading = true @element.textContent = '' div = document.createElement('div') div.classList.add('markdown-spinner') div.textContent = 'Loading Markdown\u2026' @element.appendChild(div) selectAll: -> return if @loading selection = window.getSelection() selection.removeAllRanges() range = document.createRange() range.selectNodeContents(@element) selection.addRange(range) copyToClipboard: -> return if @loading selection = window.getSelection() selectedText = selection.toString() selectedNode = selection.baseNode # Use default copy event handler if there is selected text inside this view if selectedText and selectedNode? and (@element is selectedNode or @element.contains(selectedNode)) atom.clipboard.write(selectedText) else @getHTML (error, html) -> if error? atom.notifications.addError('Copying Markdown as HTML failed', {dismissable: true, detail: error.message}) else atom.clipboard.write(html) getSaveDialogOptions: -> defaultPath = @getPath() if defaultPath defaultPath += '.html' else defaultPath = 'untitled.md.html' if projectPath = atom.project.getPaths()[0] defaultPath = path.join(projectPath, defaultPath) return {defaultPath} saveAs: (htmlFilePath) -> if @loading atom.notifications.addWarning('Please wait until the Markdown Preview has finished loading before saving') return filePath = @getPath() title = 'Markdown to HTML' if filePath title = path.parse(filePath).name @getHTML (error, htmlBody) => if error? throw error else html = """ <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>#{title}</title> <style>#{@getMarkdownPreviewCSS()}</style> </head> <body class='markdown-preview-kramdown' data-use-github-style>#{htmlBody}</body> </html>""" + "\n" # Ensure trailing newline fs.writeFileSync(htmlFilePath, html) atom.workspace.open(htmlFilePath)
10300
path = require 'path' {Emitter, Disposable, CompositeDisposable, File} = require 'atom' _ = require 'underscore-plus' fs = require 'fs-plus' renderer = require './renderer' module.exports = class MarkdownPreviewView @deserialize: (params) -> new MarkdownPreviewView(params) constructor: ({@editorId, @filePath}) -> @element = document.createElement('div') @element.classList.add('markdown-preview-kramdown') @element.tabIndex = -1 @emitter = new Emitter @loaded = false @disposables = new CompositeDisposable @registerScrollCommands() if @editorId? @resolveEditor(@editorId) else if atom.packages.hasActivatedInitialPackages() @subscribeToFilePath(@filePath) else @disposables.add atom.packages.onDidActivateInitialPackages => @subscribeToFilePath(@filePath) serialize: -> deserializer: 'MarkdownPreviewView' filePath: @getPath() ? @filePath editorId: @editorId copy: -> new MarkdownPreviewView({@editorId, filePath: @getPath() ? @filePath}) destroy: -> @disposables.dispose() @element.remove() registerScrollCommands: -> @disposables.add(atom.commands.add(@element, { 'core:move-up': => @element.scrollTop -= document.body.offsetHeight / 20 return 'core:move-down': => @element.scrollTop += document.body.offsetHeight / 20 return 'core:page-up': => @element.scrollTop -= @element.offsetHeight return 'core:page-down': => @element.scrollTop += @element.offsetHeight return 'core:move-to-top': => @element.scrollTop = 0 return 'core:move-to-bottom': => @element.scrollTop = @element.scrollHeight return })) return onDidChangeTitle: (callback) -> @emitter.on 'did-change-title', callback onDidChangeModified: (callback) -> # No op to suppress deprecation warning new Disposable onDidChangeMarkdown: (callback) -> @emitter.on 'did-change-markdown', callback subscribeToFilePath: (filePath) -> @file = new File(filePath) @emitter.emit 'did-change-title' @disposables.add @file.onDidRename => @emitter.emit 'did-change-title' @handleEvents() @renderMarkdown() resolveEditor: (editorId) -> resolve = => @editor = @editorForId(editorId) if @editor? @emitter.emit 'did-change-title' @disposables.add @editor.onDidDestroy => @subscribeToFilePath(@getPath()) @handleEvents() @renderMarkdown() else @subscribeToFilePath(@filePath) if atom.packages.hasActivatedInitialPackages() resolve() else @disposables.add atom.packages.onDidActivateInitialPackages(resolve) editorForId: (editorId) -> for editor in atom.workspace.getTextEditors() return editor if editor.id?.toString() is editorId.toString() null handleEvents: -> lazyRenderMarkdown = _.debounce((=> @renderMarkdown()), 250) @disposables.add atom.grammars.onDidAddGrammar -> lazyRenderMarkdown() if typeof atom.grammars.onDidRemoveGrammar is 'function' @disposables.add atom.grammars.onDidRemoveGrammar -> lazyRenderMarkdown() else # TODO: Remove onDidUpdateGrammar hook once onDidRemoveGrammar is released @disposables.add atom.grammars.onDidUpdateGrammar -> lazyRenderMarkdown() atom.commands.add @element, 'core:copy': (event) => event.stopPropagation() @copyToClipboard() 'markdown-preview-kramdown:select-all': => @selectAll() 'markdown-preview-kramdown:zoom-in': => zoomLevel = parseFloat(getComputedStyle(@element).zoom) @element.style.zoom = zoomLevel + 0.1 'markdown-preview-kramdown:zoom-out': => zoomLevel = parseFloat(getComputedStyle(@element).zoom) @element.style.zoom = zoomLevel - 0.1 'markdown-preview-kramdown:reset-zoom': => @element.style.zoom = 1 'markdown-preview-kramdown:toggle-break-on-single-newline': -> keyPath = '<KEY>' atom.config.set(keyPath, not atom.config.get(keyPath)) 'markdown-preview-kramdown:toggle-github-style': -> keyPath = '<KEY>' atom.config.set(keyPath, not atom.config.get(keyPath)) changeHandler = => @renderMarkdown() pane = atom.workspace.paneForItem(this) if pane? and pane isnt atom.workspace.getActivePane() pane.activateItem(this) if @file? @disposables.add @file.onDidChange(changeHandler) else if @editor? @disposables.add @editor.getBuffer().onDidStopChanging -> changeHandler() if atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add @editor.onDidChangePath => @emitter.emit 'did-change-title' @disposables.add @editor.getBuffer().onDidSave -> changeHandler() unless atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add @editor.getBuffer().onDidReload -> changeHandler() unless atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add atom.config.onDidChange 'markdown-preview-kramdown.breakOnSingleNewline', changeHandler @disposables.add atom.config.observe 'markdown-preview-kramdown.useGitHubStyle', (useGitHubStyle) => if useGitHubStyle @element.setAttribute('data-use-github-style', '') else @element.removeAttribute('data-use-github-style') document.onselectionchange = => selection = window.getSelection() selectedNode = selection.baseNode if selectedNode is null or @element is selectedNode or @element.contains(selectedNode) if selection.isCollapsed @element.classList.remove('has-selection') else @element.classList.add('has-selection') renderMarkdown: -> @showLoading() unless @loaded @getMarkdownSource() .then (source) => @renderMarkdownText(source) if source? .catch (reason) => @showError({message: reason}) getMarkdownSource: -> if @file?.getPath() @file.read().then (source) => if source is null Promise.reject("#{@file.getBaseName()} could not be found") else Promise.resolve(source) .catch (reason) -> Promise.reject(reason) else if @editor? Promise.resolve(@editor.getText()) else Promise.reject() getHTML: (callback) -> @getMarkdownSource().then (source) => return unless source? renderer.toHTML source, @getPath(), @getGrammar(), callback renderMarkdownText: (text) -> scrollTop = @element.scrollTop renderer.toDOMFragment text, @getPath(), @getGrammar(), (error, domFragment) => if error @showError(error) else @loading = false @loaded = true @element.textContent = '' @element.appendChild(domFragment) @emitter.emit 'did-change-markdown' @element.scrollTop = scrollTop getTitle: -> if @file? and @getPath()? "#{path.basename(@getPath())} Preview" else if @editor? "#{@editor.getTitle()} Preview" else "Markdown Preview" getIconName: -> "markdown" getURI: -> if @file? "markdown-preview-kramdown://#{@getPath()}" else "markdown-preview-kramdown://editor/#{@editorId}" getPath: -> if @file? @file.getPath() else if @editor? @editor.getPath() getGrammar: -> @editor?.getGrammar() getDocumentStyleSheets: -> # This function exists so we can stub it document.styleSheets getTextEditorStyles: -> textEditorStyles = document.createElement("atom-styles") textEditorStyles.initialize(atom.styles) textEditorStyles.setAttribute "context", "atom-text-editor" document.body.appendChild textEditorStyles # Extract style elements content Array.prototype.slice.apply(textEditorStyles.childNodes).map (styleElement) -> styleElement.innerText getMarkdownPreviewCSS: -> markdownPreviewRules = [] ruleRegExp = /\.markdown-preview-kramdown/ cssUrlRegExp = /url\(atom:\/\/markdown-preview-kramdown\/assets\/(.*)\)/ for stylesheet in @getDocumentStyleSheets() if stylesheet.rules? for rule in stylesheet.rules # We only need `.markdown-review` css markdownPreviewRules.push(rule.cssText) if rule.selectorText?.match(ruleRegExp)? markdownPreviewRules .concat(@getTextEditorStyles()) .join('\n') .replace(/atom-text-editor/g, 'pre.editor-colors') .replace(/:host/g, '.host') # Remove shadow-dom :host selector causing problem on FF .replace cssUrlRegExp, (match, assetsName, offset, string) -> # base64 encode assets assetPath = path.join __dirname, '../assets', assetsName originalData = fs.readFileSync assetPath, 'binary' base64Data = new Buffer(originalData, 'binary').toString('base64') "url('data:image/jpeg;base64,#{base64Data}')" showError: (result) -> @element.textContent = '' h2 = document.createElement('h2') h2.textContent = 'Previewing Markdown Failed' @element.appendChild(h2) if failureMessage = result?.message h3 = document.createElement('h3') h3.textContent = failureMessage @element.appendChild(h3) showLoading: -> @loading = true @element.textContent = '' div = document.createElement('div') div.classList.add('markdown-spinner') div.textContent = 'Loading Markdown\u2026' @element.appendChild(div) selectAll: -> return if @loading selection = window.getSelection() selection.removeAllRanges() range = document.createRange() range.selectNodeContents(@element) selection.addRange(range) copyToClipboard: -> return if @loading selection = window.getSelection() selectedText = selection.toString() selectedNode = selection.baseNode # Use default copy event handler if there is selected text inside this view if selectedText and selectedNode? and (@element is selectedNode or @element.contains(selectedNode)) atom.clipboard.write(selectedText) else @getHTML (error, html) -> if error? atom.notifications.addError('Copying Markdown as HTML failed', {dismissable: true, detail: error.message}) else atom.clipboard.write(html) getSaveDialogOptions: -> defaultPath = @getPath() if defaultPath defaultPath += '.html' else defaultPath = 'untitled.md.html' if projectPath = atom.project.getPaths()[0] defaultPath = path.join(projectPath, defaultPath) return {defaultPath} saveAs: (htmlFilePath) -> if @loading atom.notifications.addWarning('Please wait until the Markdown Preview has finished loading before saving') return filePath = @getPath() title = 'Markdown to HTML' if filePath title = path.parse(filePath).name @getHTML (error, htmlBody) => if error? throw error else html = """ <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>#{title}</title> <style>#{@getMarkdownPreviewCSS()}</style> </head> <body class='markdown-preview-kramdown' data-use-github-style>#{htmlBody}</body> </html>""" + "\n" # Ensure trailing newline fs.writeFileSync(htmlFilePath, html) atom.workspace.open(htmlFilePath)
true
path = require 'path' {Emitter, Disposable, CompositeDisposable, File} = require 'atom' _ = require 'underscore-plus' fs = require 'fs-plus' renderer = require './renderer' module.exports = class MarkdownPreviewView @deserialize: (params) -> new MarkdownPreviewView(params) constructor: ({@editorId, @filePath}) -> @element = document.createElement('div') @element.classList.add('markdown-preview-kramdown') @element.tabIndex = -1 @emitter = new Emitter @loaded = false @disposables = new CompositeDisposable @registerScrollCommands() if @editorId? @resolveEditor(@editorId) else if atom.packages.hasActivatedInitialPackages() @subscribeToFilePath(@filePath) else @disposables.add atom.packages.onDidActivateInitialPackages => @subscribeToFilePath(@filePath) serialize: -> deserializer: 'MarkdownPreviewView' filePath: @getPath() ? @filePath editorId: @editorId copy: -> new MarkdownPreviewView({@editorId, filePath: @getPath() ? @filePath}) destroy: -> @disposables.dispose() @element.remove() registerScrollCommands: -> @disposables.add(atom.commands.add(@element, { 'core:move-up': => @element.scrollTop -= document.body.offsetHeight / 20 return 'core:move-down': => @element.scrollTop += document.body.offsetHeight / 20 return 'core:page-up': => @element.scrollTop -= @element.offsetHeight return 'core:page-down': => @element.scrollTop += @element.offsetHeight return 'core:move-to-top': => @element.scrollTop = 0 return 'core:move-to-bottom': => @element.scrollTop = @element.scrollHeight return })) return onDidChangeTitle: (callback) -> @emitter.on 'did-change-title', callback onDidChangeModified: (callback) -> # No op to suppress deprecation warning new Disposable onDidChangeMarkdown: (callback) -> @emitter.on 'did-change-markdown', callback subscribeToFilePath: (filePath) -> @file = new File(filePath) @emitter.emit 'did-change-title' @disposables.add @file.onDidRename => @emitter.emit 'did-change-title' @handleEvents() @renderMarkdown() resolveEditor: (editorId) -> resolve = => @editor = @editorForId(editorId) if @editor? @emitter.emit 'did-change-title' @disposables.add @editor.onDidDestroy => @subscribeToFilePath(@getPath()) @handleEvents() @renderMarkdown() else @subscribeToFilePath(@filePath) if atom.packages.hasActivatedInitialPackages() resolve() else @disposables.add atom.packages.onDidActivateInitialPackages(resolve) editorForId: (editorId) -> for editor in atom.workspace.getTextEditors() return editor if editor.id?.toString() is editorId.toString() null handleEvents: -> lazyRenderMarkdown = _.debounce((=> @renderMarkdown()), 250) @disposables.add atom.grammars.onDidAddGrammar -> lazyRenderMarkdown() if typeof atom.grammars.onDidRemoveGrammar is 'function' @disposables.add atom.grammars.onDidRemoveGrammar -> lazyRenderMarkdown() else # TODO: Remove onDidUpdateGrammar hook once onDidRemoveGrammar is released @disposables.add atom.grammars.onDidUpdateGrammar -> lazyRenderMarkdown() atom.commands.add @element, 'core:copy': (event) => event.stopPropagation() @copyToClipboard() 'markdown-preview-kramdown:select-all': => @selectAll() 'markdown-preview-kramdown:zoom-in': => zoomLevel = parseFloat(getComputedStyle(@element).zoom) @element.style.zoom = zoomLevel + 0.1 'markdown-preview-kramdown:zoom-out': => zoomLevel = parseFloat(getComputedStyle(@element).zoom) @element.style.zoom = zoomLevel - 0.1 'markdown-preview-kramdown:reset-zoom': => @element.style.zoom = 1 'markdown-preview-kramdown:toggle-break-on-single-newline': -> keyPath = 'PI:KEY:<KEY>END_PI' atom.config.set(keyPath, not atom.config.get(keyPath)) 'markdown-preview-kramdown:toggle-github-style': -> keyPath = 'PI:KEY:<KEY>END_PI' atom.config.set(keyPath, not atom.config.get(keyPath)) changeHandler = => @renderMarkdown() pane = atom.workspace.paneForItem(this) if pane? and pane isnt atom.workspace.getActivePane() pane.activateItem(this) if @file? @disposables.add @file.onDidChange(changeHandler) else if @editor? @disposables.add @editor.getBuffer().onDidStopChanging -> changeHandler() if atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add @editor.onDidChangePath => @emitter.emit 'did-change-title' @disposables.add @editor.getBuffer().onDidSave -> changeHandler() unless atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add @editor.getBuffer().onDidReload -> changeHandler() unless atom.config.get 'markdown-preview-kramdown.liveUpdate' @disposables.add atom.config.onDidChange 'markdown-preview-kramdown.breakOnSingleNewline', changeHandler @disposables.add atom.config.observe 'markdown-preview-kramdown.useGitHubStyle', (useGitHubStyle) => if useGitHubStyle @element.setAttribute('data-use-github-style', '') else @element.removeAttribute('data-use-github-style') document.onselectionchange = => selection = window.getSelection() selectedNode = selection.baseNode if selectedNode is null or @element is selectedNode or @element.contains(selectedNode) if selection.isCollapsed @element.classList.remove('has-selection') else @element.classList.add('has-selection') renderMarkdown: -> @showLoading() unless @loaded @getMarkdownSource() .then (source) => @renderMarkdownText(source) if source? .catch (reason) => @showError({message: reason}) getMarkdownSource: -> if @file?.getPath() @file.read().then (source) => if source is null Promise.reject("#{@file.getBaseName()} could not be found") else Promise.resolve(source) .catch (reason) -> Promise.reject(reason) else if @editor? Promise.resolve(@editor.getText()) else Promise.reject() getHTML: (callback) -> @getMarkdownSource().then (source) => return unless source? renderer.toHTML source, @getPath(), @getGrammar(), callback renderMarkdownText: (text) -> scrollTop = @element.scrollTop renderer.toDOMFragment text, @getPath(), @getGrammar(), (error, domFragment) => if error @showError(error) else @loading = false @loaded = true @element.textContent = '' @element.appendChild(domFragment) @emitter.emit 'did-change-markdown' @element.scrollTop = scrollTop getTitle: -> if @file? and @getPath()? "#{path.basename(@getPath())} Preview" else if @editor? "#{@editor.getTitle()} Preview" else "Markdown Preview" getIconName: -> "markdown" getURI: -> if @file? "markdown-preview-kramdown://#{@getPath()}" else "markdown-preview-kramdown://editor/#{@editorId}" getPath: -> if @file? @file.getPath() else if @editor? @editor.getPath() getGrammar: -> @editor?.getGrammar() getDocumentStyleSheets: -> # This function exists so we can stub it document.styleSheets getTextEditorStyles: -> textEditorStyles = document.createElement("atom-styles") textEditorStyles.initialize(atom.styles) textEditorStyles.setAttribute "context", "atom-text-editor" document.body.appendChild textEditorStyles # Extract style elements content Array.prototype.slice.apply(textEditorStyles.childNodes).map (styleElement) -> styleElement.innerText getMarkdownPreviewCSS: -> markdownPreviewRules = [] ruleRegExp = /\.markdown-preview-kramdown/ cssUrlRegExp = /url\(atom:\/\/markdown-preview-kramdown\/assets\/(.*)\)/ for stylesheet in @getDocumentStyleSheets() if stylesheet.rules? for rule in stylesheet.rules # We only need `.markdown-review` css markdownPreviewRules.push(rule.cssText) if rule.selectorText?.match(ruleRegExp)? markdownPreviewRules .concat(@getTextEditorStyles()) .join('\n') .replace(/atom-text-editor/g, 'pre.editor-colors') .replace(/:host/g, '.host') # Remove shadow-dom :host selector causing problem on FF .replace cssUrlRegExp, (match, assetsName, offset, string) -> # base64 encode assets assetPath = path.join __dirname, '../assets', assetsName originalData = fs.readFileSync assetPath, 'binary' base64Data = new Buffer(originalData, 'binary').toString('base64') "url('data:image/jpeg;base64,#{base64Data}')" showError: (result) -> @element.textContent = '' h2 = document.createElement('h2') h2.textContent = 'Previewing Markdown Failed' @element.appendChild(h2) if failureMessage = result?.message h3 = document.createElement('h3') h3.textContent = failureMessage @element.appendChild(h3) showLoading: -> @loading = true @element.textContent = '' div = document.createElement('div') div.classList.add('markdown-spinner') div.textContent = 'Loading Markdown\u2026' @element.appendChild(div) selectAll: -> return if @loading selection = window.getSelection() selection.removeAllRanges() range = document.createRange() range.selectNodeContents(@element) selection.addRange(range) copyToClipboard: -> return if @loading selection = window.getSelection() selectedText = selection.toString() selectedNode = selection.baseNode # Use default copy event handler if there is selected text inside this view if selectedText and selectedNode? and (@element is selectedNode or @element.contains(selectedNode)) atom.clipboard.write(selectedText) else @getHTML (error, html) -> if error? atom.notifications.addError('Copying Markdown as HTML failed', {dismissable: true, detail: error.message}) else atom.clipboard.write(html) getSaveDialogOptions: -> defaultPath = @getPath() if defaultPath defaultPath += '.html' else defaultPath = 'untitled.md.html' if projectPath = atom.project.getPaths()[0] defaultPath = path.join(projectPath, defaultPath) return {defaultPath} saveAs: (htmlFilePath) -> if @loading atom.notifications.addWarning('Please wait until the Markdown Preview has finished loading before saving') return filePath = @getPath() title = 'Markdown to HTML' if filePath title = path.parse(filePath).name @getHTML (error, htmlBody) => if error? throw error else html = """ <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>#{title}</title> <style>#{@getMarkdownPreviewCSS()}</style> </head> <body class='markdown-preview-kramdown' data-use-github-style>#{htmlBody}</body> </html>""" + "\n" # Ensure trailing newline fs.writeFileSync(htmlFilePath, html) atom.workspace.open(htmlFilePath)
[ { "context": "###\n * cena_auth\n * https://github.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan Gaus\n * Li", "end": 46, "score": 0.9957606792449951, "start": 39, "tag": "USERNAME", "value": "1egoman" }, { "context": "thub.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan ...
src/frontend/app.coffee
1egoman/cena_app
0
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 Ryan Gaus * Licensed under the MIT license. ### 'use strict'; @app = angular.module 'Cena', [ 'ui.bootstrap' 'ngRoute' 'ngResource' 'hc.marked' ]
31746
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. ### 'use strict'; @app = angular.module 'Cena', [ 'ui.bootstrap' 'ngRoute' 'ngResource' 'hc.marked' ]
true
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### 'use strict'; @app = angular.module 'Cena', [ 'ui.bootstrap' 'ngRoute' 'ngResource' 'hc.marked' ]
[ { "context": "can', 'Asian']\n people: [\n { 'name': 'moe', 'age': 40 }\n { 'name': 'larry', 'age': 5", "end": 2439, "score": 0.9996395707130432, "start": 2436, "tag": "NAME", "value": "moe" }, { "context": " { 'name': 'moe', 'age': 40 }\n { 'name': 'larry'...
source/spec/spec-data.coffee
anodynos/uBerscore
1
define -> prop1 = 'aProp1.1': "o1.aVal1.1" 'aProp1.2': "o1.aVal1.2" object1 = aProp2: "o1.aVal2" object1.aProp1 = Object.create prop1 object2 = Object.create object1 object2.aProp2 = "o2.aVal2-1" object3 = Object.create object2 _.extend object3, aProp2: "o3.aVal2-2" aProp3: [1, '2', 3, {aProp4:"o3.aVal3"}] objectWithProtoInheritedProps = Object.create object3 objectWithProtoInheritedProps.aProp0 = "o0.aVal0" class Class0 constructor:-> @aProp0 = 'o0.aVal0' class Class1 extends Class0 aProp1: prop1 aProp2: "o1.aVal2" class Class2 extends Class1 aProp2: "o2.aVal2-1" class Class3 extends Class2 aProp2: "o3.aVal2-2" aProp3: [1, '2', 3, {aProp4:"o3.aVal3"}] c3 = new Class3 expectedPropertyValues = aProp0: 'o0.aVal0' aProp1: 'aProp1.1': "o1.aVal1.1" 'aProp1.2': "o1.aVal1.2" aProp2: "o3.aVal2-2" aProp3: [1,'2',3,{aProp4:"o3.aVal3"}] ### Inheritance (simple): A simple object, with : - 2 shallow clones, - 2 deep clones - 2 inherited ### object = p1: 1 p2: {p2_2: 3} objectShallowClone1 = p1: 1 p2: object.p2 objectShallowClone2 = _.clone object objectDeepClone1 = p1: 1 p2: {p2_2: 3} objectDeepClone2 = _.clone object, true # shallow inherited inheritedShallowCloneParent = p2: object.p2 # can't do this in IE : `inheritedShallowClone.__proto__ = inheritedShallowCloneParent` inheritedShallowClone = Object.create inheritedShallowCloneParent inheritedShallowClone.p1 = 1 # deep inherited inheritedDeepCloneParent = p2: {p2_2: 3} # inheritedDeepClone.__proto__ = inheritedDeepCloneParent inheritedDeepClone = Object.create inheritedDeepCloneParent inheritedDeepClone.p1 = 1 ### Defaults deep merging: the experiment. We have 3 environments, each with its own defaults. They range from generic 'earth', specilizing to the 'laboratory' and finally the fine-tuned 'laboratory'. We blend them in different ways to see what comes out. ### earth = name: 'earthDefaults' environment: temperature: 20 gravity: 9.80 moisture: min: 10 life: true laboratory = name: 'laboratoryDefaults' environment: temperature: 35 moisture: max: 40 life: races: ['Caucasian', 'African', 'Asian'] people: [ { 'name': 'moe', 'age': 40 } { 'name': 'larry', 'age': 50 } ] experiment = name: 'experimentDefaults' environment: gravity: 1.5 temperature: null life: races: ['Kafkasian', 'ApHriCan', 'Azian', 'Mutant'] people: [ { 'name': 'moe', 'age': 400 } { 'name': 'blanka', 'age': 20 } { 'name': 'ken', 'age': 25 } { 'name': 'ryu', 'age': 28 } { 'name': 'larry', 'age': 500 } ] results:success:false ### Results (for _B.DeepDefaultsBlender.blend) ### earth_laboratory_experiment = # earth is 1st (more important) than laboratory & experiment. Earth's default prevail. name: 'earthDefaults' # <-- by earth(was undefined) environment: temperature: 20 # <-- by earth(was undefined) gravity: 9.80 # <-- by earth(was undefined) moisture: # <-- by earth(was undefined) min: 10 # <-- by earth(was undefined) max: 40 # <-- by laboratory(was undefined) life: true # <-- by earth(was undefined) results:success:false # <-- by experiment (was undefined) experiment_laboratory_earth = # experiment is 1st (more important) than laboratory & earth name: 'experimentDefaults' # <-- by experiment (was undefined) environment: gravity: 1.5 # <-- by experiment (was undefined) temperature: 35 # <-- added by laboratory (was null) moisture: max: 40 # <-- added by laboratory (was undefined) min: 10 # <-- added by earth (was undefined) life: # <-- by experiment (was undefined) races: ['Kafkasian', 'ApHriCan', 'Azian', 'Mutant'] people: [ # <-- by experiment (was undefined) { 'name': 'moe', 'age': 400 } { 'name': 'blanka', 'age': 20 } { 'name': 'ken', 'age': 25 } { 'name': 'ryu', 'age': 28 } { 'name': 'larry', 'age': 500 } ] results:success:false # <-- by experiment (was undefined) laboratory_experiment = # laboratory is 1st (more important) than experiment name: 'laboratoryDefaults' # <-- by experiment (was undefined) environment: gravity: 1.5 # <-- by experiment (was undefined) temperature: 35 # <-- added by laboratory (was null) moisture: max: 40 # <-- added by laboratory (was undefined) life: # <-- by experiment (was undefined) races: ['Caucasian', 'African', 'Asian', 'Mutant'] # <-- retained at index 0,1,2 from laboratory (not was undefined) people: [ # <-- merged with experiment (was undefined) { 'name': 'moe', 'age': 40 } # <-- retained from laboratory (not was undefined) { 'name': 'larry', 'age': 50 } # <-- retained from laboratory (not was undefined) { 'name': 'ken', 'age': 25 } { 'name': 'ryu', 'age': 28 } { 'name': 'larry', 'age': 500 } ] results:success:false # <-- by experiment (was undefined) { # module.exports = data module objectWithProtoInheritedProps Class3 c3 expectedPropertyValues # simple object with 2+2+2 clones object objectShallowClone1 objectShallowClone2 objectDeepClone1 objectDeepClone2 inheritedShallowClone inheritedDeepClone # various data obj: ciba: 4, aaa: 7, b: 2, c: -1 arrInt: [ 4, 7, 2, -1 ] arrInt2: [7, -1, 3, 5] arrStr: ['Pikoulas', 'Anodynos', 'Babylon', 'Agelos'] ### The experiment ### earth laboratory experiment earth_laboratory_experiment experiment_laboratory_earth laboratory_experiment ### Defaults merging ### team: 'enabled': true 'bundleRoot': '/team' 'compilers': # 'coffee-script': # params: true # 'urequire': enabled: true 'rjs-build': 'team-rjs' project: 'bundleRoot': '/team/project' 'compilers': 'rjs-build': 'project-rjs-build' bundle: 'bundleRoot': '/team/project/bundle' 'compilers': 'coffee-script': 'params': 'w b' 'urequire': 'scanPrevent': true ### Results ### bundle_project_team: 'enabled': true 'bundleRoot': '/team/project/bundle' 'compilers': 'coffee-script': # <- changed by someBundle 'params': 'w b' 'urequire': # <- changed by someBundle 'scanPrevent': true 'rjs-build': 'project-rjs-build' # <- changed by project }
114380
define -> prop1 = 'aProp1.1': "o1.aVal1.1" 'aProp1.2': "o1.aVal1.2" object1 = aProp2: "o1.aVal2" object1.aProp1 = Object.create prop1 object2 = Object.create object1 object2.aProp2 = "o2.aVal2-1" object3 = Object.create object2 _.extend object3, aProp2: "o3.aVal2-2" aProp3: [1, '2', 3, {aProp4:"o3.aVal3"}] objectWithProtoInheritedProps = Object.create object3 objectWithProtoInheritedProps.aProp0 = "o0.aVal0" class Class0 constructor:-> @aProp0 = 'o0.aVal0' class Class1 extends Class0 aProp1: prop1 aProp2: "o1.aVal2" class Class2 extends Class1 aProp2: "o2.aVal2-1" class Class3 extends Class2 aProp2: "o3.aVal2-2" aProp3: [1, '2', 3, {aProp4:"o3.aVal3"}] c3 = new Class3 expectedPropertyValues = aProp0: 'o0.aVal0' aProp1: 'aProp1.1': "o1.aVal1.1" 'aProp1.2': "o1.aVal1.2" aProp2: "o3.aVal2-2" aProp3: [1,'2',3,{aProp4:"o3.aVal3"}] ### Inheritance (simple): A simple object, with : - 2 shallow clones, - 2 deep clones - 2 inherited ### object = p1: 1 p2: {p2_2: 3} objectShallowClone1 = p1: 1 p2: object.p2 objectShallowClone2 = _.clone object objectDeepClone1 = p1: 1 p2: {p2_2: 3} objectDeepClone2 = _.clone object, true # shallow inherited inheritedShallowCloneParent = p2: object.p2 # can't do this in IE : `inheritedShallowClone.__proto__ = inheritedShallowCloneParent` inheritedShallowClone = Object.create inheritedShallowCloneParent inheritedShallowClone.p1 = 1 # deep inherited inheritedDeepCloneParent = p2: {p2_2: 3} # inheritedDeepClone.__proto__ = inheritedDeepCloneParent inheritedDeepClone = Object.create inheritedDeepCloneParent inheritedDeepClone.p1 = 1 ### Defaults deep merging: the experiment. We have 3 environments, each with its own defaults. They range from generic 'earth', specilizing to the 'laboratory' and finally the fine-tuned 'laboratory'. We blend them in different ways to see what comes out. ### earth = name: 'earthDefaults' environment: temperature: 20 gravity: 9.80 moisture: min: 10 life: true laboratory = name: 'laboratoryDefaults' environment: temperature: 35 moisture: max: 40 life: races: ['Caucasian', 'African', 'Asian'] people: [ { 'name': '<NAME>', 'age': 40 } { 'name': '<NAME>', 'age': 50 } ] experiment = name: 'experimentDefaults' environment: gravity: 1.5 temperature: null life: races: ['Kafkasian', 'ApHriCan', 'Azian', 'Mutant'] people: [ { 'name': '<NAME>', 'age': 400 } { 'name': '<NAME>', 'age': 20 } { 'name': '<NAME>', 'age': 25 } { 'name': '<NAME>', 'age': 28 } { 'name': '<NAME>', 'age': 500 } ] results:success:false ### Results (for _B.DeepDefaultsBlender.blend) ### earth_laboratory_experiment = # earth is 1st (more important) than laboratory & experiment. Earth's default prevail. name: 'earthDefaults' # <-- by earth(was undefined) environment: temperature: 20 # <-- by earth(was undefined) gravity: 9.80 # <-- by earth(was undefined) moisture: # <-- by earth(was undefined) min: 10 # <-- by earth(was undefined) max: 40 # <-- by laboratory(was undefined) life: true # <-- by earth(was undefined) results:success:false # <-- by experiment (was undefined) experiment_laboratory_earth = # experiment is 1st (more important) than laboratory & earth name: 'experimentDefaults' # <-- by experiment (was undefined) environment: gravity: 1.5 # <-- by experiment (was undefined) temperature: 35 # <-- added by laboratory (was null) moisture: max: 40 # <-- added by laboratory (was undefined) min: 10 # <-- added by earth (was undefined) life: # <-- by experiment (was undefined) races: ['Kafkasian', 'ApHriCan', 'Azian', 'Mutant'] people: [ # <-- by experiment (was undefined) { 'name': '<NAME>', 'age': 400 } { 'name': '<NAME>', 'age': 20 } { 'name': '<NAME>', 'age': 25 } { 'name': '<NAME>', 'age': 28 } { 'name': '<NAME>', 'age': 500 } ] results:success:false # <-- by experiment (was undefined) laboratory_experiment = # laboratory is 1st (more important) than experiment name: 'laboratoryDefaults' # <-- by experiment (was undefined) environment: gravity: 1.5 # <-- by experiment (was undefined) temperature: 35 # <-- added by laboratory (was null) moisture: max: 40 # <-- added by laboratory (was undefined) life: # <-- by experiment (was undefined) races: ['Caucasian', 'African', 'Asian', 'Mutant'] # <-- retained at index 0,1,2 from laboratory (not was undefined) people: [ # <-- merged with experiment (was undefined) { 'name': '<NAME>', 'age': 40 } # <-- retained from laboratory (not was undefined) { 'name': '<NAME>', 'age': 50 } # <-- retained from laboratory (not was undefined) { 'name': '<NAME>', 'age': 25 } { 'name': '<NAME>', 'age': 28 } { 'name': '<NAME>', 'age': 500 } ] results:success:false # <-- by experiment (was undefined) { # module.exports = data module objectWithProtoInheritedProps Class3 c3 expectedPropertyValues # simple object with 2+2+2 clones object objectShallowClone1 objectShallowClone2 objectDeepClone1 objectDeepClone2 inheritedShallowClone inheritedDeepClone # various data obj: ciba: 4, aaa: 7, b: 2, c: -1 arrInt: [ 4, 7, 2, -1 ] arrInt2: [7, -1, 3, 5] arrStr: ['Pikoulas', 'Anodynos', 'Babylon', 'Agelos'] ### The experiment ### earth laboratory experiment earth_laboratory_experiment experiment_laboratory_earth laboratory_experiment ### Defaults merging ### team: 'enabled': true 'bundleRoot': '/team' 'compilers': # 'coffee-script': # params: true # 'urequire': enabled: true 'rjs-build': 'team-rjs' project: 'bundleRoot': '/team/project' 'compilers': 'rjs-build': 'project-rjs-build' bundle: 'bundleRoot': '/team/project/bundle' 'compilers': 'coffee-script': 'params': 'w b' 'urequire': 'scanPrevent': true ### Results ### bundle_project_team: 'enabled': true 'bundleRoot': '/team/project/bundle' 'compilers': 'coffee-script': # <- changed by someBundle 'params': 'w b' 'urequire': # <- changed by someBundle 'scanPrevent': true 'rjs-build': 'project-rjs-build' # <- changed by project }
true
define -> prop1 = 'aProp1.1': "o1.aVal1.1" 'aProp1.2': "o1.aVal1.2" object1 = aProp2: "o1.aVal2" object1.aProp1 = Object.create prop1 object2 = Object.create object1 object2.aProp2 = "o2.aVal2-1" object3 = Object.create object2 _.extend object3, aProp2: "o3.aVal2-2" aProp3: [1, '2', 3, {aProp4:"o3.aVal3"}] objectWithProtoInheritedProps = Object.create object3 objectWithProtoInheritedProps.aProp0 = "o0.aVal0" class Class0 constructor:-> @aProp0 = 'o0.aVal0' class Class1 extends Class0 aProp1: prop1 aProp2: "o1.aVal2" class Class2 extends Class1 aProp2: "o2.aVal2-1" class Class3 extends Class2 aProp2: "o3.aVal2-2" aProp3: [1, '2', 3, {aProp4:"o3.aVal3"}] c3 = new Class3 expectedPropertyValues = aProp0: 'o0.aVal0' aProp1: 'aProp1.1': "o1.aVal1.1" 'aProp1.2': "o1.aVal1.2" aProp2: "o3.aVal2-2" aProp3: [1,'2',3,{aProp4:"o3.aVal3"}] ### Inheritance (simple): A simple object, with : - 2 shallow clones, - 2 deep clones - 2 inherited ### object = p1: 1 p2: {p2_2: 3} objectShallowClone1 = p1: 1 p2: object.p2 objectShallowClone2 = _.clone object objectDeepClone1 = p1: 1 p2: {p2_2: 3} objectDeepClone2 = _.clone object, true # shallow inherited inheritedShallowCloneParent = p2: object.p2 # can't do this in IE : `inheritedShallowClone.__proto__ = inheritedShallowCloneParent` inheritedShallowClone = Object.create inheritedShallowCloneParent inheritedShallowClone.p1 = 1 # deep inherited inheritedDeepCloneParent = p2: {p2_2: 3} # inheritedDeepClone.__proto__ = inheritedDeepCloneParent inheritedDeepClone = Object.create inheritedDeepCloneParent inheritedDeepClone.p1 = 1 ### Defaults deep merging: the experiment. We have 3 environments, each with its own defaults. They range from generic 'earth', specilizing to the 'laboratory' and finally the fine-tuned 'laboratory'. We blend them in different ways to see what comes out. ### earth = name: 'earthDefaults' environment: temperature: 20 gravity: 9.80 moisture: min: 10 life: true laboratory = name: 'laboratoryDefaults' environment: temperature: 35 moisture: max: 40 life: races: ['Caucasian', 'African', 'Asian'] people: [ { 'name': 'PI:NAME:<NAME>END_PI', 'age': 40 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 50 } ] experiment = name: 'experimentDefaults' environment: gravity: 1.5 temperature: null life: races: ['Kafkasian', 'ApHriCan', 'Azian', 'Mutant'] people: [ { 'name': 'PI:NAME:<NAME>END_PI', 'age': 400 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 20 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 25 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 28 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 500 } ] results:success:false ### Results (for _B.DeepDefaultsBlender.blend) ### earth_laboratory_experiment = # earth is 1st (more important) than laboratory & experiment. Earth's default prevail. name: 'earthDefaults' # <-- by earth(was undefined) environment: temperature: 20 # <-- by earth(was undefined) gravity: 9.80 # <-- by earth(was undefined) moisture: # <-- by earth(was undefined) min: 10 # <-- by earth(was undefined) max: 40 # <-- by laboratory(was undefined) life: true # <-- by earth(was undefined) results:success:false # <-- by experiment (was undefined) experiment_laboratory_earth = # experiment is 1st (more important) than laboratory & earth name: 'experimentDefaults' # <-- by experiment (was undefined) environment: gravity: 1.5 # <-- by experiment (was undefined) temperature: 35 # <-- added by laboratory (was null) moisture: max: 40 # <-- added by laboratory (was undefined) min: 10 # <-- added by earth (was undefined) life: # <-- by experiment (was undefined) races: ['Kafkasian', 'ApHriCan', 'Azian', 'Mutant'] people: [ # <-- by experiment (was undefined) { 'name': 'PI:NAME:<NAME>END_PI', 'age': 400 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 20 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 25 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 28 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 500 } ] results:success:false # <-- by experiment (was undefined) laboratory_experiment = # laboratory is 1st (more important) than experiment name: 'laboratoryDefaults' # <-- by experiment (was undefined) environment: gravity: 1.5 # <-- by experiment (was undefined) temperature: 35 # <-- added by laboratory (was null) moisture: max: 40 # <-- added by laboratory (was undefined) life: # <-- by experiment (was undefined) races: ['Caucasian', 'African', 'Asian', 'Mutant'] # <-- retained at index 0,1,2 from laboratory (not was undefined) people: [ # <-- merged with experiment (was undefined) { 'name': 'PI:NAME:<NAME>END_PI', 'age': 40 } # <-- retained from laboratory (not was undefined) { 'name': 'PI:NAME:<NAME>END_PI', 'age': 50 } # <-- retained from laboratory (not was undefined) { 'name': 'PI:NAME:<NAME>END_PI', 'age': 25 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 28 } { 'name': 'PI:NAME:<NAME>END_PI', 'age': 500 } ] results:success:false # <-- by experiment (was undefined) { # module.exports = data module objectWithProtoInheritedProps Class3 c3 expectedPropertyValues # simple object with 2+2+2 clones object objectShallowClone1 objectShallowClone2 objectDeepClone1 objectDeepClone2 inheritedShallowClone inheritedDeepClone # various data obj: ciba: 4, aaa: 7, b: 2, c: -1 arrInt: [ 4, 7, 2, -1 ] arrInt2: [7, -1, 3, 5] arrStr: ['Pikoulas', 'Anodynos', 'Babylon', 'Agelos'] ### The experiment ### earth laboratory experiment earth_laboratory_experiment experiment_laboratory_earth laboratory_experiment ### Defaults merging ### team: 'enabled': true 'bundleRoot': '/team' 'compilers': # 'coffee-script': # params: true # 'urequire': enabled: true 'rjs-build': 'team-rjs' project: 'bundleRoot': '/team/project' 'compilers': 'rjs-build': 'project-rjs-build' bundle: 'bundleRoot': '/team/project/bundle' 'compilers': 'coffee-script': 'params': 'w b' 'urequire': 'scanPrevent': true ### Results ### bundle_project_team: 'enabled': true 'bundleRoot': '/team/project/bundle' 'compilers': 'coffee-script': # <- changed by someBundle 'params': 'w b' 'urequire': # <- changed by someBundle 'scanPrevent': true 'rjs-build': 'project-rjs-build' # <- changed by project }
[ { "context": "ave: true\n saveUninitialized: true\n secret: 'CERNET2ISGOOD'\n store: new RedisStore(\n client: redis\n ", "end": 907, "score": 0.49664032459259033, "start": 901, "tag": "KEY", "value": "NET2IS" } ]
backend/index.coffee
rao1219/Vedio
0
# Call this first to handle all uncaught exceptions require('./utils/log').handleUncaughtExceptions() express = require 'express' session = require 'express-session' path = require 'path' http = require 'http' RedisStore = require('connect-redis') session SequelizeFixture = require 'sequelize-fixtures' expressWinston = require 'express-winston' auth = require './utils/auth' config = require './config' logger = require('./utils/log').newConsoleLogger module.filename redis = require './utils/redis' db = require('./models') app = express() # Request logging app.use expressWinston.logger transports: [ require('./utils/log').newConsoleTransport 'Access' ] meta: config.debug or false # static files will be served first for speed # Maybe secure problem? app.use express.static path.join __dirname, '../public' app.use session resave: true saveUninitialized: true secret: 'CERNET2ISGOOD' store: new RedisStore( client: redis ) cookie: domain: config.rootDomain auth.initApp(app) app.use '/api', require './routes' # Error logging app.use expressWinston.errorLogger transports: [ require('./utils/log').newConsoleTransport 'Error' ] module.exports = app module.exports.startServer = -> db.sequelize.sync().then -> SequelizeFixture.loadFile path.join(__dirname, '/fixture/init.yml'), db .then -> port = config.port or 80 http .createServer app .listen port, -> logger.info "Express server listening on port #{port}" process.setgid config.gid process.setuid config.uid
77325
# Call this first to handle all uncaught exceptions require('./utils/log').handleUncaughtExceptions() express = require 'express' session = require 'express-session' path = require 'path' http = require 'http' RedisStore = require('connect-redis') session SequelizeFixture = require 'sequelize-fixtures' expressWinston = require 'express-winston' auth = require './utils/auth' config = require './config' logger = require('./utils/log').newConsoleLogger module.filename redis = require './utils/redis' db = require('./models') app = express() # Request logging app.use expressWinston.logger transports: [ require('./utils/log').newConsoleTransport 'Access' ] meta: config.debug or false # static files will be served first for speed # Maybe secure problem? app.use express.static path.join __dirname, '../public' app.use session resave: true saveUninitialized: true secret: 'CER<KEY>GOOD' store: new RedisStore( client: redis ) cookie: domain: config.rootDomain auth.initApp(app) app.use '/api', require './routes' # Error logging app.use expressWinston.errorLogger transports: [ require('./utils/log').newConsoleTransport 'Error' ] module.exports = app module.exports.startServer = -> db.sequelize.sync().then -> SequelizeFixture.loadFile path.join(__dirname, '/fixture/init.yml'), db .then -> port = config.port or 80 http .createServer app .listen port, -> logger.info "Express server listening on port #{port}" process.setgid config.gid process.setuid config.uid
true
# Call this first to handle all uncaught exceptions require('./utils/log').handleUncaughtExceptions() express = require 'express' session = require 'express-session' path = require 'path' http = require 'http' RedisStore = require('connect-redis') session SequelizeFixture = require 'sequelize-fixtures' expressWinston = require 'express-winston' auth = require './utils/auth' config = require './config' logger = require('./utils/log').newConsoleLogger module.filename redis = require './utils/redis' db = require('./models') app = express() # Request logging app.use expressWinston.logger transports: [ require('./utils/log').newConsoleTransport 'Access' ] meta: config.debug or false # static files will be served first for speed # Maybe secure problem? app.use express.static path.join __dirname, '../public' app.use session resave: true saveUninitialized: true secret: 'CERPI:KEY:<KEY>END_PIGOOD' store: new RedisStore( client: redis ) cookie: domain: config.rootDomain auth.initApp(app) app.use '/api', require './routes' # Error logging app.use expressWinston.errorLogger transports: [ require('./utils/log').newConsoleTransport 'Error' ] module.exports = app module.exports.startServer = -> db.sequelize.sync().then -> SequelizeFixture.loadFile path.join(__dirname, '/fixture/init.yml'), db .then -> port = config.port or 80 http .createServer app .listen port, -> logger.info "Express server listening on port #{port}" process.setgid config.gid process.setuid config.uid
[ { "context": "eo'\n plural_name : 'videos'\n thumbnail_key : 'thumbnail_small_square'\n media_accept : 'video/*'\n\n #\n # Override ba", "end": 144, "score": 0.9799617528915405, "start": 122, "tag": "KEY", "value": "thumbnail_small_square" } ]
assets/js/src/uploaders/video.coffee
JasonSanford/rogen
2
Base = require './base' class Video extends Base singular_name : 'video' plural_name : 'videos' thumbnail_key : 'thumbnail_small_square' media_accept : 'video/*' # # Override base method because we probably don't have a thumbnail ready yet. # Show placeholder image instead. # renderMedia: (media_data) -> access_key = media_data.access_key html = "<div class='thumbnail media col-xs-6 col-md-3' data-access-key='#{access_key}'><i class='glyphicon glyphicon-facetime-video'></i><input type='text' placeholder='Caption (optional)' class='caption form-control'></div>" @$uploads.append html module.exports = Video
193890
Base = require './base' class Video extends Base singular_name : 'video' plural_name : 'videos' thumbnail_key : '<KEY>' media_accept : 'video/*' # # Override base method because we probably don't have a thumbnail ready yet. # Show placeholder image instead. # renderMedia: (media_data) -> access_key = media_data.access_key html = "<div class='thumbnail media col-xs-6 col-md-3' data-access-key='#{access_key}'><i class='glyphicon glyphicon-facetime-video'></i><input type='text' placeholder='Caption (optional)' class='caption form-control'></div>" @$uploads.append html module.exports = Video
true
Base = require './base' class Video extends Base singular_name : 'video' plural_name : 'videos' thumbnail_key : 'PI:KEY:<KEY>END_PI' media_accept : 'video/*' # # Override base method because we probably don't have a thumbnail ready yet. # Show placeholder image instead. # renderMedia: (media_data) -> access_key = media_data.access_key html = "<div class='thumbnail media col-xs-6 col-md-3' data-access-key='#{access_key}'><i class='glyphicon glyphicon-facetime-video'></i><input type='text' placeholder='Caption (optional)' class='caption form-control'></div>" @$uploads.append html module.exports = Video
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9990556240081787, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/debugger/helper-debugger-repl.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. startDebugger = (scriptToDebug) -> scriptToDebug = process.env.NODE_DEBUGGER_TEST_SCRIPT or common.fixturesDir + "/" + scriptToDebug child = spawn(process.execPath, [ "debug" "--port=" + port scriptToDebug ]) console.error "./node", "debug", "--port=" + port, scriptToDebug child.stdout.setEncoding "utf-8" child.stdout.on "data", (data) -> data = (buffer + data).split("\n") buffer = data.pop() data.forEach (line) -> child.emit "line", line return return child.stderr.pipe process.stderr child.on "line", (line) -> line = line.replace(/^(debug> *)+/, "") console.log line assert.ok expected.length > 0, "Got unexpected line: " + line expectedLine = expected[0].lines.shift() assert.ok line.match(expectedLine) isnt null, line + " != " + expectedLine if expected[0].lines.length is 0 callback = expected[0].callback expected.shift() callback and callback() return childClosed = false child.on "close", (code) -> assert not code childClosed = true return quitCalled = false quit = -> return if quitCalled or childClosed quitCalled = true child.stdin.write "quit" child.kill "SIGTERM" return setTimeout(-> console.error "dying badly buffer=%j", buffer err = "Timeout" err = err + ". Expected: " + expected[0].lines.shift() if expected.length > 0 and expected[0].lines child.on "close", -> console.error "child is closed" throw new Error(err)return quit() return , 10000).unref() process.once "uncaughtException", (e) -> console.error "UncaughtException", e, e.stack quit() console.error e.toString() process.exit 1 return process.on "exit", (code) -> console.error "process exit", code quit() assert childClosed if code is 0 return return addTest = (input, output) -> next = -> if expected.length > 0 console.log "debug> " + expected[0].input child.stdin.write expected[0].input + "\n" unless expected[0].lines callback = expected[0].callback expected.shift() callback and callback() else quit() return expected.push input: input lines: output callback: next return process.env.NODE_DEBUGGER_TIMEOUT = 2000 common = require("../common") assert = require("assert") spawn = require("child_process").spawn port = common.PORT + 1337 child = undefined buffer = "" expected = [] quit = undefined handshakeLines = [ /listening on port \d+/ /connecting.* ok/ ] initialBreakLines = [ /break in .*:1/ /1/ /2/ /3/ ] initialLines = handshakeLines.concat(initialBreakLines) # Process initial lines addTest null, initialLines exports.startDebugger = startDebugger exports.addTest = addTest exports.initialLines = initialLines exports.handshakeLines = handshakeLines exports.initialBreakLines = initialBreakLines
219812
# 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. startDebugger = (scriptToDebug) -> scriptToDebug = process.env.NODE_DEBUGGER_TEST_SCRIPT or common.fixturesDir + "/" + scriptToDebug child = spawn(process.execPath, [ "debug" "--port=" + port scriptToDebug ]) console.error "./node", "debug", "--port=" + port, scriptToDebug child.stdout.setEncoding "utf-8" child.stdout.on "data", (data) -> data = (buffer + data).split("\n") buffer = data.pop() data.forEach (line) -> child.emit "line", line return return child.stderr.pipe process.stderr child.on "line", (line) -> line = line.replace(/^(debug> *)+/, "") console.log line assert.ok expected.length > 0, "Got unexpected line: " + line expectedLine = expected[0].lines.shift() assert.ok line.match(expectedLine) isnt null, line + " != " + expectedLine if expected[0].lines.length is 0 callback = expected[0].callback expected.shift() callback and callback() return childClosed = false child.on "close", (code) -> assert not code childClosed = true return quitCalled = false quit = -> return if quitCalled or childClosed quitCalled = true child.stdin.write "quit" child.kill "SIGTERM" return setTimeout(-> console.error "dying badly buffer=%j", buffer err = "Timeout" err = err + ". Expected: " + expected[0].lines.shift() if expected.length > 0 and expected[0].lines child.on "close", -> console.error "child is closed" throw new Error(err)return quit() return , 10000).unref() process.once "uncaughtException", (e) -> console.error "UncaughtException", e, e.stack quit() console.error e.toString() process.exit 1 return process.on "exit", (code) -> console.error "process exit", code quit() assert childClosed if code is 0 return return addTest = (input, output) -> next = -> if expected.length > 0 console.log "debug> " + expected[0].input child.stdin.write expected[0].input + "\n" unless expected[0].lines callback = expected[0].callback expected.shift() callback and callback() else quit() return expected.push input: input lines: output callback: next return process.env.NODE_DEBUGGER_TIMEOUT = 2000 common = require("../common") assert = require("assert") spawn = require("child_process").spawn port = common.PORT + 1337 child = undefined buffer = "" expected = [] quit = undefined handshakeLines = [ /listening on port \d+/ /connecting.* ok/ ] initialBreakLines = [ /break in .*:1/ /1/ /2/ /3/ ] initialLines = handshakeLines.concat(initialBreakLines) # Process initial lines addTest null, initialLines exports.startDebugger = startDebugger exports.addTest = addTest exports.initialLines = initialLines exports.handshakeLines = handshakeLines exports.initialBreakLines = initialBreakLines
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. startDebugger = (scriptToDebug) -> scriptToDebug = process.env.NODE_DEBUGGER_TEST_SCRIPT or common.fixturesDir + "/" + scriptToDebug child = spawn(process.execPath, [ "debug" "--port=" + port scriptToDebug ]) console.error "./node", "debug", "--port=" + port, scriptToDebug child.stdout.setEncoding "utf-8" child.stdout.on "data", (data) -> data = (buffer + data).split("\n") buffer = data.pop() data.forEach (line) -> child.emit "line", line return return child.stderr.pipe process.stderr child.on "line", (line) -> line = line.replace(/^(debug> *)+/, "") console.log line assert.ok expected.length > 0, "Got unexpected line: " + line expectedLine = expected[0].lines.shift() assert.ok line.match(expectedLine) isnt null, line + " != " + expectedLine if expected[0].lines.length is 0 callback = expected[0].callback expected.shift() callback and callback() return childClosed = false child.on "close", (code) -> assert not code childClosed = true return quitCalled = false quit = -> return if quitCalled or childClosed quitCalled = true child.stdin.write "quit" child.kill "SIGTERM" return setTimeout(-> console.error "dying badly buffer=%j", buffer err = "Timeout" err = err + ". Expected: " + expected[0].lines.shift() if expected.length > 0 and expected[0].lines child.on "close", -> console.error "child is closed" throw new Error(err)return quit() return , 10000).unref() process.once "uncaughtException", (e) -> console.error "UncaughtException", e, e.stack quit() console.error e.toString() process.exit 1 return process.on "exit", (code) -> console.error "process exit", code quit() assert childClosed if code is 0 return return addTest = (input, output) -> next = -> if expected.length > 0 console.log "debug> " + expected[0].input child.stdin.write expected[0].input + "\n" unless expected[0].lines callback = expected[0].callback expected.shift() callback and callback() else quit() return expected.push input: input lines: output callback: next return process.env.NODE_DEBUGGER_TIMEOUT = 2000 common = require("../common") assert = require("assert") spawn = require("child_process").spawn port = common.PORT + 1337 child = undefined buffer = "" expected = [] quit = undefined handshakeLines = [ /listening on port \d+/ /connecting.* ok/ ] initialBreakLines = [ /break in .*:1/ /1/ /2/ /3/ ] initialLines = handshakeLines.concat(initialBreakLines) # Process initial lines addTest null, initialLines exports.startDebugger = startDebugger exports.addTest = addTest exports.initialLines = initialLines exports.handshakeLines = handshakeLines exports.initialBreakLines = initialBreakLines
[ { "context": "ffee:migrateImagesToS3()\n###\n\n\nfilepicker.setKey \"A36NnDQaISmXZ8IOmKGEQz\"\nrequest = window.superagent\nS3Bucket = \"https://", "end": 113, "score": 0.9996199011802673, "start": 91, "tag": "KEY", "value": "A36NnDQaISmXZ8IOmKGEQz" } ]
client/migrateS3.coffee
Gratzi/pegg-scripts
0
### # DEPRECATED, see server/peggAdmin.coffee:migrateImagesToS3() ### filepicker.setKey "A36NnDQaISmXZ8IOmKGEQz" request = window.superagent S3Bucket = "https://pegg.s3.amazonaws.com/" class Migrate moveImagesToS3: -> @fetchImageUrls (items) => for item in items.body if item.image? and item.image.length > 0 matches = item.image.match /[^\/]+(#|\?|$)/ filename = if matches? then "_#{item.objectId}_.#{matches[0]}" else "_#{item.objectId}_.jpg" image = id: item.objectId url: item.image name: filename @saveImageToS3 image, (InkBlob) => @updateImageUrl InkBlob return null pickAndStore: -> filepicker.pickAndStore mimetype: "image/*", {path: '/uploaded/'}, (InkBlobs) -> result = InkBlobs[0] result.fullS3 = Config.s3.bucket + InkBlobs[0].key filepicker.convert InkBlobs[0], { width: 100, height: 100, fit: 'clip', format: 'jpg'} , { path: '/processed/' }, (thumbBlob) => thumbBlob.s3 = S3Bucket + thumbBlob.key result.thumb = thumbBlob return null fetchImageUrls: (cb) -> request .get '/choices' .end (res) -> cb res return null updateImageUrl: (InkBlob) -> request .post '/choice' .send InkBlob .end (res) -> console.log res return null saveImageToS3: (image, cb) -> combinedBlob = {} combinedBlob.id = image.id storeOptions = filename: image.name location: 'S3' path: '/orig/' filepicker.storeUrl image.url, storeOptions, (origBlob) => combinedBlob.orig = origBlob combinedBlob.orig.S3 = S3Bucket + origBlob.key convertOptions = width: 100 height: 100 fit: 'clip' format: 'jpg' storeOptions.path = '/thumb/' filepicker.convert origBlob, convertOptions, storeOptions, (thumbBlob) => combinedBlob.thumb = thumbBlob combinedBlob.thumb.S3 = S3Bucket + thumbBlob.key console.log JSON.stringify combinedBlob cb combinedBlob return null window.migrate = new Migrate()
227
### # DEPRECATED, see server/peggAdmin.coffee:migrateImagesToS3() ### filepicker.setKey "<KEY>" request = window.superagent S3Bucket = "https://pegg.s3.amazonaws.com/" class Migrate moveImagesToS3: -> @fetchImageUrls (items) => for item in items.body if item.image? and item.image.length > 0 matches = item.image.match /[^\/]+(#|\?|$)/ filename = if matches? then "_#{item.objectId}_.#{matches[0]}" else "_#{item.objectId}_.jpg" image = id: item.objectId url: item.image name: filename @saveImageToS3 image, (InkBlob) => @updateImageUrl InkBlob return null pickAndStore: -> filepicker.pickAndStore mimetype: "image/*", {path: '/uploaded/'}, (InkBlobs) -> result = InkBlobs[0] result.fullS3 = Config.s3.bucket + InkBlobs[0].key filepicker.convert InkBlobs[0], { width: 100, height: 100, fit: 'clip', format: 'jpg'} , { path: '/processed/' }, (thumbBlob) => thumbBlob.s3 = S3Bucket + thumbBlob.key result.thumb = thumbBlob return null fetchImageUrls: (cb) -> request .get '/choices' .end (res) -> cb res return null updateImageUrl: (InkBlob) -> request .post '/choice' .send InkBlob .end (res) -> console.log res return null saveImageToS3: (image, cb) -> combinedBlob = {} combinedBlob.id = image.id storeOptions = filename: image.name location: 'S3' path: '/orig/' filepicker.storeUrl image.url, storeOptions, (origBlob) => combinedBlob.orig = origBlob combinedBlob.orig.S3 = S3Bucket + origBlob.key convertOptions = width: 100 height: 100 fit: 'clip' format: 'jpg' storeOptions.path = '/thumb/' filepicker.convert origBlob, convertOptions, storeOptions, (thumbBlob) => combinedBlob.thumb = thumbBlob combinedBlob.thumb.S3 = S3Bucket + thumbBlob.key console.log JSON.stringify combinedBlob cb combinedBlob return null window.migrate = new Migrate()
true
### # DEPRECATED, see server/peggAdmin.coffee:migrateImagesToS3() ### filepicker.setKey "PI:KEY:<KEY>END_PI" request = window.superagent S3Bucket = "https://pegg.s3.amazonaws.com/" class Migrate moveImagesToS3: -> @fetchImageUrls (items) => for item in items.body if item.image? and item.image.length > 0 matches = item.image.match /[^\/]+(#|\?|$)/ filename = if matches? then "_#{item.objectId}_.#{matches[0]}" else "_#{item.objectId}_.jpg" image = id: item.objectId url: item.image name: filename @saveImageToS3 image, (InkBlob) => @updateImageUrl InkBlob return null pickAndStore: -> filepicker.pickAndStore mimetype: "image/*", {path: '/uploaded/'}, (InkBlobs) -> result = InkBlobs[0] result.fullS3 = Config.s3.bucket + InkBlobs[0].key filepicker.convert InkBlobs[0], { width: 100, height: 100, fit: 'clip', format: 'jpg'} , { path: '/processed/' }, (thumbBlob) => thumbBlob.s3 = S3Bucket + thumbBlob.key result.thumb = thumbBlob return null fetchImageUrls: (cb) -> request .get '/choices' .end (res) -> cb res return null updateImageUrl: (InkBlob) -> request .post '/choice' .send InkBlob .end (res) -> console.log res return null saveImageToS3: (image, cb) -> combinedBlob = {} combinedBlob.id = image.id storeOptions = filename: image.name location: 'S3' path: '/orig/' filepicker.storeUrl image.url, storeOptions, (origBlob) => combinedBlob.orig = origBlob combinedBlob.orig.S3 = S3Bucket + origBlob.key convertOptions = width: 100 height: 100 fit: 'clip' format: 'jpg' storeOptions.path = '/thumb/' filepicker.convert origBlob, convertOptions, storeOptions, (thumbBlob) => combinedBlob.thumb = thumbBlob combinedBlob.thumb.S3 = S3Bucket + thumbBlob.key console.log JSON.stringify combinedBlob cb combinedBlob return null window.migrate = new Migrate()
[ { "context": "m https://github.com/github/gemoji\n#\n# Author:\n# dzello\n\nmodule.exports = (robot) ->\n\n robot.brain.on \"l", "end": 642, "score": 0.9997175335884094, "start": 636, "tag": "USERNAME", "value": "dzello" }, { "context": "nese_castle: '1f3ef',\n joy_cat: '1f639',\...
src/scripts/emoji.coffee
Reelhouse/hubot-scripts
1,450
# Description: # emoji.coffee - Replaces :text: or text with emojis. # Great for IRC or anywhere not already emojified. # # Dependencies: # None # # Configuration: # None # # Commands: # "put a bird on it" - Prints "put a 🐦 on it" in 'more' emoji mode. # "put a :bird: on it" - Prints "put a 🐦 on it" in 'less' emoji mode. # hubot list emoji - Print a list of available emojis # hubot more emoji - Try to substitute all words - no :colons: required. # hubot less emoji - Require :colons: to substitute emojis (default). # # Notes: # Emoji/unicode pairing data from https://github.com/github/gemoji # # Author: # dzello module.exports = (robot) -> robot.brain.on "loaded", -> robot.brain.data.emojis ?= {} robot.hear /.+/, (msg) -> if textWithEmoji = substituteEmoji(msg.message.text, robot) msg.send(textWithEmoji) robot.respond /more emoji/, (msg) -> robot.brain.data.emojis.more = true robot.respond /less emoji/, (msg) -> robot.brain.data.emojis.more = false robot.respond /list emoji/, (msg) -> buf = "" for symbol, hexCode of emojis buf += "#{toEmoji(hexCode)} #{symbol}\n" msg.send buf substituteEmoji = (text, robot) -> ct = 0 re = if robot.brain.data.emojis.more then /([a-zA-Z0-9_:]{3,})/g else /:([a-zA-Z0-9_]+):/g text = text.replace re, (match, key) -> if emoji = emojis[key.toLowerCase().replace(/:/g, '')] ct++ toEmoji(emoji) + " " else key text if ct > 0 toEmoji = (hexCode) -> fromFullCharCode(parseInt(hexCode, 16)) fromFullCharCode = (args...) -> chars= [] for n in args if (n < 0x10000) chars.push(String.fromCharCode(n)); else high = Math.floor((n - 0x10000) / 0x400) + 0xD800 low = (n - 0x10000) % 0x400 + 0xDC00 chars.push(String.fromCharCode(high, low)) chars.join('') `emojis = { '100': '1f4af', '1234': '1f522', haircut: '1f487', house: '1f3e0', ideograph_advantage: '1f250', house_with_garden: '1f3e1', incoming_envelope: '1f4e8', japan: '1f5fe', information_source: '2139', it: '1f1ee', inbox_tray: '1f4e5', pisces: '2653', loudspeaker: '1f4e2', loop: '27bf', lips: '1f444', libra: '264e', leaves: '1f343', large_blue_diamond: '1f537', man: '1f468', laughing: '1f606', light_rail: '1f688', police_car: '1f693', mountain_railway: '1f69e', mailbox_closed: '1f4ea', musical_note: '1f3b5', left_right_arrow: '2194', link: '1f517', leo: '264c', last_quarter_moon_with_face: '1f31c', love_hotel: '1f3e9', lipstick: '1f484', leftwards_arrow_with_hook: '21a9', ledger: '1f4d2', japanese_goblin: '1f47a', left_luggage: '1f6c5', japanese_ogre: '1f479', information_desk_person: '1f481', large_orange_diamond: '1f536', koala: '1f428', kissing_cat: '1f63d', large_blue_circle: '1f535', koko: '1f201', jp: '1f1ef', joy: '1f602', last_quarter_moon: '1f317', lantern: '1f3ee', kr: '1f1f0', interrobang: '2049', jack_o_lantern: '1f383', imp: '1f47f', izakaya_lantern: '1f3ee', japanese_castle: '1f3ef', joy_cat: '1f639', key: '1f511', kiss: '1f48b', kissing_smiling_eyes: '1f619', kissing_closed_eyes: '1f61a', kimono: '1f458', jeans: '1f456', icecream: '1f366', iphone: '1f4f1', kissing: '1f617', id: '1f194', innocent: '1f607', hushed: '1f62f', ice_cream: '1f368', hourglass_flowing_sand: '23f3', hourglass: '231b', no_entry: '26d4', lock: '1f512', memo: '1f4dd', muscle: '1f4aa', lock_with_ink_pen: '1f50f', lemon: '1f34b', keycap_ten: '1f51f', microphone: '1f3a4', no_mobile_phones: '1f4f5', mouse2: '1f401', kissing_heart: '1f618', man_with_gua_pi_mao: '1f472', microscope: '1f52c', point_down: '1f447', pizza: '1f355', pouch: '1f45d', pound: '1f4b7', potable_water: '1f6b0', no_mouth: '1f636', postbox: '1f4ee', poultry_leg: '1f357', point_right: '1f449', post_office: '1f3e3', point_left: '1f448', point_up_2: '1f446', poodle: '1f429', pray: '1f64f', no_pedestrians: '1f6b7', moyai: '1f5ff', point_up: '261d', monkey: '1f412', postal_horn: '1f4ef', no_entry_sign: '1f6ab', newspaper: '1f4f0', poop: '1f4a9', pouting_cat: '1f63e', princess: '1f478', nine: '0039', neutral_face: '1f610', no_bell: '1f515', ng: '1f196', metro: '1f687', necktie: '1f454', new: '1f195', mute: '1f507', no_good: '1f645', new_moon_with_face: '1f31a', nail_care: '1f485', low_brightness: '1f505', couplekiss: '1f48f', copyright: '00a9', couple: '1f46b', couple_with_heart: '1f491', cookie: '1f36a', construction: '1f6a7', cool: '1f192', cherry_blossom: '1f338', clock4: '1f553', corn: '1f33d', credit_card: '1f4b3', clock1030: '1f565', church: '26ea', cop: '1f46e', convenience_store: '1f3ea', cow: '1f42e', clapper: '1f3ac', clock1130: '1f566', clock12: '1f55b', card_index: '1f4c7', cat: '1f431', bomb: '1f4a3', car: '1f697', cancer: '264b', capricorn: '2651', blush: '1f60a', candy: '1f36c', boom: '1f4a5', capital_abcd: '1f520', clock930: '1f564', bride_with_veil: '1f470', book: '1f4d6', bookmark_tabs: '1f4d1', blue_book: '1f4d8', carousel_horse: '1f3a0', bust_in_silhouette: '1f464', boat: '26f5', blowfish: '1f421', bookmark: '1f516', books: '1f4da', black_small_square: '25aa', boar: '1f417', blue_heart: '1f499', boot: '1f462', santa: '1f385', saxophone: '1f3b7', scream: '1f631', minidisc: '1f4bd', school_satchel: '1f392', scorpius: '264f', blue_car: '1f699', scissors: '2702', satisfied: '1f606', sandal: '1f461', black_square_button: '1f532', school: '1f3eb', hamster: '1f439', satellite: '1f4e1', sake: '1f376', sa: '1f202', busstop: '1f68f', sailboat: '26f5', running_shirt_with_sash: '1f3bd', bulb: '1f4a1', sagittarius: '2650', mushroom: '1f344', massage: '1f486', mailbox_with_mail: '1f4ec', m: '24c2', maple_leaf: '1f341', mailbox_with_no_mail: '1f4ed', mask: '1f637', mega: '1f4e3', basketball: '1f3c0', arrow_up: '2b06', abcd: '1f521', '+1': '1f44d', alien: '1f47d', ant: '1f41c', anguished: '1f627', sheep: '1f411', a: '1f170', sos: '1f198', '8ball': '1f3b1', office: '1f3e2', older_man: '1f474', seat: '1f4ba', smirk_cat: '1f63c', tiger: '1f42f', vhs: '1f4fc', surfer: '1f3c4', ok_hand: '1f44c', 'non-potable_water': '1f6b1', older_woman: '1f475', ok: '1f197', octopus: '1f419', mountain_cableway: '1f6a0', unlock: '1f513', nose: '1f443', mount_fuji: '1f5fb', notebook_with_decorative_cover: '1f4d4', ok_woman: '1f646', notes: '1f3b6', nut_and_bolt: '1f529', ocean: '1f30a', o: '2b55', new_moon: '1f311', mountain_bicyclist: '1f6b5', notebook: '1f4d3', mag: '1f50d', no_bicycles: '1f6b3', train2: '1f686', smile: '1f604', shirt: '1f455', speak_no_evil: '1f64a', vertical_traffic_light: '1f6a6', shit: '1f4a9', musical_keyboard: '1f3b9', ambulance: '1f691', tv: '1f4fa', battery: '1f50b', lollipop: '1f36d', mouse: '1f42d', movie_camera: '1f3a5', bamboo: '1f38d', cold_sweat: '1f630', mens: '1f6b9', station: '1f689', sound: '1f509', first_quarter_moon: '1f313', elephant: '1f418', doughnut: '1f369', door: '1f6aa', earth_asia: '1f30f', fire: '1f525', cloud: '2601', ear: '1f442', eight_pointed_black_star: '2734', dizzy: '1f4ab', crocodile: '1f40a', mailbox: '1f4eb', feet: '1f43e', heart_eyes: '1f60d', currency_exchange: '1f4b1', facepunch: '1f44a', hankey: '1f4a9', minibus: '1f690', ferris_wheel: '1f3a1', fireworks: '1f386', crossed_flags: '1f38c', department_store: '1f3ec', heavy_check_mark: '2714', fountain: '26f2', flushed: '1f633', fork_and_knife: '1f374', waxing_gibbous_moon: '1f314', dragon_face: '1f432', x: '274c', white_circle: '26aa', sparkler: '1f387', white_medium_small_square: '25fd', white_check_mark: '2705', uk: '1f1ec', v: '270c', sunflower: '1f33b', white_large_square: '2b1c', tent: '26fa', triangular_flag_on_post: '1f6a9', telephone_receiver: '1f4de', tram: '1f68a', whale: '1f433', triumph: '1f624', weary: '1f629', hash: '0023', speech_balloon: '1f4ac', sparkling_heart: '1f496', stars: '1f303', speaker: '1f50a', snowflake: '2744', sunglasses: '1f60e', speedboat: '1f6a4', snake: '1f40d', earth_americas: '1f30e', smile_cat: '1f638', star2: '1f31f', small_orange_diamond: '1f538', smoking: '1f6ac', spaghetti: '1f35d', sleepy: '1f62a', star: '2b50', smiley: '1f603', small_red_triangle_down: '1f53b', snowman: '26c4', small_blue_diamond: '1f539', pig: '1f437', rice: '1f35a', smiley_cat: '1f63a', snowboarder: '1f3c2', heavy_dollar_sign: '1f4b2', smirk: '1f60f', rugby_football: '1f3c9', smiling_imp: '1f608', rowboat: '1f6a3', shower: '1f6bf', slot_machine: '1f3b0', shell: '1f41a', hear_no_evil: '1f649', pensive: '1f614', hibiscus: '1f33a', person_frowning: '1f64d', raising_hand: '1f64b', rabbit2: '1f407', snail: '1f40c', ramen: '1f35c', radio: '1f4fb', deciduous_tree: '1f333', diamond_shape_with_a_dot_inside: '1f4a0', first_quarter_moon_with_face: '1f31b', dog: '1f436', eggplant: '1f346', shoe: '1f45e', customs: '1f6c3', pill: '1f48a', 'e-mail': '1f4e7', dolphin: '1f42c', disappointed_relieved: '1f625', dizzy_face: '1f635', curly_loop: '27b0', crying_cat_face: '1f63f', milky_way: '1f30c', small_red_triangle: '1f53a', coffee: '2615', flashlight: '1f526', eight_spoked_asterisk: '2733', heart_decoration: '1f49f', open_mouth: '1f62e', curry: '1f35b', passport_control: '1f6c2', cupid: '1f498', high_heel: '1f460', heavy_exclamation_mark: '2757', gun: '1f52b', fries: '1f35f', melon: '1f348', euro: '1f4b6', meat_on_bone: '1f356', fish_cake: '1f365', gem: '1f48e', mahjong: '1f004', dog2: '1f415', egg: '1f373', date: '1f4c5', girl: '1f467', free: '1f193', ear_of_rice: '1f33e', full_moon: '1f315', man_with_turban: '1f473', european_castle: '1f3f0', five: '0035', fax: '1f4e0', crown: '1f451', diamonds: '2666', fist: '270a', cn: '1f1e8', flags: '1f38f', grin: '1f601', exclamation: '2757', green_book: '1f4d7', fishing_pole_and_fish: '1f3a3', cocktail: '1f378', factory: '1f3ed', frowning: '1f626', fr: '1f1eb', envelope_with_arrow: '1f4e9', handbag: '1f45c', foggy: '1f301', floppy_disk: '1f4be', beer: '1f37a', footprints: '1f463', globe_with_meridians: '1f310', mans_shoe: '1f45e', dango: '1f361', dancer: '1f483', gift_heart: '1f49d', dromedary_camel: '1f42a', clock330: '1f55e', clock3: '1f552', construction_worker: '1f477', cow2: '1f404', email: '2709', fast_forward: '23e9', file_folder: '1f4c1', collision: '1f4a5', clock230: '1f55d', horse_racing: '1f3c7', fish: '1f41f', clock2: '1f551', confetti_ball: '1f38a', heavy_division_sign: '2797', u6709: '1f236', full_moon_with_face: '1f31d', european_post_office: '1f3e4', ski: '1f3bf', congratulations: '3297', football: '1f3c8', four_leaf_clover: '1f340', negative_squared_cross_mark: '274e', confounded: '1f616', money_with_wings: '1f4b8', honey_pot: '1f36f', closed_umbrella: '1f302', computer: '1f4bb', hearts: '2665', dart: '1f3af', heart_eyes_cat: '1f63b', love_letter: '1f48c', racehorse: '1f40e', helicopter: '1f681', honeybee: '1f41d', railway_car: '1f683', musical_score: '1f3bc', fire_engine: '1f692', heavy_multiplication_x: '2716', heartpulse: '1f497', hotsprings: '2668', headphones: '1f3a7', family: '1f46a', end: '1f51a', dragon: '1f409', evergreen_tree: '1f332', hocho: '1f52a', high_brightness: '1f506', ship: '1f6a2', horse: '1f434', see_no_evil: '1f648', es: '1f1ea', ru: '1f1f7', runner: '1f3c3', goat: '1f410', o2: '1f17e', scroll: '1f4dc', running: '1f3c3', punch: '1f44a', secret: '3299', question: '2753', persevere: '1f623', frog: '1f438', four: '0034', gift: '1f381', gemini: '264a', dancers: '1f46f', relaxed: '263a', repeat: '1f501', red_circle: '1f534', phone: '260e', rocket: '1f680', purple_heart: '1f49c', rose: '1f339', fuelpump: '26fd', person_with_pouting_face: '1f64e', red_car: '1f697', rewind: '23ea', rice_ball: '1f359', disappointed: '1f61e', rooster: '1f413', restroom: '1f6bb', registered: '00ae', relieved: '1f60c', recycle: '267b', rotating_light: '1f6a8', rainbow: '1f308', rice_cracker: '1f358', pear: '1f350', ring: '1f48d', rat: '1f400', eyeglasses: '1f453', gb: '1f1ec', pencil: '1f4dd', fried_shrimp: '1f364', revolving_hearts: '1f49e', pencil2: '270f', partly_sunny: '26c5', outbox_tray: '1f4e4', page_with_curl: '1f4c3', part_alternation_mark: '303d', peach: '1f351', rice_scene: '1f391', roller_coaster: '1f3a2', oncoming_police_car: '1f694', paperclip: '1f4ce', open_file_folder: '1f4c2', page_facing_up: '1f4c4', paw_prints: '1f43e', palm_tree: '1f334', ox: '1f402', package: '1f4e6', one: '0031', open_book: '1f4d6', oncoming_taxi: '1f696', mortar_board: '1f393', on: '1f51b', ophiuchus: '26ce', moneybag: '1f4b0', orange_book: '1f4d9', open_hands: '1f450', mobile_phone_off: '1f4f4', monkey_face: '1f435', monorail: '1f69d', oden: '1f362', oncoming_automobile: '1f698', cyclone: '1f300', panda_face: '1f43c', oncoming_bus: '1f68d', moon: '1f314', fearful: '1f628', eyes: '1f440', person_with_blond_hair: '1f471', leopard: '1f406', ram: '1f40f', penguin: '1f427', repeat_one: '1f502', parking: '1f17f', pager: '1f4df', pig2: '1f416', rabbit: '1f430', envelope: '2709', pig_nose: '1f43d', closed_lock_with_key: '1f510', ghost: '1f47b', confused: '1f615', closed_book: '1f4d5', clock830: '1f563', dollar: '1f4b5', ribbon: '1f380', clock530: '1f560', clock8: '1f557', clock430: '1f55f', clock11: '1f55a', city_sunrise: '1f307', clock6: '1f555', circus_tent: '1f3aa', clock7: '1f556', cl: '1f191', chocolate_bar: '1f36b', clock1: '1f550', name_badge: '1f4db', clock630: '1f561', clock10: '1f559', cd: '1f4bf', clock9: '1f558', clipboard: '1f4cb', clock1230: '1f567', chart_with_downwards_trend: '1f4c9', chart: '1f4b9', clock730: '1f562', chicken: '1f414', performing_arts: '1f3ad', city_sunset: '1f306', christmas_tree: '1f384', cherries: '1f352', camel: '1f42b', cat2: '1f408', cactus: '1f335', bug: '1f41b', cake: '1f370', bullettrain_side: '1f684', calendar: '1f4c6', checkered_flag: '1f3c1', bus: '1f68c', broken_heart: '1f494', busts_in_silhouette: '1f465', bullettrain_front: '1f685', chestnut: '1f330', calling: '1f4f2', bread: '1f35e', bridge_at_night: '1f309', briefcase: '1f4bc', bouquet: '1f490', bowling: '1f3b3', bow: '1f647', droplet: '1f4a7', blossom: '1f33c', clap: '1f44f', clock130: '1f55c', cinema: '1f3a6', clubs: '2663', clock5: '1f554', children_crossing: '1f6b8', boy: '1f466', camera: '1f4f7', bento: '1f371', black_large_square: '2b1b', black_nib: '2712', birthday: '1f382', black_medium_small_square: '25fe', bird: '1f426', black_joker: '1f0cf', bicyclist: '1f6b4', black_circle: '26ab', beetle: '1f41e', bikini: '1f459', no_smoking: '1f6ad', bike: '1f6b2', black_medium_square: '25fc', bell: '1f514', mag_right: '1f50e', bee: '1f41d', bathtub: '1f6c1', bar_chart: '1f4ca', bath: '1f6c0', barber: '1f488', baby_symbol: '1f6bc', bank: '1f3e6', bangbang: '203c', arrow_up_small: '1f53c', atm: '1f3e7', baby: '1f476', back: '1f519', arrows_clockwise: '1f503', b: '1f171', arrow_upper_left: '2196', balloon: '1f388', athletic_shoe: '1f45f', arrows_counterclockwise: '1f504', ballot_box_with_check: '2611', articulated_lorry: '1f69b', round_pushpin: '1f4cd', radio_button: '1f518', raised_hands: '1f64c', raised_hand: '270b', purse: '1f45b', put_litter_in_its_place: '1f6ae', rage: '1f621', pushpin: '1f4cc', pineapple: '1f34d', dash: '1f4a8', bear: '1f43b', baggage_claim: '1f6c4', art: '1f3a8', arrow_upper_right: '2197', chart_with_upwards_trend: '1f4c8', baby_chick: '1f424', baseball: '26be', baby_bottle: '1f37c', arrow_forward: '25b6', aries: '2648', arrow_left: '2b05', arrow_lower_left: '2199', arrow_right: '27a1', ab: '1f18e', arrow_down: '2b07', anger: '1f4a2', accept: '1f251', arrow_lower_right: '2198', arrow_double_up: '23eb', arrow_down_small: '1f53d', arrow_heading_up: '2934', aquarius: '2652', arrow_backward: '25c0', abc: '1f524', aerial_tramway: '1f6a1', astonished: '1f632', alarm_clock: '23f0', angry: '1f620', arrow_right_hook: '21aa', arrow_double_down: '23ec', arrow_heading_down: '2935', apple: '1f34e', airplane: '2708', angel: '1f47c', anchor: '2693', '-1': '1f44e', zero: '0030', yellow_heart: '1f49b', zzz: '1f4a4', zap: '26a1', womens: '1f6ba', woman: '1f469', wind_chime: '1f390', wink: '1f609', wave: '1f44b', wc: '1f6be', white_square_button: '1f533', womans_hat: '1f452', white_flower: '1f4ae', wine_glass: '1f377', womans_clothes: '1f45a', white_small_square: '25ab', worried: '1f61f', violin: '1f3bb', two_women_holding_hands: '1f46d', whale2: '1f40b', waning_gibbous_moon: '1f316', virgo: '264d', tulip: '1f337', u5272: '1f239', u5408: '1f234', watch: '231a', wavy_dash: '3030', trumpet: '1f3ba', two_men_holding_hands: '1f46c', two_hearts: '1f495', u55b6: '1f23a', volcano: '1f30b', warning: '26a0', video_game: '1f3ae', truck: '1f69a', tropical_fish: '1f420', u6708: '1f237', up: '1f199', watermelon: '1f349', tired_face: '1f62b', twisted_rightwards_arrows: '1f500', train: '1f683', tongue: '1f445', water_buffalo: '1f403', two: '0032', yum: '1f60b', turtle: '1f422', waning_crescent_moon: '1f318', traffic_light: '1f6a5', tshirt: '1f455', vibration_mode: '1f4f3', u6307: '1f22f', vs: '1f19a', toilet: '1f6bd', tokyo_tower: '1f5fc', thumbsdown: '1f44e', thumbsup: '1f44d', tangerine: '1f34a', three: '0033', ticket: '1f3ab', tennis: '1f3be', taurus: '2649', tm: '2122', taxi: '1f695', tada: '1f389', tea: '1f375', telescope: '1f52d', symbols: '1f523', tanabata_tree: '1f38b', syringe: '1f489', sunny: '2600', suspension_railway: '1f69f', sweet_potato: '1f360', stuck_out_tongue_closed_eyes: '1f61d', sushi: '1f363', stew: '1f372', sweat_smile: '1f605', six_pointed_star: '1f52f', space_invader: '1f47e', signal_strength: '1f4f6', stuck_out_tongue_winking_eye: '1f61c', seven: '0037', steam_locomotive: '1f682', strawberry: '1f353', swimmer: '1f3ca', skull: '1f480', straight_ruler: '1f4cf', sunrise: '1f305', sweat: '1f613', sun_with_face: '1f31e', sparkles: '2728', statue_of_liberty: '1f5fd', sleeping: '1f634', soon: '1f51c', beginner: '1f530', yen: '1f4b4', beers: '1f37b', white_medium_square: '25fb', wolf: '1f43a', wrench: '1f527', video_camera: '1f4f9', walking: '1f6b6', waxing_crescent_moon: '1f312', wheelchair: '267f', tiger2: '1f405', sweat_drops: '1f4a6', seedling: '1f331', wedding: '1f492', u7533: '1f238', umbrella: '2614', sunrise_over_mountains: '1f304', us: '1f1fa', u7981: '1f232', u7a7a: '1f233', underage: '1f51e', unamused: '1f612', u7121: '1f21a', sparkle: '2747', sob: '1f62d', stuck_out_tongue: '1f61b', u6e80: '1f235', tropical_drink: '1f379', trophy: '1f3c6', trolleybus: '1f68e', triangular_ruler: '1f4d0', trident: '1f531', top: '1f51d', tomato: '1f345', telephone: '260e', thought_balloon: '1f4ad', tophat: '1f3a9', tractor: '1f69c', soccer: '26bd', six: '0036', scream_cat: '1f640', shaved_ice: '1f367', spades: '2660', dvd: '1f4c0', flower_playing_cards: '1f3b4', cry: '1f622', hospital: '1f3e5', hotel: '1f3e8', herb: '1f33f', heavy_plus_sign: '2795', hatched_chick: '1f425', hammer: '1f528', grey_exclamation: '2755', green_apple: '1f34f', grinning: '1f600', heavy_minus_sign: '2796', hamburger: '1f354', guardsman: '1f482', hand: '270b', green_heart: '1f49a', grey_question: '2754', golf: '26f3', grapes: '1f347', heartbeat: '1f493', grimacing: '1f62c', hatching_chick: '1f423', dolls: '1f38e', de: '1f1e9', do_not_litter: '1f6af', dress: '1f457', custard: '1f36e', eight: '0038', earth_africa: '1f30d', guitar: '1f3b8', game_die: '1f3b2', fallen_leaf: '1f342', heart: '2764', expressionless: '1f611', crescent_moon: '1f319', electric_plug: '1f50c', crystal_ball: '1f52e', arrow_up_down: '2195', banana: '1f34c' }`
82814
# Description: # emoji.coffee - Replaces :text: or text with emojis. # Great for IRC or anywhere not already emojified. # # Dependencies: # None # # Configuration: # None # # Commands: # "put a bird on it" - Prints "put a 🐦 on it" in 'more' emoji mode. # "put a :bird: on it" - Prints "put a 🐦 on it" in 'less' emoji mode. # hubot list emoji - Print a list of available emojis # hubot more emoji - Try to substitute all words - no :colons: required. # hubot less emoji - Require :colons: to substitute emojis (default). # # Notes: # Emoji/unicode pairing data from https://github.com/github/gemoji # # Author: # dzello module.exports = (robot) -> robot.brain.on "loaded", -> robot.brain.data.emojis ?= {} robot.hear /.+/, (msg) -> if textWithEmoji = substituteEmoji(msg.message.text, robot) msg.send(textWithEmoji) robot.respond /more emoji/, (msg) -> robot.brain.data.emojis.more = true robot.respond /less emoji/, (msg) -> robot.brain.data.emojis.more = false robot.respond /list emoji/, (msg) -> buf = "" for symbol, hexCode of emojis buf += "#{toEmoji(hexCode)} #{symbol}\n" msg.send buf substituteEmoji = (text, robot) -> ct = 0 re = if robot.brain.data.emojis.more then /([a-zA-Z0-9_:]{3,})/g else /:([a-zA-Z0-9_]+):/g text = text.replace re, (match, key) -> if emoji = emojis[key.toLowerCase().replace(/:/g, '')] ct++ toEmoji(emoji) + " " else key text if ct > 0 toEmoji = (hexCode) -> fromFullCharCode(parseInt(hexCode, 16)) fromFullCharCode = (args...) -> chars= [] for n in args if (n < 0x10000) chars.push(String.fromCharCode(n)); else high = Math.floor((n - 0x10000) / 0x400) + 0xD800 low = (n - 0x10000) % 0x400 + 0xDC00 chars.push(String.fromCharCode(high, low)) chars.join('') `emojis = { '100': '1f4af', '1234': '1f522', haircut: '1f487', house: '1f3e0', ideograph_advantage: '1f250', house_with_garden: '1f3e1', incoming_envelope: '1f4e8', japan: '1f5fe', information_source: '2139', it: '1f1ee', inbox_tray: '1f4e5', pisces: '2653', loudspeaker: '1f4e2', loop: '27bf', lips: '1f444', libra: '264e', leaves: '1f343', large_blue_diamond: '1f537', man: '1f468', laughing: '1f606', light_rail: '1f688', police_car: '1f693', mountain_railway: '1f69e', mailbox_closed: '1f4ea', musical_note: '1f3b5', left_right_arrow: '2194', link: '1f517', leo: '264c', last_quarter_moon_with_face: '1f31c', love_hotel: '1f3e9', lipstick: '1f484', leftwards_arrow_with_hook: '21a9', ledger: '1f4d2', japanese_goblin: '1f47a', left_luggage: '1f6c5', japanese_ogre: '1f479', information_desk_person: '1f481', large_orange_diamond: '1f536', koala: '1f428', kissing_cat: '1f63d', large_blue_circle: '1f535', koko: '1f201', jp: '1f1ef', joy: '1f602', last_quarter_moon: '1f317', lantern: '1f3ee', kr: '1f1f0', interrobang: '2049', jack_o_lantern: '1f383', imp: '1f47f', izakaya_lantern: '1f3ee', japanese_castle: '1f3ef', joy_cat: '1f639', key: '<KEY>', kiss: '1f48b', kissing_smiling_eyes: '1f619', kissing_closed_eyes: '1f61a', kimono: '1f458', jeans: '1f456', icecream: '1f366', iphone: '1f4f1', kissing: '1f617', id: '1f194', innocent: '1f607', hushed: '1f62f', ice_cream: '1f368', hourglass_flowing_sand: '23f3', hourglass: '231b', no_entry: '26d4', lock: '1f512', memo: '1f4dd', muscle: '1f4aa', lock_with_ink_pen: '1f50f', lemon: '1f34b', keycap_ten: '1f51f', microphone: '1f3a4', no_mobile_phones: '1f4f5', mouse2: '1f401', kissing_heart: '1f618', man_with_gua_pi_mao: '1f472', microscope: '1f52c', point_down: '1f447', pizza: '1f355', pouch: '1f45d', pound: '1f4b7', potable_water: '1f6b0', no_mouth: '1f636', postbox: '1f4ee', poultry_leg: '1f357', point_right: '1f449', post_office: '1f3e3', point_left: '1f448', point_up_2: '1f446', poodle: '1f429', pray: '1f64f', no_pedestrians: '1f6b7', moyai: '1f5ff', point_up: '261d', monkey: '1f412', postal_horn: '1f4ef', no_entry_sign: '1f6ab', newspaper: '1f4f0', poop: '1f4a9', pouting_cat: '1f63e', princess: '1f478', nine: '0039', neutral_face: '1f610', no_bell: '1f515', ng: '1f196', metro: '1f687', necktie: '1f454', new: '1f195', mute: '1f507', no_good: '1f645', new_moon_with_face: '1f31a', nail_care: '1f485', low_brightness: '1f505', couplekiss: '1f48f', copyright: '00a9', couple: '1f46b', couple_with_heart: '1f491', cookie: '1f36a', construction: '1f6a7', cool: '1f192', cherry_blossom: '1f338', clock4: '1f553', corn: '1f33d', credit_card: '1<KEY>', clock1030: '1f565', church: '26ea', cop: '1f46e', convenience_store: '1f3ea', cow: '1f42e', clapper: '1f3ac', clock1130: '1f566', clock12: '1f55b', card_index: '1f4c7', cat: '1f431', bomb: '1f4a3', car: '1f697', cancer: '264b', capricorn: '2651', blush: '1f60a', candy: '1f36c', boom: '1f4a5', capital_abcd: '1f520', clock930: '1f564', bride_with_veil: '1f470', book: '1f4d6', bookmark_tabs: '1f4d1', blue_book: '1f4d8', carousel_horse: '1f3a0', bust_in_silhouette: '1f464', boat: '26f5', blowfish: '1f421', bookmark: '1f516', books: '1f4da', black_small_square: '25aa', boar: '1f417', blue_heart: '1f499', boot: '1f462', santa: '1f385', saxophone: '1f3b7', scream: '1f631', minidisc: '1f4bd', school_satchel: '1f392', scorpius: '264f', blue_car: '1f699', scissors: '2702', satisfied: '1f606', sandal: '1f461', black_square_button: '1f532', school: '1f3eb', hamster: '1f439', satellite: '1f4e1', sake: '1f376', sa: '1f202', busstop: '1f68f', sailboat: '26f5', running_shirt_with_sash: '1f3bd', bulb: '1f4a1', sagittarius: '2650', mushroom: '1f344', massage: '1f486', mailbox_with_mail: '1f4ec', m: '24c2', maple_leaf: '1f341', mailbox_with_no_mail: '1f4ed', mask: '1f637', mega: '1f4e3', basketball: '1f3c0', arrow_up: '2b06', abcd: '1f521', '+1': '1f44d', alien: '1f47d', ant: '1f41c', anguished: '1f627', sheep: '1f411', a: '1f170', sos: '1f198', '8ball': '1f3b1', office: '1f3e2', older_man: '1f474', seat: '1f4ba', smirk_cat: '1f63c', tiger: '1f42f', vhs: '1f4fc', surfer: '1f3c4', ok_hand: '1f44c', 'non-potable_water': '1f6b1', older_woman: '1f475', ok: '1f197', octopus: '1f419', mountain_cableway: '1f6a0', unlock: '1f513', nose: '1f443', mount_fuji: '1f5fb', notebook_with_decorative_cover: '1f4d4', ok_woman: '1f646', notes: '1f3b6', nut_and_bolt: '1f529', ocean: '1f30a', o: '2b55', new_moon: '1f311', mountain_bicyclist: '1f6b5', notebook: '1f4d3', mag: '1f50d', no_bicycles: '1f6b3', train2: '1f686', smile: '1f604', shirt: '1f455', speak_no_evil: '1f64a', vertical_traffic_light: '1f6a6', shit: '1f4a9', musical_keyboard: '1f3b9', ambulance: '1f691', tv: '1f4fa', battery: '1f50b', lollipop: '1f36d', mouse: '1f42d', movie_camera: '1f3a5', bamboo: '1f38d', cold_sweat: '1f630', mens: '1f6b9', station: '1f689', sound: '1f509', first_quarter_moon: '1f313', elephant: '1f418', doughnut: '1f369', door: '1f6aa', earth_asia: '1f30f', fire: '1f525', cloud: '2601', ear: '1f442', eight_pointed_black_star: '2734', dizzy: '1f4ab', crocodile: '1f40a', mailbox: '1f4eb', feet: '1f43e', heart_eyes: '1f60d', currency_exchange: '1f4b1', facepunch: '1f44a', hankey: '1<KEY>', minibus: '1f690', ferris_wheel: '1f3a1', fireworks: '1f386', crossed_flags: '1f38c', department_store: '1f3ec', heavy_check_mark: '2714', fountain: '26f2', flushed: '1f633', fork_and_knife: '1f374', waxing_gibbous_moon: '1f314', dragon_face: '1f432', x: '274c', white_circle: '26aa', sparkler: '1f387', white_medium_small_square: '25fd', white_check_mark: '2705', uk: '1f1ec', v: '270c', sunflower: '1f33b', white_large_square: '2b1c', tent: '26fa', triangular_flag_on_post: '1f6a9', telephone_receiver: '1f4de', tram: '1f68a', whale: '1f433', triumph: '1f624', weary: '1f629', hash: '0023', speech_balloon: '1f4ac', sparkling_heart: '1f496', stars: '1f303', speaker: '1f50a', snowflake: '2744', sunglasses: '1f60e', speedboat: '1f6a4', snake: '1f40d', earth_americas: '1f30e', smile_cat: '1f638', star2: '1f31f', small_orange_diamond: '1f538', smoking: '1f6ac', spaghetti: '1f35d', sleepy: '1f62a', star: '2b50', smiley: '1f603', small_red_triangle_down: '1f53b', snowman: '26c4', small_blue_diamond: '1f539', pig: '1f437', rice: '1f35a', smiley_cat: '1f63a', snowboarder: '1f3c2', heavy_dollar_sign: '1f4b2', smirk: '1f60f', rugby_football: '1f3c9', smiling_imp: '1f608', rowboat: '1f6a3', shower: '1f6bf', slot_machine: '1f3b0', shell: '1f41a', hear_no_evil: '1f649', pensive: '1f614', hibiscus: '1f33a', person_frowning: '1f64d', raising_hand: '1f64b', rabbit2: '1f407', snail: '1f40c', ramen: '1f35c', radio: '1f4fb', deciduous_tree: '1f333', diamond_shape_with_a_dot_inside: '1f4a0', first_quarter_moon_with_face: '1f31b', dog: '1f436', eggplant: '1f346', shoe: '1f45e', customs: '1f6c3', pill: '1f48a', 'e-mail': '1f4e7', dolphin: '1f42c', disappointed_relieved: '1f625', dizzy_face: '1f635', curly_loop: '27b0', crying_cat_face: '1f63f', milky_way: '1f30c', small_red_triangle: '1f53a', coffee: '2615', flashlight: '1f526', eight_spoked_asterisk: '2733', heart_decoration: '1f49f', open_mouth: '1f62e', curry: '1f35b', passport_control: '1f6c2', cupid: '1f498', high_heel: '1f460', heavy_exclamation_mark: '2757', gun: '1f52b', fries: '1f35f', melon: '1f348', euro: '1f4b6', meat_on_bone: '1f356', fish_cake: '1f365', gem: '1f48e', mahjong: '1f004', dog2: '1f415', egg: '1f373', date: '1f4c5', girl: '1f467', free: '1f193', ear_of_rice: '1f33e', full_moon: '1f315', man_with_turban: '1f473', european_castle: '1f3f0', five: '0035', fax: '1f4e0', crown: '1f451', diamonds: '2666', fist: '270a', cn: '1f1e8', flags: '1f38f', grin: '1f601', exclamation: '2757', green_book: '1f4d7', fishing_pole_and_fish: '1f3a3', cocktail: '1f378', factory: '1f3ed', frowning: '1f626', fr: '1f1eb', envelope_with_arrow: '1f4e9', handbag: '1f45c', foggy: '1f301', floppy_disk: '1f4be', beer: '1f37a', footprints: '1f463', globe_with_meridians: '1f310', mans_shoe: '1f45e', dango: '1f361', dancer: '1f483', gift_heart: '1f49d', dromedary_camel: '1f42a', clock330: '1f55e', clock3: '1f552', construction_worker: '1f477', cow2: '1f404', email: '2709', fast_forward: '23e9', file_folder: '1f4c1', collision: '1f4a5', clock230: '1f55d', horse_racing: '1f3c7', fish: '1f41f', clock2: '1f551', confetti_ball: '1f38a', heavy_division_sign: '2797', u6709: '1f236', full_moon_with_face: '1f31d', european_post_office: '1f3e4', ski: '1f3bf', congratulations: '3297', football: '1f3c8', four_leaf_clover: '1f340', negative_squared_cross_mark: '274e', confounded: '1f616', money_with_wings: '1f4b8', honey_pot: '1f36f', closed_umbrella: '1f302', computer: '1f4bb', hearts: '2665', dart: '1f3af', heart_eyes_cat: '1f63b', love_letter: '1f48c', racehorse: '1f40e', helicopter: '1f681', honeybee: '1f41d', railway_car: '1f683', musical_score: '1f3bc', fire_engine: '1f692', heavy_multiplication_x: '2716', heartpulse: '1f497', hotsprings: '2668', headphones: '1f3a7', family: '1f46a', end: '1f51a', dragon: '1f409', evergreen_tree: '1f332', hocho: '1f52a', high_brightness: '1f506', ship: '1f6a2', horse: '1f434', see_no_evil: '1f648', es: '1f1ea', ru: '1f1f7', runner: '1f3c3', goat: '1f410', o2: '1f17e', scroll: '1f4dc', running: '1f3c3', punch: '1f44a', secret: '3299', question: '2753', persevere: '1f623', frog: '1f438', four: '0034', gift: '1f381', gemini: '264a', dancers: '1f46f', relaxed: '263a', repeat: '1f501', red_circle: '1f534', phone: '260e', rocket: '1f680', purple_heart: '1f49c', rose: '1f339', fuelpump: '26fd', person_with_pouting_face: '1f64e', red_car: '1f697', rewind: '23ea', rice_ball: '1f359', disappointed: '1f61e', rooster: '1f413', restroom: '1f6bb', registered: '00ae', relieved: '1f60c', recycle: '267b', rotating_light: '1f6a8', rainbow: '1f308', rice_cracker: '1f358', pear: '1f350', ring: '1f48d', rat: '1f400', eyeglasses: '1f453', gb: '1f1ec', pencil: '1f4dd', fried_shrimp: '1f364', revolving_hearts: '1f49e', pencil2: '270f', partly_sunny: '26c5', outbox_tray: '1f4e4', page_with_curl: '1f4c3', part_alternation_mark: '303d', peach: '1f351', rice_scene: '1f391', roller_coaster: '1f3a2', oncoming_police_car: '1f694', paperclip: '1f4ce', open_file_folder: '1f4c2', page_facing_up: '1f4c4', paw_prints: '1f43e', palm_tree: '1f334', ox: '1f402', package: '1f4e6', one: '0031', open_book: '1f4d6', oncoming_taxi: '1f696', mortar_board: '1f393', on: '1f51b', ophiuchus: '26ce', moneybag: '1f4b0', orange_book: '1f4d9', open_hands: '1f450', mobile_phone_off: '1f4f4', monkey_face: '1f435', monorail: '1f69d', oden: '1f362', oncoming_automobile: '1f698', cyclone: '1f300', panda_face: '1f43c', oncoming_bus: '1f68d', moon: '1f314', fearful: '1f628', eyes: '1f440', person_with_blond_hair: '1f471', leopard: '1f406', ram: '1f40f', penguin: '1f427', repeat_one: '1f502', parking: '1f17f', pager: '1f4df', pig2: '1f416', rabbit: '1f430', envelope: '2709', pig_nose: '1f43d', closed_lock_with_key: '<KEY>', ghost: '1f47b', confused: '1f615', closed_book: '1f4d5', clock830: '1f563', dollar: '1f4b5', ribbon: '1f380', clock530: '1f560', clock8: '1f557', clock430: '1f55f', clock11: '1f55a', city_sunrise: '1f307', clock6: '1f555', circus_tent: '1f3aa', clock7: '1f556', cl: '1f191', chocolate_bar: '1f36b', clock1: '1f550', name_badge: '1f4db', clock630: '1f561', clock10: '1f559', cd: '1f4bf', clock9: '1f558', clipboard: '1f4cb', clock1230: '1f567', chart_with_downwards_trend: '1f4c9', chart: '1f4b9', clock730: '1f562', chicken: '1f414', performing_arts: '1f3ad', city_sunset: '1f306', christmas_tree: '1f384', cherries: '1f352', camel: '1f42b', cat2: '1f408', cactus: '1f335', bug: '1f41b', cake: '1f370', bullettrain_side: '1f684', calendar: '1f4c6', checkered_flag: '1f3c1', bus: '1f68c', broken_heart: '1f494', busts_in_silhouette: '1f465', bullettrain_front: '1f685', chestnut: '1f330', calling: '1f4f2', bread: '1f35e', bridge_at_night: '1f309', briefcase: '1f4bc', bouquet: '1f490', bowling: '1f3b3', bow: '1f647', droplet: '1f4a7', blossom: '1f33c', clap: '1f44f', clock130: '1f55c', cinema: '1f3a6', clubs: '2663', clock5: '1f554', children_crossing: '1f6b8', boy: '1f466', camera: '1f4f7', bento: '1f371', black_large_square: '2b1b', black_nib: '2712', birthday: '1f382', black_medium_small_square: '25fe', bird: '1f426', black_joker: '1f0cf', bicyclist: '1f6b4', black_circle: '26ab', beetle: '1f41e', bikini: '1f459', no_smoking: '1f6ad', bike: '1f6b2', black_medium_square: '25fc', bell: '1f514', mag_right: '1f50e', bee: '1f41d', bathtub: '1f6c1', bar_chart: '1f4ca', bath: '1f6c0', barber: '1f488', baby_symbol: '1f6bc', bank: '1f3e6', bangbang: '203c', arrow_up_small: '1f53c', atm: '1f3e7', baby: '1f476', back: '1f519', arrows_clockwise: '1f503', b: '1f171', arrow_upper_left: '2196', balloon: '1f388', athletic_shoe: '1f45f', arrows_counterclockwise: '1f504', ballot_box_with_check: '2611', articulated_lorry: '1f69b', round_pushpin: '1f4cd', radio_button: '1f518', raised_hands: '1f64c', raised_hand: '270b', purse: '1f45b', put_litter_in_its_place: '1f6ae', rage: '1f621', pushpin: '1f4cc', pineapple: '1f34d', dash: '1f4a8', bear: '1f43b', baggage_claim: '1f6c4', art: '1f3a8', arrow_upper_right: '2197', chart_with_upwards_trend: '1f4c8', baby_chick: '1f424', baseball: '26be', baby_bottle: '1f37c', arrow_forward: '25b6', aries: '2648', arrow_left: '2b05', arrow_lower_left: '2199', arrow_right: '27a1', ab: '1f18e', arrow_down: '2b07', anger: '1f4a2', accept: '1f251', arrow_lower_right: '2198', arrow_double_up: '23eb', arrow_down_small: '1f53d', arrow_heading_up: '2934', aquarius: '2652', arrow_backward: '25c0', abc: '1f524', aerial_tramway: '1f6a1', astonished: '1f632', alarm_clock: '23f0', angry: '1f620', arrow_right_hook: '21aa', arrow_double_down: '23ec', arrow_heading_down: '2935', apple: '1f34e', airplane: '2708', angel: '1f47c', anchor: '2693', '-1': '1f44e', zero: '0030', yellow_heart: '1f49b', zzz: '1f4a4', zap: '26a1', womens: '1f6ba', woman: '1f469', wind_chime: '1f390', wink: '1f609', wave: '1f44b', wc: '1f6be', white_square_button: '1f533', womans_hat: '1f452', white_flower: '1f4ae', wine_glass: '1f377', womans_clothes: '1f45a', white_small_square: '25ab', worried: '1f61f', violin: '1f3bb', two_women_holding_hands: '1f46d', whale2: '1f40b', waning_gibbous_moon: '1f316', virgo: '264d', tulip: '1f337', u5272: '1f239', u5408: '1f234', watch: '231a', wavy_dash: '3030', trumpet: '1f3ba', two_men_holding_hands: '1f46c', two_hearts: '1f495', u55b6: '1f23a', volcano: '1f30b', warning: '26a0', video_game: '1f3ae', truck: '1f69a', tropical_fish: '1f420', u6708: '1f237', up: '1f199', watermelon: '1f349', tired_face: '1f62b', twisted_rightwards_arrows: '1f500', train: '1f683', tongue: '1f445', water_buffalo: '1f403', two: '0032', yum: '1f60b', turtle: '1f422', waning_crescent_moon: '1f318', traffic_light: '1f6a5', tshirt: '1f455', vibration_mode: '1f4f3', u6307: '1f22f', vs: '1f19a', toilet: '1f6bd', tokyo_tower: '1f5fc', thumbsdown: '1f44e', thumbsup: '1f44d', tangerine: '1f34a', three: '0033', ticket: '1f3ab', tennis: '1f3be', taurus: '2649', tm: '2122', taxi: '1f695', tada: '1f389', tea: '1f375', telescope: '1f52d', symbols: '1f523', tanabata_tree: '1f38b', syringe: '1f489', sunny: '2600', suspension_railway: '1f69f', sweet_potato: '1f360', stuck_out_tongue_closed_eyes: '1f61d', sushi: '1f363', stew: '1f372', sweat_smile: '1f605', six_pointed_star: '1f52f', space_invader: '1f47e', signal_strength: '1f4f6', stuck_out_tongue_winking_eye: '1f61c', seven: '0037', steam_locomotive: '1f682', strawberry: '1f353', swimmer: '1f3ca', skull: '1f480', straight_ruler: '1f4cf', sunrise: '1f305', sweat: '1f613', sun_with_face: '1f31e', sparkles: '2728', statue_of_liberty: '1f5fd', sleeping: '1f634', soon: '1f51c', beginner: '1f530', yen: '1f4b4', beers: '1f37b', white_medium_square: '25fb', wolf: '1f43a', wrench: '1f527', video_camera: '1f4f9', walking: '1f6b6', waxing_crescent_moon: '1f312', wheelchair: '267f', tiger2: '1f405', sweat_drops: '1f4a6', seedling: '1f331', wedding: '1f492', u7533: '1f238', umbrella: '2614', sunrise_over_mountains: '1f304', us: '1f1fa', u7981: '1f232', u7a7a: '1f233', underage: '1f51e', unamused: '1f612', u7121: '1f21a', sparkle: '2747', sob: '1f62d', stuck_out_tongue: '1f61b', u6e80: '1f235', tropical_drink: '1f379', trophy: '1f3c6', trolleybus: '1f68e', triangular_ruler: '1f4d0', trident: '1f531', top: '1f51d', tomato: '1f345', telephone: '260e', thought_balloon: '1f4ad', tophat: '1f3a9', tractor: '1f69c', soccer: '26bd', six: '0036', scream_cat: '1f640', shaved_ice: '1f367', spades: '2660', dvd: '1f4c0', flower_playing_cards: '1f3b4', cry: '1f622', hospital: '1f3e5', hotel: '1f3e8', herb: '1f33f', heavy_plus_sign: '2795', hatched_chick: '1f425', hammer: '1f528', grey_exclamation: '2755', green_apple: '1f34f', grinning: '1f600', heavy_minus_sign: '2796', hamburger: '1f354', guardsman: '1f482', hand: '270b', green_heart: '1f49a', grey_question: '2754', golf: '26f3', grapes: '1f347', heartbeat: '1f493', grimacing: '1f62c', hatching_chick: '1f423', dolls: '1f38e', de: '1f1e9', do_not_litter: '1f6af', dress: '1f457', custard: '1f36e', eight: '0038', earth_africa: '1f30d', guitar: '1f3b8', game_die: '1f3b2', fallen_leaf: '1f342', heart: '2764', expressionless: '1f611', crescent_moon: '1f319', electric_plug: '1f50c', crystal_ball: '1f52e', arrow_up_down: '2195', banana: '1f34c' }`
true
# Description: # emoji.coffee - Replaces :text: or text with emojis. # Great for IRC or anywhere not already emojified. # # Dependencies: # None # # Configuration: # None # # Commands: # "put a bird on it" - Prints "put a 🐦 on it" in 'more' emoji mode. # "put a :bird: on it" - Prints "put a 🐦 on it" in 'less' emoji mode. # hubot list emoji - Print a list of available emojis # hubot more emoji - Try to substitute all words - no :colons: required. # hubot less emoji - Require :colons: to substitute emojis (default). # # Notes: # Emoji/unicode pairing data from https://github.com/github/gemoji # # Author: # dzello module.exports = (robot) -> robot.brain.on "loaded", -> robot.brain.data.emojis ?= {} robot.hear /.+/, (msg) -> if textWithEmoji = substituteEmoji(msg.message.text, robot) msg.send(textWithEmoji) robot.respond /more emoji/, (msg) -> robot.brain.data.emojis.more = true robot.respond /less emoji/, (msg) -> robot.brain.data.emojis.more = false robot.respond /list emoji/, (msg) -> buf = "" for symbol, hexCode of emojis buf += "#{toEmoji(hexCode)} #{symbol}\n" msg.send buf substituteEmoji = (text, robot) -> ct = 0 re = if robot.brain.data.emojis.more then /([a-zA-Z0-9_:]{3,})/g else /:([a-zA-Z0-9_]+):/g text = text.replace re, (match, key) -> if emoji = emojis[key.toLowerCase().replace(/:/g, '')] ct++ toEmoji(emoji) + " " else key text if ct > 0 toEmoji = (hexCode) -> fromFullCharCode(parseInt(hexCode, 16)) fromFullCharCode = (args...) -> chars= [] for n in args if (n < 0x10000) chars.push(String.fromCharCode(n)); else high = Math.floor((n - 0x10000) / 0x400) + 0xD800 low = (n - 0x10000) % 0x400 + 0xDC00 chars.push(String.fromCharCode(high, low)) chars.join('') `emojis = { '100': '1f4af', '1234': '1f522', haircut: '1f487', house: '1f3e0', ideograph_advantage: '1f250', house_with_garden: '1f3e1', incoming_envelope: '1f4e8', japan: '1f5fe', information_source: '2139', it: '1f1ee', inbox_tray: '1f4e5', pisces: '2653', loudspeaker: '1f4e2', loop: '27bf', lips: '1f444', libra: '264e', leaves: '1f343', large_blue_diamond: '1f537', man: '1f468', laughing: '1f606', light_rail: '1f688', police_car: '1f693', mountain_railway: '1f69e', mailbox_closed: '1f4ea', musical_note: '1f3b5', left_right_arrow: '2194', link: '1f517', leo: '264c', last_quarter_moon_with_face: '1f31c', love_hotel: '1f3e9', lipstick: '1f484', leftwards_arrow_with_hook: '21a9', ledger: '1f4d2', japanese_goblin: '1f47a', left_luggage: '1f6c5', japanese_ogre: '1f479', information_desk_person: '1f481', large_orange_diamond: '1f536', koala: '1f428', kissing_cat: '1f63d', large_blue_circle: '1f535', koko: '1f201', jp: '1f1ef', joy: '1f602', last_quarter_moon: '1f317', lantern: '1f3ee', kr: '1f1f0', interrobang: '2049', jack_o_lantern: '1f383', imp: '1f47f', izakaya_lantern: '1f3ee', japanese_castle: '1f3ef', joy_cat: '1f639', key: 'PI:KEY:<KEY>END_PI', kiss: '1f48b', kissing_smiling_eyes: '1f619', kissing_closed_eyes: '1f61a', kimono: '1f458', jeans: '1f456', icecream: '1f366', iphone: '1f4f1', kissing: '1f617', id: '1f194', innocent: '1f607', hushed: '1f62f', ice_cream: '1f368', hourglass_flowing_sand: '23f3', hourglass: '231b', no_entry: '26d4', lock: '1f512', memo: '1f4dd', muscle: '1f4aa', lock_with_ink_pen: '1f50f', lemon: '1f34b', keycap_ten: '1f51f', microphone: '1f3a4', no_mobile_phones: '1f4f5', mouse2: '1f401', kissing_heart: '1f618', man_with_gua_pi_mao: '1f472', microscope: '1f52c', point_down: '1f447', pizza: '1f355', pouch: '1f45d', pound: '1f4b7', potable_water: '1f6b0', no_mouth: '1f636', postbox: '1f4ee', poultry_leg: '1f357', point_right: '1f449', post_office: '1f3e3', point_left: '1f448', point_up_2: '1f446', poodle: '1f429', pray: '1f64f', no_pedestrians: '1f6b7', moyai: '1f5ff', point_up: '261d', monkey: '1f412', postal_horn: '1f4ef', no_entry_sign: '1f6ab', newspaper: '1f4f0', poop: '1f4a9', pouting_cat: '1f63e', princess: '1f478', nine: '0039', neutral_face: '1f610', no_bell: '1f515', ng: '1f196', metro: '1f687', necktie: '1f454', new: '1f195', mute: '1f507', no_good: '1f645', new_moon_with_face: '1f31a', nail_care: '1f485', low_brightness: '1f505', couplekiss: '1f48f', copyright: '00a9', couple: '1f46b', couple_with_heart: '1f491', cookie: '1f36a', construction: '1f6a7', cool: '1f192', cherry_blossom: '1f338', clock4: '1f553', corn: '1f33d', credit_card: '1PI:KEY:<KEY>END_PI', clock1030: '1f565', church: '26ea', cop: '1f46e', convenience_store: '1f3ea', cow: '1f42e', clapper: '1f3ac', clock1130: '1f566', clock12: '1f55b', card_index: '1f4c7', cat: '1f431', bomb: '1f4a3', car: '1f697', cancer: '264b', capricorn: '2651', blush: '1f60a', candy: '1f36c', boom: '1f4a5', capital_abcd: '1f520', clock930: '1f564', bride_with_veil: '1f470', book: '1f4d6', bookmark_tabs: '1f4d1', blue_book: '1f4d8', carousel_horse: '1f3a0', bust_in_silhouette: '1f464', boat: '26f5', blowfish: '1f421', bookmark: '1f516', books: '1f4da', black_small_square: '25aa', boar: '1f417', blue_heart: '1f499', boot: '1f462', santa: '1f385', saxophone: '1f3b7', scream: '1f631', minidisc: '1f4bd', school_satchel: '1f392', scorpius: '264f', blue_car: '1f699', scissors: '2702', satisfied: '1f606', sandal: '1f461', black_square_button: '1f532', school: '1f3eb', hamster: '1f439', satellite: '1f4e1', sake: '1f376', sa: '1f202', busstop: '1f68f', sailboat: '26f5', running_shirt_with_sash: '1f3bd', bulb: '1f4a1', sagittarius: '2650', mushroom: '1f344', massage: '1f486', mailbox_with_mail: '1f4ec', m: '24c2', maple_leaf: '1f341', mailbox_with_no_mail: '1f4ed', mask: '1f637', mega: '1f4e3', basketball: '1f3c0', arrow_up: '2b06', abcd: '1f521', '+1': '1f44d', alien: '1f47d', ant: '1f41c', anguished: '1f627', sheep: '1f411', a: '1f170', sos: '1f198', '8ball': '1f3b1', office: '1f3e2', older_man: '1f474', seat: '1f4ba', smirk_cat: '1f63c', tiger: '1f42f', vhs: '1f4fc', surfer: '1f3c4', ok_hand: '1f44c', 'non-potable_water': '1f6b1', older_woman: '1f475', ok: '1f197', octopus: '1f419', mountain_cableway: '1f6a0', unlock: '1f513', nose: '1f443', mount_fuji: '1f5fb', notebook_with_decorative_cover: '1f4d4', ok_woman: '1f646', notes: '1f3b6', nut_and_bolt: '1f529', ocean: '1f30a', o: '2b55', new_moon: '1f311', mountain_bicyclist: '1f6b5', notebook: '1f4d3', mag: '1f50d', no_bicycles: '1f6b3', train2: '1f686', smile: '1f604', shirt: '1f455', speak_no_evil: '1f64a', vertical_traffic_light: '1f6a6', shit: '1f4a9', musical_keyboard: '1f3b9', ambulance: '1f691', tv: '1f4fa', battery: '1f50b', lollipop: '1f36d', mouse: '1f42d', movie_camera: '1f3a5', bamboo: '1f38d', cold_sweat: '1f630', mens: '1f6b9', station: '1f689', sound: '1f509', first_quarter_moon: '1f313', elephant: '1f418', doughnut: '1f369', door: '1f6aa', earth_asia: '1f30f', fire: '1f525', cloud: '2601', ear: '1f442', eight_pointed_black_star: '2734', dizzy: '1f4ab', crocodile: '1f40a', mailbox: '1f4eb', feet: '1f43e', heart_eyes: '1f60d', currency_exchange: '1f4b1', facepunch: '1f44a', hankey: '1PI:KEY:<KEY>END_PI', minibus: '1f690', ferris_wheel: '1f3a1', fireworks: '1f386', crossed_flags: '1f38c', department_store: '1f3ec', heavy_check_mark: '2714', fountain: '26f2', flushed: '1f633', fork_and_knife: '1f374', waxing_gibbous_moon: '1f314', dragon_face: '1f432', x: '274c', white_circle: '26aa', sparkler: '1f387', white_medium_small_square: '25fd', white_check_mark: '2705', uk: '1f1ec', v: '270c', sunflower: '1f33b', white_large_square: '2b1c', tent: '26fa', triangular_flag_on_post: '1f6a9', telephone_receiver: '1f4de', tram: '1f68a', whale: '1f433', triumph: '1f624', weary: '1f629', hash: '0023', speech_balloon: '1f4ac', sparkling_heart: '1f496', stars: '1f303', speaker: '1f50a', snowflake: '2744', sunglasses: '1f60e', speedboat: '1f6a4', snake: '1f40d', earth_americas: '1f30e', smile_cat: '1f638', star2: '1f31f', small_orange_diamond: '1f538', smoking: '1f6ac', spaghetti: '1f35d', sleepy: '1f62a', star: '2b50', smiley: '1f603', small_red_triangle_down: '1f53b', snowman: '26c4', small_blue_diamond: '1f539', pig: '1f437', rice: '1f35a', smiley_cat: '1f63a', snowboarder: '1f3c2', heavy_dollar_sign: '1f4b2', smirk: '1f60f', rugby_football: '1f3c9', smiling_imp: '1f608', rowboat: '1f6a3', shower: '1f6bf', slot_machine: '1f3b0', shell: '1f41a', hear_no_evil: '1f649', pensive: '1f614', hibiscus: '1f33a', person_frowning: '1f64d', raising_hand: '1f64b', rabbit2: '1f407', snail: '1f40c', ramen: '1f35c', radio: '1f4fb', deciduous_tree: '1f333', diamond_shape_with_a_dot_inside: '1f4a0', first_quarter_moon_with_face: '1f31b', dog: '1f436', eggplant: '1f346', shoe: '1f45e', customs: '1f6c3', pill: '1f48a', 'e-mail': '1f4e7', dolphin: '1f42c', disappointed_relieved: '1f625', dizzy_face: '1f635', curly_loop: '27b0', crying_cat_face: '1f63f', milky_way: '1f30c', small_red_triangle: '1f53a', coffee: '2615', flashlight: '1f526', eight_spoked_asterisk: '2733', heart_decoration: '1f49f', open_mouth: '1f62e', curry: '1f35b', passport_control: '1f6c2', cupid: '1f498', high_heel: '1f460', heavy_exclamation_mark: '2757', gun: '1f52b', fries: '1f35f', melon: '1f348', euro: '1f4b6', meat_on_bone: '1f356', fish_cake: '1f365', gem: '1f48e', mahjong: '1f004', dog2: '1f415', egg: '1f373', date: '1f4c5', girl: '1f467', free: '1f193', ear_of_rice: '1f33e', full_moon: '1f315', man_with_turban: '1f473', european_castle: '1f3f0', five: '0035', fax: '1f4e0', crown: '1f451', diamonds: '2666', fist: '270a', cn: '1f1e8', flags: '1f38f', grin: '1f601', exclamation: '2757', green_book: '1f4d7', fishing_pole_and_fish: '1f3a3', cocktail: '1f378', factory: '1f3ed', frowning: '1f626', fr: '1f1eb', envelope_with_arrow: '1f4e9', handbag: '1f45c', foggy: '1f301', floppy_disk: '1f4be', beer: '1f37a', footprints: '1f463', globe_with_meridians: '1f310', mans_shoe: '1f45e', dango: '1f361', dancer: '1f483', gift_heart: '1f49d', dromedary_camel: '1f42a', clock330: '1f55e', clock3: '1f552', construction_worker: '1f477', cow2: '1f404', email: '2709', fast_forward: '23e9', file_folder: '1f4c1', collision: '1f4a5', clock230: '1f55d', horse_racing: '1f3c7', fish: '1f41f', clock2: '1f551', confetti_ball: '1f38a', heavy_division_sign: '2797', u6709: '1f236', full_moon_with_face: '1f31d', european_post_office: '1f3e4', ski: '1f3bf', congratulations: '3297', football: '1f3c8', four_leaf_clover: '1f340', negative_squared_cross_mark: '274e', confounded: '1f616', money_with_wings: '1f4b8', honey_pot: '1f36f', closed_umbrella: '1f302', computer: '1f4bb', hearts: '2665', dart: '1f3af', heart_eyes_cat: '1f63b', love_letter: '1f48c', racehorse: '1f40e', helicopter: '1f681', honeybee: '1f41d', railway_car: '1f683', musical_score: '1f3bc', fire_engine: '1f692', heavy_multiplication_x: '2716', heartpulse: '1f497', hotsprings: '2668', headphones: '1f3a7', family: '1f46a', end: '1f51a', dragon: '1f409', evergreen_tree: '1f332', hocho: '1f52a', high_brightness: '1f506', ship: '1f6a2', horse: '1f434', see_no_evil: '1f648', es: '1f1ea', ru: '1f1f7', runner: '1f3c3', goat: '1f410', o2: '1f17e', scroll: '1f4dc', running: '1f3c3', punch: '1f44a', secret: '3299', question: '2753', persevere: '1f623', frog: '1f438', four: '0034', gift: '1f381', gemini: '264a', dancers: '1f46f', relaxed: '263a', repeat: '1f501', red_circle: '1f534', phone: '260e', rocket: '1f680', purple_heart: '1f49c', rose: '1f339', fuelpump: '26fd', person_with_pouting_face: '1f64e', red_car: '1f697', rewind: '23ea', rice_ball: '1f359', disappointed: '1f61e', rooster: '1f413', restroom: '1f6bb', registered: '00ae', relieved: '1f60c', recycle: '267b', rotating_light: '1f6a8', rainbow: '1f308', rice_cracker: '1f358', pear: '1f350', ring: '1f48d', rat: '1f400', eyeglasses: '1f453', gb: '1f1ec', pencil: '1f4dd', fried_shrimp: '1f364', revolving_hearts: '1f49e', pencil2: '270f', partly_sunny: '26c5', outbox_tray: '1f4e4', page_with_curl: '1f4c3', part_alternation_mark: '303d', peach: '1f351', rice_scene: '1f391', roller_coaster: '1f3a2', oncoming_police_car: '1f694', paperclip: '1f4ce', open_file_folder: '1f4c2', page_facing_up: '1f4c4', paw_prints: '1f43e', palm_tree: '1f334', ox: '1f402', package: '1f4e6', one: '0031', open_book: '1f4d6', oncoming_taxi: '1f696', mortar_board: '1f393', on: '1f51b', ophiuchus: '26ce', moneybag: '1f4b0', orange_book: '1f4d9', open_hands: '1f450', mobile_phone_off: '1f4f4', monkey_face: '1f435', monorail: '1f69d', oden: '1f362', oncoming_automobile: '1f698', cyclone: '1f300', panda_face: '1f43c', oncoming_bus: '1f68d', moon: '1f314', fearful: '1f628', eyes: '1f440', person_with_blond_hair: '1f471', leopard: '1f406', ram: '1f40f', penguin: '1f427', repeat_one: '1f502', parking: '1f17f', pager: '1f4df', pig2: '1f416', rabbit: '1f430', envelope: '2709', pig_nose: '1f43d', closed_lock_with_key: 'PI:KEY:<KEY>END_PI', ghost: '1f47b', confused: '1f615', closed_book: '1f4d5', clock830: '1f563', dollar: '1f4b5', ribbon: '1f380', clock530: '1f560', clock8: '1f557', clock430: '1f55f', clock11: '1f55a', city_sunrise: '1f307', clock6: '1f555', circus_tent: '1f3aa', clock7: '1f556', cl: '1f191', chocolate_bar: '1f36b', clock1: '1f550', name_badge: '1f4db', clock630: '1f561', clock10: '1f559', cd: '1f4bf', clock9: '1f558', clipboard: '1f4cb', clock1230: '1f567', chart_with_downwards_trend: '1f4c9', chart: '1f4b9', clock730: '1f562', chicken: '1f414', performing_arts: '1f3ad', city_sunset: '1f306', christmas_tree: '1f384', cherries: '1f352', camel: '1f42b', cat2: '1f408', cactus: '1f335', bug: '1f41b', cake: '1f370', bullettrain_side: '1f684', calendar: '1f4c6', checkered_flag: '1f3c1', bus: '1f68c', broken_heart: '1f494', busts_in_silhouette: '1f465', bullettrain_front: '1f685', chestnut: '1f330', calling: '1f4f2', bread: '1f35e', bridge_at_night: '1f309', briefcase: '1f4bc', bouquet: '1f490', bowling: '1f3b3', bow: '1f647', droplet: '1f4a7', blossom: '1f33c', clap: '1f44f', clock130: '1f55c', cinema: '1f3a6', clubs: '2663', clock5: '1f554', children_crossing: '1f6b8', boy: '1f466', camera: '1f4f7', bento: '1f371', black_large_square: '2b1b', black_nib: '2712', birthday: '1f382', black_medium_small_square: '25fe', bird: '1f426', black_joker: '1f0cf', bicyclist: '1f6b4', black_circle: '26ab', beetle: '1f41e', bikini: '1f459', no_smoking: '1f6ad', bike: '1f6b2', black_medium_square: '25fc', bell: '1f514', mag_right: '1f50e', bee: '1f41d', bathtub: '1f6c1', bar_chart: '1f4ca', bath: '1f6c0', barber: '1f488', baby_symbol: '1f6bc', bank: '1f3e6', bangbang: '203c', arrow_up_small: '1f53c', atm: '1f3e7', baby: '1f476', back: '1f519', arrows_clockwise: '1f503', b: '1f171', arrow_upper_left: '2196', balloon: '1f388', athletic_shoe: '1f45f', arrows_counterclockwise: '1f504', ballot_box_with_check: '2611', articulated_lorry: '1f69b', round_pushpin: '1f4cd', radio_button: '1f518', raised_hands: '1f64c', raised_hand: '270b', purse: '1f45b', put_litter_in_its_place: '1f6ae', rage: '1f621', pushpin: '1f4cc', pineapple: '1f34d', dash: '1f4a8', bear: '1f43b', baggage_claim: '1f6c4', art: '1f3a8', arrow_upper_right: '2197', chart_with_upwards_trend: '1f4c8', baby_chick: '1f424', baseball: '26be', baby_bottle: '1f37c', arrow_forward: '25b6', aries: '2648', arrow_left: '2b05', arrow_lower_left: '2199', arrow_right: '27a1', ab: '1f18e', arrow_down: '2b07', anger: '1f4a2', accept: '1f251', arrow_lower_right: '2198', arrow_double_up: '23eb', arrow_down_small: '1f53d', arrow_heading_up: '2934', aquarius: '2652', arrow_backward: '25c0', abc: '1f524', aerial_tramway: '1f6a1', astonished: '1f632', alarm_clock: '23f0', angry: '1f620', arrow_right_hook: '21aa', arrow_double_down: '23ec', arrow_heading_down: '2935', apple: '1f34e', airplane: '2708', angel: '1f47c', anchor: '2693', '-1': '1f44e', zero: '0030', yellow_heart: '1f49b', zzz: '1f4a4', zap: '26a1', womens: '1f6ba', woman: '1f469', wind_chime: '1f390', wink: '1f609', wave: '1f44b', wc: '1f6be', white_square_button: '1f533', womans_hat: '1f452', white_flower: '1f4ae', wine_glass: '1f377', womans_clothes: '1f45a', white_small_square: '25ab', worried: '1f61f', violin: '1f3bb', two_women_holding_hands: '1f46d', whale2: '1f40b', waning_gibbous_moon: '1f316', virgo: '264d', tulip: '1f337', u5272: '1f239', u5408: '1f234', watch: '231a', wavy_dash: '3030', trumpet: '1f3ba', two_men_holding_hands: '1f46c', two_hearts: '1f495', u55b6: '1f23a', volcano: '1f30b', warning: '26a0', video_game: '1f3ae', truck: '1f69a', tropical_fish: '1f420', u6708: '1f237', up: '1f199', watermelon: '1f349', tired_face: '1f62b', twisted_rightwards_arrows: '1f500', train: '1f683', tongue: '1f445', water_buffalo: '1f403', two: '0032', yum: '1f60b', turtle: '1f422', waning_crescent_moon: '1f318', traffic_light: '1f6a5', tshirt: '1f455', vibration_mode: '1f4f3', u6307: '1f22f', vs: '1f19a', toilet: '1f6bd', tokyo_tower: '1f5fc', thumbsdown: '1f44e', thumbsup: '1f44d', tangerine: '1f34a', three: '0033', ticket: '1f3ab', tennis: '1f3be', taurus: '2649', tm: '2122', taxi: '1f695', tada: '1f389', tea: '1f375', telescope: '1f52d', symbols: '1f523', tanabata_tree: '1f38b', syringe: '1f489', sunny: '2600', suspension_railway: '1f69f', sweet_potato: '1f360', stuck_out_tongue_closed_eyes: '1f61d', sushi: '1f363', stew: '1f372', sweat_smile: '1f605', six_pointed_star: '1f52f', space_invader: '1f47e', signal_strength: '1f4f6', stuck_out_tongue_winking_eye: '1f61c', seven: '0037', steam_locomotive: '1f682', strawberry: '1f353', swimmer: '1f3ca', skull: '1f480', straight_ruler: '1f4cf', sunrise: '1f305', sweat: '1f613', sun_with_face: '1f31e', sparkles: '2728', statue_of_liberty: '1f5fd', sleeping: '1f634', soon: '1f51c', beginner: '1f530', yen: '1f4b4', beers: '1f37b', white_medium_square: '25fb', wolf: '1f43a', wrench: '1f527', video_camera: '1f4f9', walking: '1f6b6', waxing_crescent_moon: '1f312', wheelchair: '267f', tiger2: '1f405', sweat_drops: '1f4a6', seedling: '1f331', wedding: '1f492', u7533: '1f238', umbrella: '2614', sunrise_over_mountains: '1f304', us: '1f1fa', u7981: '1f232', u7a7a: '1f233', underage: '1f51e', unamused: '1f612', u7121: '1f21a', sparkle: '2747', sob: '1f62d', stuck_out_tongue: '1f61b', u6e80: '1f235', tropical_drink: '1f379', trophy: '1f3c6', trolleybus: '1f68e', triangular_ruler: '1f4d0', trident: '1f531', top: '1f51d', tomato: '1f345', telephone: '260e', thought_balloon: '1f4ad', tophat: '1f3a9', tractor: '1f69c', soccer: '26bd', six: '0036', scream_cat: '1f640', shaved_ice: '1f367', spades: '2660', dvd: '1f4c0', flower_playing_cards: '1f3b4', cry: '1f622', hospital: '1f3e5', hotel: '1f3e8', herb: '1f33f', heavy_plus_sign: '2795', hatched_chick: '1f425', hammer: '1f528', grey_exclamation: '2755', green_apple: '1f34f', grinning: '1f600', heavy_minus_sign: '2796', hamburger: '1f354', guardsman: '1f482', hand: '270b', green_heart: '1f49a', grey_question: '2754', golf: '26f3', grapes: '1f347', heartbeat: '1f493', grimacing: '1f62c', hatching_chick: '1f423', dolls: '1f38e', de: '1f1e9', do_not_litter: '1f6af', dress: '1f457', custard: '1f36e', eight: '0038', earth_africa: '1f30d', guitar: '1f3b8', game_die: '1f3b2', fallen_leaf: '1f342', heart: '2764', expressionless: '1f611', crescent_moon: '1f319', electric_plug: '1f50c', crystal_ball: '1f52e', arrow_up_down: '2195', banana: '1f34c' }`
[ { "context": " url = null\n sampleUser =\n id: 24\n name: 'test user'\n email: 'test.user@guc.edu.eg'\n verified: ", "end": 204, "score": 0.6421984434127808, "start": 195, "tag": "USERNAME", "value": "test user" }, { "context": "er =\n id: 24\n name: 'test user'\n...
spec/controllers/signup_spec.coffee
ah450/guclink-auth-www
0
describe 'SignupController', -> beforeEach module 'guclinkAuth' $controller = null $httpBackend = null $rootScope = null $state = null url = null sampleUser = id: 24 name: 'test user' email: 'test.user@guc.edu.eg' verified: false student: false super_user: false full_name: 'Test User' created_at: '2016-04-08T20:06:45.391Z' updated_at: '2016-04-08T20:06:45.391Z' beforeEach inject (_$controller_, _$httpBackend_, _$rootScope_, _$state_) -> $controller = _$controller_ $httpBackend = _$httpBackend_ $state = _$state_ $rootScope = _$rootScope_ url = ['http://localhost:3000/api', 'users.json'].join '/' beforeEach -> $httpBackend.when('GET', 'http://localhost:3000/api/configurations.json') .respond({ default_token_exp: 30, pass_reset_resend_delay: 120, pass_reset_expiration: 240, verification_expiration: 3600 }) it 'sets processing to true', -> $httpBackend.when('POST', url) .respond 201, sampleUser $scope = {} controller = $controller 'SignupController', {$scope: $scope} $scope.userData = sampleUser $scope.submit() expect($scope.processing).to.be.true $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'transitions to welcome state', -> $httpBackend.when('POST', url) .respond 201, sampleUser $scope = {} controller = $controller 'SignupController', {$scope: $scope} $scope.userData = sampleUser $scope.submit() $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() $rootScope.$apply() expect($state.current.name).to.eql('public.welcome')
206360
describe 'SignupController', -> beforeEach module 'guclinkAuth' $controller = null $httpBackend = null $rootScope = null $state = null url = null sampleUser = id: 24 name: 'test user' email: '<EMAIL>' verified: false student: false super_user: false full_name: '<NAME>' created_at: '2016-04-08T20:06:45.391Z' updated_at: '2016-04-08T20:06:45.391Z' beforeEach inject (_$controller_, _$httpBackend_, _$rootScope_, _$state_) -> $controller = _$controller_ $httpBackend = _$httpBackend_ $state = _$state_ $rootScope = _$rootScope_ url = ['http://localhost:3000/api', 'users.json'].join '/' beforeEach -> $httpBackend.when('GET', 'http://localhost:3000/api/configurations.json') .respond({ default_token_exp: 30, pass_reset_resend_delay: 120, pass_reset_expiration: 240, verification_expiration: 3600 }) it 'sets processing to true', -> $httpBackend.when('POST', url) .respond 201, sampleUser $scope = {} controller = $controller 'SignupController', {$scope: $scope} $scope.userData = sampleUser $scope.submit() expect($scope.processing).to.be.true $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'transitions to welcome state', -> $httpBackend.when('POST', url) .respond 201, sampleUser $scope = {} controller = $controller 'SignupController', {$scope: $scope} $scope.userData = sampleUser $scope.submit() $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() $rootScope.$apply() expect($state.current.name).to.eql('public.welcome')
true
describe 'SignupController', -> beforeEach module 'guclinkAuth' $controller = null $httpBackend = null $rootScope = null $state = null url = null sampleUser = id: 24 name: 'test user' email: 'PI:EMAIL:<EMAIL>END_PI' verified: false student: false super_user: false full_name: 'PI:NAME:<NAME>END_PI' created_at: '2016-04-08T20:06:45.391Z' updated_at: '2016-04-08T20:06:45.391Z' beforeEach inject (_$controller_, _$httpBackend_, _$rootScope_, _$state_) -> $controller = _$controller_ $httpBackend = _$httpBackend_ $state = _$state_ $rootScope = _$rootScope_ url = ['http://localhost:3000/api', 'users.json'].join '/' beforeEach -> $httpBackend.when('GET', 'http://localhost:3000/api/configurations.json') .respond({ default_token_exp: 30, pass_reset_resend_delay: 120, pass_reset_expiration: 240, verification_expiration: 3600 }) it 'sets processing to true', -> $httpBackend.when('POST', url) .respond 201, sampleUser $scope = {} controller = $controller 'SignupController', {$scope: $scope} $scope.userData = sampleUser $scope.submit() expect($scope.processing).to.be.true $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'transitions to welcome state', -> $httpBackend.when('POST', url) .respond 201, sampleUser $scope = {} controller = $controller 'SignupController', {$scope: $scope} $scope.userData = sampleUser $scope.submit() $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() $rootScope.$apply() expect($state.current.name).to.eql('public.welcome')
[ { "context": " user = $(\"#username\").val()\n pass = Sha256.hash($(\"#password\").val())\n if(user == \"\" |", "end": 180, "score": 0.9980272650718689, "start": 169, "tag": "PASSWORD", "value": "Sha256.hash" } ]
target/web/public/main/js/admin.coffee
zanderdk/playtest
0
angular.module("stregsystemet", []) .controller("loginController", ($scope) -> $scope.login = -> user = $("#username").val() pass = Sha256.hash($("#password").val()) if(user == "" || pass == "") $("#error").show() return false $.post("/AdminLogin", {"username": user, "password": pass}, (data) -> if(!(data.firstName?)) $("#error").show() else $("#user").val(user) $("#pass").val(pass) $("#target").submit() ) false ) $ -> $("#error").hide()
59514
angular.module("stregsystemet", []) .controller("loginController", ($scope) -> $scope.login = -> user = $("#username").val() pass = <PASSWORD>($("#password").val()) if(user == "" || pass == "") $("#error").show() return false $.post("/AdminLogin", {"username": user, "password": pass}, (data) -> if(!(data.firstName?)) $("#error").show() else $("#user").val(user) $("#pass").val(pass) $("#target").submit() ) false ) $ -> $("#error").hide()
true
angular.module("stregsystemet", []) .controller("loginController", ($scope) -> $scope.login = -> user = $("#username").val() pass = PI:PASSWORD:<PASSWORD>END_PI($("#password").val()) if(user == "" || pass == "") $("#error").show() return false $.post("/AdminLogin", {"username": user, "password": pass}, (data) -> if(!(data.firstName?)) $("#error").show() else $("#user").val(user) $("#pass").val(pass) $("#target").submit() ) false ) $ -> $("#error").hide()
[ { "context": "ge.lastfm_scrobbling_on?\n auth:\n password: localStorage.auth_password\n show_edit: not localStorage.auth_password? ", "end": 6167, "score": 0.9989797472953796, "start": 6141, "tag": "PASSWORD", "value": "localStorage.auth_password" }, { "context": "e}\"\n...
src/client/app.coffee
joshbedo/groovebasin
1
#depend "util" #depend "socketmpd" #depend "jquery-1.7.1.min" bare #depend "jquery-ui-1.8.17.custom.min" bare #depend "soundmanager2/soundmanager2-nodebug-jsmin" bare #depend "fileuploader/fileuploader" bare #depend "socket.io/socket.io.min" bare selection = ids: playlist: {} # key is id, value is some dummy value artist: {} album: {} track: {} cursor: null # the last touched id type: null # 'playlist', 'artist', 'album', or 'track' isLibrary: -> return false if not this.type? return this.type isnt 'playlist' isPlaylist: -> return false if not this.type? return this.type is 'playlist' clear: -> this.ids.artist = {} this.ids.album = {} this.ids.track = {} this.ids.playlist = {} fullClear: -> this.clear() this.type = null this.cursor = null selectOnly: (sel_name, key) -> this.clear() this.type = sel_name this.ids[sel_name][key] = true this.cursor = key server_status = null permissions = {} socket = null mpd = null base_title = document.title user_is_seeking = false user_is_volume_sliding = false started_drag = false abortDrag = -> clickTab = null trying_to_stream = false actually_streaming = false streaming_buffering = false my_user_id = null my_user_ids = {} chat_name_input_visible = false MARGIN = 10 LoadStatus = Init: 0 NoMpd: 1 NoServer: 2 GoodToGo: 3 LoadStatusMsg = [ 'Loading...' 'mpd is not running on the server.' 'Server is down.' ] load_status = LoadStatus.Init # cache jQuery objects $document = $(document) $playlist_items = $("#playlist-items") $dynamic_mode = $("#dynamic-mode") $pl_btn_repeat = $("#pl-btn-repeat") $stream_btn = $("#stream-btn") $lib_tabs = $("#lib-tabs") $upload_tab = $("#lib-tabs .upload-tab") $chat_tab = $("#lib-tabs .chat-tab") $library = $("#library") $track_slider = $("#track-slider") $nowplaying = $("#nowplaying") $nowplaying_elapsed = $nowplaying.find(".elapsed") $nowplaying_left = $nowplaying.find(".left") $vol_slider = $("#vol-slider") $chat_user_list = $("#chat-user-list") $chat_list = $("#chat-list") $chat_user_id_span = $("#user-id") $settings = $("#settings") $upload_by_url = $("#upload-by-url") $main_err_msg = $("#main-err-msg") $main_err_msg_text = $("#main-err-msg-text") haveUserName = -> server_status?.user_names[my_user_id]? getUserName = -> userIdToUserName my_user_id userIdToUserName = (user_id) -> return user_id unless server_status? user_name = server_status.user_names[user_id] return user_name ? user_id storeMyUserIds = -> # scrub stale ids. TODO: this is broken. #if server_status? # for user_id of my_user_ids # delete my_user_ids[user_id] unless server_status.user_names[user_id]? localStorage?.my_user_ids = JSON.stringify my_user_ids setUserName = (new_name) -> new_name = $.trim new_name localStorage?.user_name = new_name socket.emit 'SetUserName', new_name scrollLibraryToSelection = -> return unless (helpers = getSelHelpers())? delete helpers.playlist scrollThingToSelection $library, helpers scrollPlaylistToSelection = -> return unless (helpers = getSelHelpers())? delete helpers.track delete helpers.artist delete helpers.album scrollThingToSelection $playlist_items, helpers scrollThingToSelection = ($scroll_area, helpers) -> top_pos = null bottom_pos = null for sel_name, [ids, table, $getDiv] of helpers for id of ids item_top = ($div = $getDiv(id)).offset().top item_bottom = item_top + $div.height() if not top_pos? or item_top < top_pos top_pos = item_top if not bottom_pos? or item_bottom > bottom_pos bottom_pos = item_bottom if top_pos? scroll_area_top = $scroll_area.offset().top selection_top = top_pos - scroll_area_top selection_bottom = bottom_pos - scroll_area_top - $scroll_area.height() scroll_amt = $scroll_area.scrollTop() if selection_top < 0 $scroll_area.scrollTop scroll_amt + selection_top else if selection_bottom > 0 $scroll_area.scrollTop scroll_amt + selection_bottom selectionToFiles = (random=false) -> # render selection into a single object by file to remove duplicates # works for library only track_set = {} selRenderArtist = (artist) -> selRenderAlbum album for album in artist.albums selRenderAlbum = (album) -> selRenderTrack track for track in album.tracks selRenderTrack = (track) -> track_set[track.file] = libPosToArr(getTrackSelPos(track)) selRenderArtist(mpd.search_results.artist_table[key]) for key of selection.ids.artist selRenderAlbum(mpd.search_results.album_table[key]) for key of selection.ids.album selRenderTrack(mpd.search_results.track_table[file]) for file of selection.ids.track if random files = (file for file of track_set) Util.shuffle files return files else track_arr = ({file: file, pos: pos} for file, pos of track_set) track_arr.sort (a, b) -> Util.compareArrays(a.pos, b.pos) return (track.file for track in track_arr) getDragPosition = (x, y) -> # loop over the playlist items and find where it fits best = track_id: null distance: null direction: null for item in $playlist_items.find(".pl-item").get() $item = $(item) pos = $item.offset() height = $item.height() track_id = parseInt($item.data('id')) # try the top of this element distance = Math.abs(pos.top - y) if not best.distance? or distance < best.distance best.distance = distance best.direction = "top" best.track_id = track_id # try the bottom distance = Math.abs(pos.top + height - y) if distance < best.distance best.distance = distance best.direction = "bottom" best.track_id = track_id return best renderSettings = -> return unless (api_key = server_status?.lastfm_api_key)? context = lastfm: auth_url: "http://www.last.fm/api/auth/?api_key=#{escape(api_key)}&cb=#{location.protocol}//#{location.host}/" username: localStorage.lastfm_username session_key: localStorage.lastfm_session_key scrobbling_on: localStorage.lastfm_scrobbling_on? auth: password: localStorage.auth_password show_edit: not localStorage.auth_password? or settings_ui.auth.show_edit permissions: permissions $settings.html Handlebars.templates.settings(context) $settings.find(".signout").button() $settings.find("#toggle-scrobble").button() $settings.find(".auth-cancel").button() $settings.find(".auth-save").button() $settings.find(".auth-edit").button() $settings.find(".auth-clear").button() $settings.find("#auth-password").val(settings_ui.auth.password) scrollChatWindowToBottom = -> # for some reason, Infinity goes to the top :/ $chat_list.scrollTop 1000000 renderChat = -> chat_status_text = "" if (users = server_status?.users)? chat_status_text = " (#{users.length})" if users.length > 1 user_objects = ({ "class": if user_id is my_user_id then "chat-user-self" else "chat-user" user_name: userIdToUserName user_id } for user_id in users) # write everyone's name in the chat objects (too bad handlebars can't do this in the template) for chat_object in server_status.chats chat_object["class"] = if my_user_ids[chat_object.user_id]? then "chat-user-self" else "chat-user" chat_object.user_name = userIdToUserName chat_object.user_id $chat_user_list.html Handlebars.templates.chat_user_list users: user_objects $chat_list.html Handlebars.templates.chat_list chats: server_status.chats scrollChatWindowToBottom() $chat_user_id_span.text if chat_name_input_visible then "" else getUserName() + ": " $chat_tab.find("span").text("Chat#{chat_status_text}") resizeChat() renderStreamButton = -> label = if trying_to_stream if actually_streaming if streaming_buffering "Stream: Buffering" else "Stream: On" else "Stream: Paused" else "Stream: Off" # disable stream button if we don't have it set up $stream_btn .button("option", "disabled", not server_status?.stream_httpd_port?) .button("option", "label", label) .prop("checked", trying_to_stream) .button("refresh") renderPlaylistButtons = -> # set the state of dynamic mode button $dynamic_mode .prop("checked", if server_status?.dynamic_mode then true else false) .button("option", "disabled", not server_status?.dynamic_mode_enabled) .button("refresh") repeat_state = getRepeatStateName() $pl_btn_repeat .button("option", "label", "Repeat: #{repeat_state}") .prop("checked", repeat_state isnt 'Off') .button("refresh") renderStreamButton() # show/hide upload $upload_tab.removeClass("ui-state-disabled") $upload_tab.addClass("ui-state-disabled") if not server_status?.upload_enabled renderPlaylist = -> context = playlist: mpd.playlist.item_list server_status: server_status scroll_top = $playlist_items.scrollTop() $playlist_items.html Handlebars.templates.playlist(context) refreshSelection() labelPlaylistItems() $playlist_items.scrollTop(scroll_top) labelPlaylistItems = -> cur_item = mpd.status.current_item # label the old ones $playlist_items.find(".pl-item").removeClass('current').removeClass('old') if cur_item? and server_status?.dynamic_mode for pos in [0...cur_item.pos] id = mpd.playlist.item_list[pos].id $("#playlist-track-#{id}").addClass('old') # label the random ones if server_status?.random_ids? for item in mpd.playlist.item_list if server_status.random_ids[item.id] $("#playlist-track-#{item.id}").addClass('random') # label the current one $("#playlist-track-#{cur_item.id}").addClass('current') if cur_item? getSelHelpers = -> return null unless mpd?.playlist?.item_table? return null unless mpd?.search_results?.artist_table? return {} = playlist: [selection.ids.playlist, mpd.playlist.item_table, (id) -> $("#playlist-track-#{id}")] artist: [selection.ids.artist, mpd.search_results.artist_table, (id) -> $("#lib-artist-#{Util.toHtmlId(id)}")] album: [selection.ids.album, mpd.search_results.album_table, (id) -> $("#lib-album-#{Util.toHtmlId(id)}")] track: [selection.ids.track, mpd.search_results.track_table, (id) -> $("#lib-track-#{Util.toHtmlId(id)}")] refreshSelection = -> return unless (helpers = getSelHelpers())? # clear all selection $playlist_items.find(".pl-item").removeClass('selected').removeClass('cursor') $library.find(".artist").removeClass('selected').removeClass('cursor') $library.find(".album").removeClass('selected').removeClass('cursor') $library.find(".track").removeClass('selected').removeClass('cursor') return unless selection.type? for sel_name, [ids, table, $getDiv] of helpers # if any selected artists are not in mpd.search_results, unselect them delete ids[id] for id in (id for id of ids when not table[id]?) # highlight selected rows $getDiv(id).addClass 'selected' for id of ids if selection.cursor? and sel_name is selection.type $getDiv(selection.cursor).addClass('cursor') renderLibrary = -> context = artists: mpd.search_results.artists empty_library_message: if mpd.have_file_list_cache then "No Results" else "loading..." scroll_top = $library.scrollTop() $library.html Handlebars.templates.library(context) # auto expand small datasets $artists = $library.children("ul").children("li") node_count = $artists.length node_count_limit = 20 expand_stuff = ($li_set) -> for li in $li_set $li = $(li) return if node_count >= node_count_limit $ul = $li.children("ul") $sub_li_set = $ul.children("li") proposed_node_count = node_count + $sub_li_set.length if proposed_node_count <= node_count_limit toggleExpansion $li # get these vars again because they might have been dynamically added # by toggleExpansion $ul = $li.children("ul") $sub_li_set = $ul.children("li") node_count = proposed_node_count expand_stuff $sub_li_set expand_stuff $artists $library.scrollTop(scroll_top) refreshSelection() # returns how many seconds we are into the track getCurrentTrackPosition = -> if mpd.status.track_start_date? and mpd.status.state is "play" (new Date() - mpd.status.track_start_date) / 1000 else mpd.status.elapsed updateSliderPos = -> return if user_is_seeking if (time = mpd.status.time)? and mpd.status.current_item? and (mpd.status.state ? "stop") isnt "stop" disabled = false elapsed = getCurrentTrackPosition() slider_pos = elapsed / time else disabled = true elapsed = time = slider_pos = 0 $track_slider .slider("option", "disabled", disabled) .slider("option", "value", slider_pos) $nowplaying_elapsed.html Util.formatTime(elapsed) $nowplaying_left.html Util.formatTime(time) renderNowPlaying = -> # set window title if (track = mpd.status.current_item?.track)? track_display = "#{track.name} - #{track.artist_name}" if track.album_name.length track_display += " - " + track.album_name document.title = "#{track_display} - #{base_title}" # Easter time! if track.name.indexOf("Groove Basin") is 0 $("html").addClass('groovebasin') else $("html").removeClass('groovebasin') if track.name.indexOf("Never Gonna Give You Up") is 0 and track.artist_name.indexOf("Rick Astley") is 0 $("html").addClass('nggyu') else $("html").removeClass('nggyu') else track_display = "&nbsp;" document.title = base_title # set song title $("#track-display").html(track_display) state = mpd.status.state ? "stop" # set correct pause/play icon toggle_icon = play: ['ui-icon-play', 'ui-icon-pause'] stop: ['ui-icon-pause', 'ui-icon-play'] pause: ['ui-icon-pause', 'ui-icon-play'] [old_class, new_class] = toggle_icon[state] $nowplaying.find(".toggle span").removeClass(old_class).addClass(new_class) # hide seeker bar if stopped $track_slider.slider "option", "disabled", state is "stop" updateSliderPos() # update volume pos unless user_is_volume_sliding enabled = (vol = mpd.status.volume)? $vol_slider.slider 'option', 'value', vol if enabled $vol_slider.slider 'option', 'disabled', not enabled render = -> hide_main_err = load_status is LoadStatus.GoodToGo $("#playlist-window").toggle(hide_main_err) $("#left-window").toggle(hide_main_err) $("#nowplaying").toggle(hide_main_err) $main_err_msg.toggle(not hide_main_err) unless hide_main_err document.title = base_title $main_err_msg_text.text(LoadStatusMsg[load_status]) return renderPlaylist() renderPlaylistButtons() renderLibrary() renderNowPlaying() renderChat() renderSettings() handleResize() toggleExpansion = ($li) -> $div = $li.find("> div") $ul = $li.find("> ul") if $div.hasClass('artist') if not $li.data('cached') $li.data 'cached', true $ul.html Handlebars.templates.albums albums: mpd.getArtistAlbums($div.find("span").text()) $ul.toggle() refreshSelection() $ul.toggle() old_class = 'ui-icon-triangle-1-se' new_class = 'ui-icon-triangle-1-e' [new_class, old_class] = [old_class, new_class] if $ul.is(":visible") $div.find("div").removeClass(old_class).addClass(new_class) return false confirmDelete = (files_list) -> list_text = files_list.slice(0, 7).join("\n ") if files_list.length > 7 list_text += "\n ..." song_text = if files_list.length is 1 then "song" else "songs" confirm """ You are about to delete #{files_list.length} #{song_text} permanently: #{list_text} """ handleDeletePressed = (shift) -> if selection.isLibrary() files_list = selectionToFiles() if not confirmDelete(files_list) then return socket.emit 'DeleteFromLibrary', JSON.stringify(files_list) else if selection.isPlaylist() if shift # delete from library files_list = (mpd.playlist.item_table[id].track.file for id of selection.ids.playlist) if not confirmDelete(files_list) then return socket.emit 'DeleteFromLibrary', JSON.stringify(files_list) # fall through and also remove the items from the playlist # remove items from playlist and select the item next in the list pos = mpd.playlist.item_table[selection.cursor].pos mpd.removeIds (id for id of selection.ids.playlist) pos = mpd.playlist.item_list.length - 1 if pos >= mpd.playlist.item_list.length selection.selectOnly 'playlist', mpd.playlist.item_list[pos].id if pos > -1 refreshSelection() toggleStreamStatus = -> return unless server_status?.stream_httpd_port? trying_to_stream = not trying_to_stream renderStreamButton() updateStreamingPlayer() return false updateStreamingPlayer = -> should_stream = trying_to_stream and mpd.status.state is "play" return if actually_streaming is should_stream if should_stream format = server_status.stream_httpd_format port = server_status?.stream_httpd_port stream_url = "#{location.protocol}//#{location.hostname}:#{port}/stream.#{format}" soundManager.destroySound('stream') sound = soundManager.createSound id: 'stream' url: stream_url onbufferchange: -> streaming_buffering = sound.isBuffering renderStreamButton() sound.play() streaming_buffering = sound.isBuffering else soundManager.destroySound('stream') streaming_buffering = false actually_streaming = should_stream renderStreamButton() togglePlayback = -> if mpd.status.state is 'play' mpd.pause() else mpd.play() setDynamicMode = (value) -> args = dynamic_mode: value socket.emit 'DynamicMode', JSON.stringify(args) toggleDynamicMode = -> setDynamicMode not server_status.dynamic_mode getRepeatStateName = -> if not mpd.status.repeat "Off" else if mpd.status.repeat and not mpd.status.single "All" else "One" nextRepeatState = -> if not mpd.status.repeat mpd.changeStatus repeat: true single: true else if mpd.status.repeat and not mpd.status.single mpd.changeStatus repeat: false single: false else mpd.changeStatus repeat: true single: false keyboard_handlers = do -> upDownHandler = (event) -> if event.keyCode is 38 # up default_index = mpd.playlist.item_list.length - 1 dir = -1 else default_index = 0 dir = 1 if event.ctrlKey if selection.isPlaylist() # re-order playlist items mpd.shiftIds (id for id of selection.ids.playlist), dir else # change selection if selection.isPlaylist() next_pos = mpd.playlist.item_table[selection.cursor].pos + dir return if next_pos < 0 or next_pos >= mpd.playlist.item_list.length selection.cursor = mpd.playlist.item_list[next_pos].id selection.clear() unless event.shiftKey selection.ids.playlist[selection.cursor] = true else if selection.isLibrary() next_pos = getLibSelPos(selection.type, selection.cursor) if dir > 0 then nextLibPos(next_pos) else prevLibPos(next_pos) return if not next_pos.artist? selection.clear() unless event.shiftKey if next_pos.track? selection.type = 'track' selection.cursor = next_pos.track.file else if next_pos.album? selection.type = 'album' selection.cursor = next_pos.album.key else selection.type = 'artist' selection.cursor = mpd.artistKey(next_pos.artist.name) selection.ids[selection.type][selection.cursor] = true else selection.selectOnly 'playlist', mpd.playlist.item_list[default_index].id refreshSelection() scrollPlaylistToSelection() if selection.isPlaylist() scrollLibraryToSelection() if selection.isLibrary() leftRightHandler = (event) -> dir = if event.keyCode is 37 then -1 else 1 if selection.isLibrary() return unless (helpers = getSelHelpers()) [ids, table, $getDiv] = helpers[selection.type] selected_item = table[selection.cursor] is_expanded_funcs = artist: isArtistExpanded album: isAlbumExpanded track: -> true is_expanded = is_expanded_funcs[selection.type](selected_item) $li = $getDiv(selection.cursor).closest("li") cursor_pos = getLibSelPos(selection.type, selection.cursor) if dir > 0 # expand and jump to child toggleExpansion $li unless is_expanded else # collapse; if already collapsed, jump to parent toggleExpansion $li if is_expanded else if event.ctrlKey if dir > 0 then mpd.next() else mpd.prev() else if event.shiftKey mpd.seek getCurrentTrackPosition() + dir * mpd.status.time * 0.10 else mpd.seek getCurrentTrackPosition() + dir * 10 handlers = 13: # enter ctrl: no alt: null shift: null handler: (event) -> if selection.isPlaylist() mpd.playId selection.cursor else if selection.isLibrary() queueLibSelection event 27: # escape ctrl: no alt: no shift: no handler: -> # if the user is dragging, abort the drag if started_drag abortDrag() return # if there's a menu, only remove that if $("#menu").get().length > 0 removeContextMenu() return selection.fullClear() refreshSelection() 32: # space ctrl: no alt: no shift: no handler: togglePlayback 37: # left ctrl: null alt: no shift: null handler: leftRightHandler 38: # up ctrl: null alt: no shift: null handler: upDownHandler 39: # right ctrl: null alt: no shift: null handler: leftRightHandler 40: # down ctrl: null alt: no shift: null handler: upDownHandler 46: # delete ctrl: no alt: no shift: null handler: (event) -> handleDeletePressed(event.shiftKey) 67: # 'c' ctrl: no alt: no shift: yes handler: -> mpd.clear() 68: # 'd' ctrl: no alt: no shift: no handler: toggleDynamicMode 72: # 'h' ctrl: no alt: no shift: yes handler: -> mpd.shuffle() 76: # 'l' ctrl: no alt: no shift: no handler: -> clickTab 'library' 82: # 'r' ctrl: no alt: no shift: no handler: nextRepeatState 83: # 's' ctrl: no alt: no shift: no handler: toggleStreamStatus 84: # 't' ctrl: no alt: no shift: no handler: -> clickTab 'chat' $("#chat-input").focus().select() 85: # 'u' ctrl: no alt: no shift: no handler: -> clickTab 'upload' $upload_by_url.focus().select() 187: # '=' or '+' ctrl: no alt: no shift: null handler: -> mpd.setVolume mpd.status.volume + 0.10 188: # ',' or '<' ctrl: no alt: no shift: null handler: -> mpd.prev() 189: # '-' or '_' ctrl: no alt: no shift: null handler: -> mpd.setVolume mpd.status.volume - 0.10 190: # '.' or '>' ctrl: no alt: no shift: null handler: -> mpd.next() 191: # '/' or '?' ctrl: no alt: no shift: null handler: (event) -> if event.shiftKey $(Handlebars.templates.shortcuts()).appendTo(document.body) $("#shortcuts").dialog modal: true title: "Keyboard Shortcuts" minWidth: 600 height: $document.height() - 40 close: -> $("#shortcuts").remove() else clickTab 'library' $("#lib-filter").focus().select() removeContextMenu = -> $("#menu").remove() isArtistExpanded = (artist) -> $li = $("#lib-artist-#{Util.toHtmlId(mpd.artistKey(artist.name))}").closest("li") return false unless $li.data('cached') return $li.find("> ul").is(":visible") isAlbumExpanded = (album) -> $li = $("#lib-album-#{Util.toHtmlId(album.key)}").closest("li") return $li.find("> ul").is(":visible") getTrackSelPos = (track) -> artist: track.album.artist album: track.album track: track getLibSelPos = (type, key) -> val = artist: null album: null track: null if key? switch type when 'track' val.track = mpd.search_results.track_table[key] val.album = val.track.album val.artist = val.album.artist when 'album' val.album = mpd.search_results.album_table[key] val.artist = val.album.artist when 'artist' val.artist = mpd.search_results.artist_table[key] else val.artist = mpd.search_results.artists[0] return val libPosToArr = (lib_pos) -> [lib_pos.artist?.pos, lib_pos.album?.pos, lib_pos.track?.pos] # modifies in place prevLibPos = (lib_pos) -> if lib_pos.track? lib_pos.track = lib_pos.track.album.tracks[lib_pos.track.pos - 1] else if lib_pos.album? lib_pos.album = lib_pos.artist.albums[lib_pos.album.pos - 1] if lib_pos.album? and isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[lib_pos.album.tracks.length - 1] else if lib_pos.artist? lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos - 1] if lib_pos.artist? and isArtistExpanded(lib_pos.artist) lib_pos.album = lib_pos.artist.albums[lib_pos.artist.albums.length - 1] if lib_pos.album? and isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[lib_pos.album.tracks.length - 1] # modifies in place nextLibPos = (lib_pos) -> if lib_pos.track? lib_pos.track = lib_pos.track.album.tracks[lib_pos.track.pos + 1] if not lib_pos.track? lib_pos.album = lib_pos.artist.albums[lib_pos.album.pos + 1] if not lib_pos.album? lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] else if lib_pos.album? if isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[0] else lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] lib_pos.album = null else if lib_pos.artist? if isArtistExpanded(lib_pos.artist) lib_pos.album = lib_pos.artist.albums[0] else lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] selectLibraryPosition = (lib_pos) -> if lib_pos.track? selection.ids.track[lib_pos.track.file] = true else if lib_pos.album? selection.ids.album[lib_pos.album.key] = true else if lib_pos.artist? selection.ids.artist[mpd.artistKey(lib_pos.artist.name)] = true queueFilesPos = -> pos = mpd.playlist.item_list.length return pos unless server_status? for item, i in mpd.playlist.item_list return i if server_status.random_ids[item.id]? queueLibSelection = (event) -> files = selectionToFiles(event.altKey) if event.shiftKey mpd.queueFilesNext files else mpd.queueFiles files, queueFilesPos() return false settings_ui = auth: show_edit: false password: "" sendAuth = -> pass = localStorage.auth_password return unless pass? mpd.authenticate pass, (err) -> if err delete localStorage.auth_password renderSettings() socket.emit 'Password', pass settingsAuthSave = -> settings_ui.auth.show_edit = false $text_box = $("#auth-password") localStorage.auth_password = $text_box.val() # try to auth renderSettings() sendAuth() settingsAuthCancel = -> settings_ui.auth.show_edit = false renderSettings() performDrag = (event, callbacks) -> abortDrag() start_drag_x = event.pageX start_drag_y = event.pageY abortDrag = -> $document .off('mousemove', onDragMove) .off('mouseup', onDragEnd) if started_drag $playlist_items.find(".pl-item").removeClass('border-top').removeClass('border-bottom') started_drag = false abortDrag = -> onDragMove = (event) -> if not started_drag dist = Math.pow(event.pageX - start_drag_x, 2) + Math.pow(event.pageY - start_drag_y, 2) started_drag = true if dist > 64 return unless started_drag result = getDragPosition(event.pageX, event.pageY) $playlist_items.find(".pl-item").removeClass('border-top').removeClass('border-bottom') $("#playlist-track-#{result.track_id}").addClass "border-#{result.direction}" onDragEnd = (event) -> return false unless event.button is 0 if started_drag callbacks.complete getDragPosition(event.pageX, event.pageY), event else callbacks.cancel() abortDrag() $document .on('mousemove', onDragMove) .on('mouseup', onDragEnd) onDragMove event setUpUi = -> $document.on 'mouseover', '.hoverable', (event) -> $(this).addClass "ui-state-hover" $document.on 'mouseout', '.hoverable', (event) -> $(this).removeClass "ui-state-hover" $(".jquery-button").button() $pl_window = $("#playlist-window") $pl_window.on 'click', 'button.clear', -> mpd.clear() $pl_window.on 'click', 'button.shuffle', -> mpd.shuffle() $pl_btn_repeat.on 'click', -> nextRepeatState() $dynamic_mode.on 'click', -> value = $(this).prop("checked") setDynamicMode(value) return false $playlist_items.on 'dblclick', '.pl-item', (event) -> track_id = $(this).data('id') mpd.playId track_id $playlist_items.on 'contextmenu', (event) -> return event.altKey $playlist_items.on 'mousedown', '.pl-item', (event) -> return true if started_drag # if any text box has focus, unfocus it $(document.activeElement).blur() if event.button is 0 event.preventDefault() # selecting / unselecting removeContextMenu() track_id = $(this).data('id') skip_drag = false if not selection.isPlaylist() selection.selectOnly 'playlist', track_id else if event.ctrlKey or event.shiftKey skip_drag = true if event.shiftKey and not event.ctrlKey selection.clear() if event.shiftKey old_pos = if selection.cursor? then mpd.playlist.item_table[selection.cursor].pos else 0 new_pos = mpd.playlist.item_table[track_id].pos for i in [old_pos..new_pos] selection.ids.playlist[mpd.playlist.item_list[i].id] = true else if event.ctrlKey if selection.ids.playlist[track_id]? delete selection.ids.playlist[track_id] else selection.ids.playlist[track_id] = true selection.cursor = track_id else if not selection.ids.playlist[track_id]? selection.selectOnly 'playlist', track_id refreshSelection() # dragging if not skip_drag performDrag event, complete: (result, event) -> delta = top: 0 bottom: 1 new_pos = mpd.playlist.item_table[result.track_id].pos + delta[result.direction] mpd.moveIds (id for id of selection.ids.playlist), new_pos cancel: -> # we didn't end up dragging, select the item selection.selectOnly 'playlist', track_id refreshSelection() else if event.button is 2 return if event.altKey event.preventDefault() # context menu removeContextMenu() track_id = parseInt($(this).data('id')) if not selection.isPlaylist() or not selection.ids.playlist[track_id]? selection.selectOnly 'playlist', track_id refreshSelection() # adds a new context menu to the document context = item: mpd.playlist.item_table[track_id] status: server_status permissions: permissions $(Handlebars.templates.playlist_menu(context)) .appendTo(document.body) $menu = $("#menu") # get the newly created one $menu.offset left: event.pageX+1 top: event.pageY+1 # don't close menu when you click on the area next to a button $menu.on 'mousedown', -> false $menu.on 'click', '.remove', -> handleDeletePressed(false) removeContextMenu() return false $menu.on 'click', '.download', -> removeContextMenu() return true $menu.on 'click', '.delete', -> handleDeletePressed(true) removeContextMenu() return false # don't remove selection in playlist click $playlist_items.on 'mousedown', -> false # delete context menu $document.on 'mousedown', -> removeContextMenu() selection.type = null refreshSelection() $document.on 'keydown', (event) -> if (handler = keyboard_handlers[event.keyCode])? and (not handler.ctrl? or handler.ctrl is event.ctrlKey) and (not handler.alt? or handler.alt is event.altKey) and (not handler.shift? or handler.shift is event.shiftKey) handler.handler event return false return true $library.on 'mousedown', 'div.expandable > div.ui-icon', (event) -> toggleExpansion $(this).closest("li") return false # suppress double click on the icon $library.on 'dblclick', 'div.expandable > div.ui-icon', -> false $library.on 'dblclick', 'div.artist, div.album, div.track', queueLibSelection $library.on 'contextmenu', (event) -> return event.altKey libraryMouseDown = (event, sel_name, key) -> # if any text box has focus, unfocus it $(document.activeElement).blur() if event.button is 0 event.preventDefault() removeContextMenu() skip_drag = false if not selection.isLibrary() selection.selectOnly sel_name, key else if event.ctrlKey or event.shiftKey skip_drag = true if event.shiftKey and not event.ctrlKey selection.clear() if event.shiftKey old_pos = getLibSelPos(selection.type, selection.cursor) new_pos = getLibSelPos(sel_name, key) # swap if positions are out of order new_arr = libPosToArr(new_pos) old_arr = libPosToArr(old_pos) [old_pos, new_pos] = [new_pos, old_pos] if Util.compareArrays(old_arr, new_arr) > 0 libraryPositionEqual = (old_pos, new_pos) -> old_arr = libPosToArr(old_pos) new_arr = libPosToArr(new_pos) return Util.compareArrays(old_arr, new_arr) is 0 while old_pos.artist? selectLibraryPosition old_pos break if libraryPositionEqual(old_pos, new_pos) nextLibPos old_pos else if event.ctrlKey if selection.ids[sel_name][key]? delete selection.ids[sel_name][key] else selection.ids[sel_name][key] = true selection.cursor = key selection.type = sel_name else if not selection.ids[sel_name][key]? selection.selectOnly sel_name, key refreshSelection() # dragging if not skip_drag performDrag event, complete: (result, event) -> delta = top: 0 bottom: 1 new_pos = mpd.playlist.item_table[result.track_id].pos + delta[result.direction] files = selectionToFiles(event.altKey) mpd.queueFiles files, new_pos cancel: -> # we didn't end up dragging, select the item selection.selectOnly sel_name, key refreshSelection() else if event.button = 2 return if event.altKey event.preventDefault() removeContextMenu() if not selection.isLibrary() or not selection.ids[sel_name][key]? selection.selectOnly sel_name, key refreshSelection() # adds a new context menu to the document context = status: server_status permissions: permissions if sel_name is 'track' context.track = mpd.search_results.track_table[key] $(Handlebars.templates.library_menu(context)).appendTo(document.body) $menu = $("#menu") # get the newly created one $menu.offset left: event.pageX+1 # +1 so we don't immediately close the menu by clicking it top: event.pageY+1 # don't close menu when you click on the area next to a button $menu.on 'mousedown', -> false $menu.on 'click', '.queue', -> mpd.queueFiles selectionToFiles() removeContextMenu() return false $menu.on 'click', '.queue-next', -> mpd.queueFilesNext selectionToFiles() removeContextMenu() return false $menu.on 'click', '.queue-random', -> mpd.queueFiles selectionToFiles(true) removeContextMenu() return false $menu.on 'click', '.queue-next-random', -> mpd.queueFilesNext selectionToFiles(true) removeContextMenu() return false $menu.on 'click', '.download', -> removeContextMenu() return true $menu.on 'click', '.delete', -> handleDeletePressed(true) removeContextMenu() return false $library.on 'mousedown', '.artist', (event) -> artist_key = mpd.artistKey($(this).find("span").text()) libraryMouseDown event, 'artist', artist_key $library.on 'mousedown', '.album', (event) -> libraryMouseDown event, 'album', $(this).data('key') $library.on 'mousedown', '.track', (event) -> libraryMouseDown event, 'track', $(this).data('file') $library.on 'mousedown', -> false $lib_filter = $("#lib-filter") $lib_filter.on 'keydown', (event) -> event.stopPropagation() switch event.keyCode when 27 # if the box is blank, remove focus if $(event.target).val().length is 0 $(event.target).blur() else # defer the setting of the text box until after the event loop to # work around a firefox bug Util.wait 0, -> $(event.target).val("") mpd.search "" return false when 13 # queue all the search results files = [] for artist in mpd.search_results.artists for album in artist.albums for track in album.tracks files.push track.file if event.altKey Util.shuffle(files) if files.length > 2000 return false unless confirm("You are about to queue #{files.length} songs.") if event.shiftKey mpd.queueFilesNext files else mpd.queueFiles files, queueFilesPos() return false when 40 # down # select the first item in the library selection.selectOnly 'artist', mpd.artistKey(mpd.search_results.artists[0].name) refreshSelection() $lib_filter.blur() return false when 38 # up # select the last item in the library selection.selectOnly 'artist', mpd.artistKey(mpd.search_results.artists[mpd.search_results.artists.length - 1].name) refreshSelection() $lib_filter.blur() return false $lib_filter.on 'keyup', (event) -> mpd.search $(event.target).val() $chat_name_input = $("#chat-name-input") $chat_user_id_span.on 'click', (event) -> $chat_input.attr "disabled", "disabled" chat_name_input_visible = true $chat_name_input.show().val("").focus().select() renderChat() $chat_name_input.on 'keydown', (event) -> event.stopPropagation() if event.keyCode is 27 # cancel done = true else if event.keyCode is 13 # accept done = true setUserName $(event.target).val() if done chat_name_input_visible = false $chat_name_input.hide() $chat_input.removeAttr("disabled").focus().select() renderChat() return false $chat_input = $("#chat-input") $chat_input.on 'keydown', (event) -> event.stopPropagation() if event.keyCode is 27 $(event.target).blur() return false else if event.keyCode is 13 message = $.trim($(event.target).val()) Util.wait 0, -> $(event.target).val("") return false if message is "" unless haveUserName() new_user_name = message NICK = "/nick " if message.substr(0, NICK.length) is NICK new_user_name = message.substr(NICK.length) if new_user_name? setUserName new_user_name return false socket.emit 'Chat', message return false actions = 'toggle': togglePlayback 'prev': -> mpd.prev() 'next': -> mpd.next() 'stop': -> mpd.stop() $nowplaying = $("#nowplaying") for cls, action of actions do (cls, action) -> $nowplaying.on 'mousedown', "li.#{cls}", (event) -> action() return false $track_slider.slider step: 0.0001 min: 0 max: 1 change: (event, ui) -> return if not event.originalEvent? mpd.seek ui.value * mpd.status.time slide: (event, ui) -> $nowplaying_elapsed.html Util.formatTime(ui.value * mpd.status.time) start: (event, ui) -> user_is_seeking = true stop: (event, ui) -> user_is_seeking = false setVol = (event, ui) -> return if not event.originalEvent? mpd.setVolume ui.value $vol_slider.slider step: 0.01 min: 0 max: 1 change: setVol start: (event, ui) -> user_is_volume_sliding = true stop: (event, ui) -> user_is_volume_sliding = false # move the slider along the path Util.schedule 100, updateSliderPos $stream_btn.button icons: primary: "ui-icon-signal-diag" $stream_btn.on 'click', toggleStreamStatus $lib_tabs.on 'mouseover', 'li', (event) -> $(this).addClass 'ui-state-hover' $lib_tabs.on 'mouseout', 'li', (event) -> $(this).removeClass 'ui-state-hover' tabs = [ 'library' 'upload' 'chat' 'settings' ] unselectTabs = -> $lib_tabs.find('li').removeClass 'ui-state-active' for tab in tabs $("##{tab}-tab").hide() clickTab = (name) -> return if name is 'upload' and not server_status?.upload_enabled unselectTabs() $lib_tabs.find("li.#{name}-tab").addClass 'ui-state-active' $("##{name}-tab").show() handleResize() renderChat() if name is 'chat' for tab in tabs do (tab) -> $lib_tabs.on 'click', "li.#{tab}-tab", (event) -> clickTab tab uploader = new qq.FileUploader element: document.getElementById("upload-widget") action: '/upload' encoding: 'multipart' $settings.on 'click', '.signout', (event) -> delete localStorage?.lastfm_username delete localStorage?.lastfm_session_key delete localStorage?.lastfm_scrobbling_on renderSettings() return false $settings.on 'click', '#toggle-scrobble', (event) -> value = $(this).prop("checked") if value msg = 'LastfmScrobblersAdd' localStorage?.lastfm_scrobbling_on = true else msg = 'LastfmScrobblersRemove' delete localStorage?.lastfm_scrobbling_on params = username: localStorage?.lastfm_username session_key: localStorage?.lastfm_session_key socket.emit msg, JSON.stringify(params) renderSettings() return false $settings.on 'click', '.auth-edit', (event) -> settings_ui.auth.show_edit = true renderSettings() $text_box = $("#auth-password") $text_box.focus().val(localStorage.auth_password ? "").select() $settings.on 'click', '.auth-clear', (event) -> delete localStorage.auth_password settings_ui.auth.password = "" renderSettings() $settings.on 'click', '.auth-save', (event) -> settingsAuthSave() $settings.on 'click', '.auth-cancel', (event) -> settingsAuthCancel() $settings.on 'keydown', '#auth-password', (event) -> $text_box = $(this) event.stopPropagation() settings_ui.auth.password = $text_box.val() if event.which is 27 settingsAuthCancel() else if event.which is 13 settingsAuthSave() $settings.on 'keyup', '#auth-password', (event) -> settings_ui.auth.password = $(this).val() $upload_by_url.on 'keydown', (event) -> event.stopPropagation() if event.which is 27 $upload_by_url.val("").blur() else if event.which is 13 url = $upload_by_url.val() $upload_by_url.val("").blur() socket.emit 'ImportTrackUrl', url # end setUpUi initHandlebars = -> Handlebars.registerHelper 'time', Util.formatTime Handlebars.registerHelper 'artistid', (s) -> "lib-artist-#{Util.toHtmlId(mpd.artistKey(s))}" Handlebars.registerHelper 'albumid', (s) -> "lib-album-#{Util.toHtmlId(s)}" Handlebars.registerHelper 'trackid', (s) -> "lib-track-#{Util.toHtmlId(s)}" handleResize = -> $nowplaying = $("#nowplaying") $left_window = $("#left-window") $pl_window = $("#playlist-window") # go really small to make the window as small as possible $nowplaying.width MARGIN $pl_window.height MARGIN $left_window.height MARGIN # then fit back up to the window $nowplaying.width $document.width() - MARGIN * 2 second_layer_top = $nowplaying.offset().top + $nowplaying.height() + MARGIN $left_window.offset left: MARGIN top: second_layer_top $pl_window.offset left: $left_window.offset().left + $left_window.width() + MARGIN top: second_layer_top $pl_window.width $(window).width() - $pl_window.offset().left - MARGIN $left_window.height $(window).height() - $left_window.offset().top $pl_window.height $left_window.height() - MARGIN # make the inside containers fit $lib_header = $("#library-tab .window-header") $library.height $left_window.height() - $lib_header.position().top - $lib_header.height() - MARGIN tab_contents_height = $left_window.height() - $lib_tabs.height() - MARGIN $("#upload").height tab_contents_height resizeChat() $pl_header = $pl_window.find("#playlist .header") $playlist_items.height $pl_window.height() - $pl_header.position().top - $pl_header.height() resizeChat = -> height_overshoot = $("#chat-tab").height() - $("#upload").height() $chat_list.height $chat_list.height() - height_overshoot initStreaming = -> soundManager.setup url: "/vendor/soundmanager2/" flashVersion: 9 debugMode: false window.WEB_SOCKET_SWF_LOCATION = "/vendor/socket.io/WebSocketMain.swf" $document.ready -> if localStorage?.my_user_ids? my_user_ids = JSON.parse localStorage.my_user_ids socket = io.connect() # special case when we get the callback from Last.fm. # tell the server the token and save the session in localStorage. # then refresh but remove the "?token=*" from the URL. if (token = Util.parseQuery(location.search.substring(1))?.token)? socket.emit 'LastfmGetSession', token refreshPage = -> location.href = "#{location.protocol}//#{location.host}/" socket.on 'LastfmGetSessionSuccess', (data) -> params = JSON.parse(data) localStorage?.lastfm_username = params.session.name localStorage?.lastfm_session_key = params.session.key delete localStorage?.lastfm_scrobbling_on refreshPage() socket.on 'LastfmGetSessionError', (data) -> params = JSON.parse(data) alert "Error authenticating: #{params.message}" refreshPage() return socket.on 'connect', -> load_status = LoadStatus.NoMpd render() socket.on 'Identify', (data) -> my_user_id = data.toString() my_user_ids[my_user_id] = 1 storeMyUserIds() if (user_name = localStorage?.user_name)? setUserName user_name socket.on 'Permissions', (data) -> permissions = JSON.parse data.toString() renderSettings() socket.on 'Status', (data) -> server_status = JSON.parse data.toString() storeMyUserIds() renderPlaylistButtons() renderChat() labelPlaylistItems() renderSettings() window._debug_server_status = server_status mpd = new window.SocketMpd socket mpd.on 'libraryupdate', renderLibrary mpd.on 'playlistupdate', renderPlaylist mpd.on 'statusupdate', -> renderNowPlaying() renderPlaylistButtons() labelPlaylistItems() updateStreamingPlayer() mpd.on 'chat', renderChat mpd.on 'connect', -> sendAuth() load_status = LoadStatus.GoodToGo render() socket.on 'disconnect', -> load_status = LoadStatus.NoServer render() socket.on 'MpdDisconnect', -> load_status = LoadStatus.NoMpd render() setUpUi() initHandlebars() initStreaming() render() # do this last so that everything becomes the correct size. $(window).resize handleResize window._debug_mpd = mpd
217090
#depend "util" #depend "socketmpd" #depend "jquery-1.7.1.min" bare #depend "jquery-ui-1.8.17.custom.min" bare #depend "soundmanager2/soundmanager2-nodebug-jsmin" bare #depend "fileuploader/fileuploader" bare #depend "socket.io/socket.io.min" bare selection = ids: playlist: {} # key is id, value is some dummy value artist: {} album: {} track: {} cursor: null # the last touched id type: null # 'playlist', 'artist', 'album', or 'track' isLibrary: -> return false if not this.type? return this.type isnt 'playlist' isPlaylist: -> return false if not this.type? return this.type is 'playlist' clear: -> this.ids.artist = {} this.ids.album = {} this.ids.track = {} this.ids.playlist = {} fullClear: -> this.clear() this.type = null this.cursor = null selectOnly: (sel_name, key) -> this.clear() this.type = sel_name this.ids[sel_name][key] = true this.cursor = key server_status = null permissions = {} socket = null mpd = null base_title = document.title user_is_seeking = false user_is_volume_sliding = false started_drag = false abortDrag = -> clickTab = null trying_to_stream = false actually_streaming = false streaming_buffering = false my_user_id = null my_user_ids = {} chat_name_input_visible = false MARGIN = 10 LoadStatus = Init: 0 NoMpd: 1 NoServer: 2 GoodToGo: 3 LoadStatusMsg = [ 'Loading...' 'mpd is not running on the server.' 'Server is down.' ] load_status = LoadStatus.Init # cache jQuery objects $document = $(document) $playlist_items = $("#playlist-items") $dynamic_mode = $("#dynamic-mode") $pl_btn_repeat = $("#pl-btn-repeat") $stream_btn = $("#stream-btn") $lib_tabs = $("#lib-tabs") $upload_tab = $("#lib-tabs .upload-tab") $chat_tab = $("#lib-tabs .chat-tab") $library = $("#library") $track_slider = $("#track-slider") $nowplaying = $("#nowplaying") $nowplaying_elapsed = $nowplaying.find(".elapsed") $nowplaying_left = $nowplaying.find(".left") $vol_slider = $("#vol-slider") $chat_user_list = $("#chat-user-list") $chat_list = $("#chat-list") $chat_user_id_span = $("#user-id") $settings = $("#settings") $upload_by_url = $("#upload-by-url") $main_err_msg = $("#main-err-msg") $main_err_msg_text = $("#main-err-msg-text") haveUserName = -> server_status?.user_names[my_user_id]? getUserName = -> userIdToUserName my_user_id userIdToUserName = (user_id) -> return user_id unless server_status? user_name = server_status.user_names[user_id] return user_name ? user_id storeMyUserIds = -> # scrub stale ids. TODO: this is broken. #if server_status? # for user_id of my_user_ids # delete my_user_ids[user_id] unless server_status.user_names[user_id]? localStorage?.my_user_ids = JSON.stringify my_user_ids setUserName = (new_name) -> new_name = $.trim new_name localStorage?.user_name = new_name socket.emit 'SetUserName', new_name scrollLibraryToSelection = -> return unless (helpers = getSelHelpers())? delete helpers.playlist scrollThingToSelection $library, helpers scrollPlaylistToSelection = -> return unless (helpers = getSelHelpers())? delete helpers.track delete helpers.artist delete helpers.album scrollThingToSelection $playlist_items, helpers scrollThingToSelection = ($scroll_area, helpers) -> top_pos = null bottom_pos = null for sel_name, [ids, table, $getDiv] of helpers for id of ids item_top = ($div = $getDiv(id)).offset().top item_bottom = item_top + $div.height() if not top_pos? or item_top < top_pos top_pos = item_top if not bottom_pos? or item_bottom > bottom_pos bottom_pos = item_bottom if top_pos? scroll_area_top = $scroll_area.offset().top selection_top = top_pos - scroll_area_top selection_bottom = bottom_pos - scroll_area_top - $scroll_area.height() scroll_amt = $scroll_area.scrollTop() if selection_top < 0 $scroll_area.scrollTop scroll_amt + selection_top else if selection_bottom > 0 $scroll_area.scrollTop scroll_amt + selection_bottom selectionToFiles = (random=false) -> # render selection into a single object by file to remove duplicates # works for library only track_set = {} selRenderArtist = (artist) -> selRenderAlbum album for album in artist.albums selRenderAlbum = (album) -> selRenderTrack track for track in album.tracks selRenderTrack = (track) -> track_set[track.file] = libPosToArr(getTrackSelPos(track)) selRenderArtist(mpd.search_results.artist_table[key]) for key of selection.ids.artist selRenderAlbum(mpd.search_results.album_table[key]) for key of selection.ids.album selRenderTrack(mpd.search_results.track_table[file]) for file of selection.ids.track if random files = (file for file of track_set) Util.shuffle files return files else track_arr = ({file: file, pos: pos} for file, pos of track_set) track_arr.sort (a, b) -> Util.compareArrays(a.pos, b.pos) return (track.file for track in track_arr) getDragPosition = (x, y) -> # loop over the playlist items and find where it fits best = track_id: null distance: null direction: null for item in $playlist_items.find(".pl-item").get() $item = $(item) pos = $item.offset() height = $item.height() track_id = parseInt($item.data('id')) # try the top of this element distance = Math.abs(pos.top - y) if not best.distance? or distance < best.distance best.distance = distance best.direction = "top" best.track_id = track_id # try the bottom distance = Math.abs(pos.top + height - y) if distance < best.distance best.distance = distance best.direction = "bottom" best.track_id = track_id return best renderSettings = -> return unless (api_key = server_status?.lastfm_api_key)? context = lastfm: auth_url: "http://www.last.fm/api/auth/?api_key=#{escape(api_key)}&cb=#{location.protocol}//#{location.host}/" username: localStorage.lastfm_username session_key: localStorage.lastfm_session_key scrobbling_on: localStorage.lastfm_scrobbling_on? auth: password: <PASSWORD> show_edit: not localStorage.auth_password? or settings_ui.auth.show_edit permissions: permissions $settings.html Handlebars.templates.settings(context) $settings.find(".signout").button() $settings.find("#toggle-scrobble").button() $settings.find(".auth-cancel").button() $settings.find(".auth-save").button() $settings.find(".auth-edit").button() $settings.find(".auth-clear").button() $settings.find("#auth-password").val(settings_ui.auth.password) scrollChatWindowToBottom = -> # for some reason, Infinity goes to the top :/ $chat_list.scrollTop 1000000 renderChat = -> chat_status_text = "" if (users = server_status?.users)? chat_status_text = " (#{users.length})" if users.length > 1 user_objects = ({ "class": if user_id is my_user_id then "chat-user-self" else "chat-user" user_name: userIdToUserName user_id } for user_id in users) # write everyone's name in the chat objects (too bad handlebars can't do this in the template) for chat_object in server_status.chats chat_object["class"] = if my_user_ids[chat_object.user_id]? then "chat-user-self" else "chat-user" chat_object.user_name = userIdToUserName chat_object.user_id $chat_user_list.html Handlebars.templates.chat_user_list users: user_objects $chat_list.html Handlebars.templates.chat_list chats: server_status.chats scrollChatWindowToBottom() $chat_user_id_span.text if chat_name_input_visible then "" else getUserName() + ": " $chat_tab.find("span").text("Chat#{chat_status_text}") resizeChat() renderStreamButton = -> label = if trying_to_stream if actually_streaming if streaming_buffering "Stream: Buffering" else "Stream: On" else "Stream: Paused" else "Stream: Off" # disable stream button if we don't have it set up $stream_btn .button("option", "disabled", not server_status?.stream_httpd_port?) .button("option", "label", label) .prop("checked", trying_to_stream) .button("refresh") renderPlaylistButtons = -> # set the state of dynamic mode button $dynamic_mode .prop("checked", if server_status?.dynamic_mode then true else false) .button("option", "disabled", not server_status?.dynamic_mode_enabled) .button("refresh") repeat_state = getRepeatStateName() $pl_btn_repeat .button("option", "label", "Repeat: #{repeat_state}") .prop("checked", repeat_state isnt 'Off') .button("refresh") renderStreamButton() # show/hide upload $upload_tab.removeClass("ui-state-disabled") $upload_tab.addClass("ui-state-disabled") if not server_status?.upload_enabled renderPlaylist = -> context = playlist: mpd.playlist.item_list server_status: server_status scroll_top = $playlist_items.scrollTop() $playlist_items.html Handlebars.templates.playlist(context) refreshSelection() labelPlaylistItems() $playlist_items.scrollTop(scroll_top) labelPlaylistItems = -> cur_item = mpd.status.current_item # label the old ones $playlist_items.find(".pl-item").removeClass('current').removeClass('old') if cur_item? and server_status?.dynamic_mode for pos in [0...cur_item.pos] id = mpd.playlist.item_list[pos].id $("#playlist-track-#{id}").addClass('old') # label the random ones if server_status?.random_ids? for item in mpd.playlist.item_list if server_status.random_ids[item.id] $("#playlist-track-#{item.id}").addClass('random') # label the current one $("#playlist-track-#{cur_item.id}").addClass('current') if cur_item? getSelHelpers = -> return null unless mpd?.playlist?.item_table? return null unless mpd?.search_results?.artist_table? return {} = playlist: [selection.ids.playlist, mpd.playlist.item_table, (id) -> $("#playlist-track-#{id}")] artist: [selection.ids.artist, mpd.search_results.artist_table, (id) -> $("#lib-artist-#{Util.toHtmlId(id)}")] album: [selection.ids.album, mpd.search_results.album_table, (id) -> $("#lib-album-#{Util.toHtmlId(id)}")] track: [selection.ids.track, mpd.search_results.track_table, (id) -> $("#lib-track-#{Util.toHtmlId(id)}")] refreshSelection = -> return unless (helpers = getSelHelpers())? # clear all selection $playlist_items.find(".pl-item").removeClass('selected').removeClass('cursor') $library.find(".artist").removeClass('selected').removeClass('cursor') $library.find(".album").removeClass('selected').removeClass('cursor') $library.find(".track").removeClass('selected').removeClass('cursor') return unless selection.type? for sel_name, [ids, table, $getDiv] of helpers # if any selected artists are not in mpd.search_results, unselect them delete ids[id] for id in (id for id of ids when not table[id]?) # highlight selected rows $getDiv(id).addClass 'selected' for id of ids if selection.cursor? and sel_name is selection.type $getDiv(selection.cursor).addClass('cursor') renderLibrary = -> context = artists: mpd.search_results.artists empty_library_message: if mpd.have_file_list_cache then "No Results" else "loading..." scroll_top = $library.scrollTop() $library.html Handlebars.templates.library(context) # auto expand small datasets $artists = $library.children("ul").children("li") node_count = $artists.length node_count_limit = 20 expand_stuff = ($li_set) -> for li in $li_set $li = $(li) return if node_count >= node_count_limit $ul = $li.children("ul") $sub_li_set = $ul.children("li") proposed_node_count = node_count + $sub_li_set.length if proposed_node_count <= node_count_limit toggleExpansion $li # get these vars again because they might have been dynamically added # by toggleExpansion $ul = $li.children("ul") $sub_li_set = $ul.children("li") node_count = proposed_node_count expand_stuff $sub_li_set expand_stuff $artists $library.scrollTop(scroll_top) refreshSelection() # returns how many seconds we are into the track getCurrentTrackPosition = -> if mpd.status.track_start_date? and mpd.status.state is "play" (new Date() - mpd.status.track_start_date) / 1000 else mpd.status.elapsed updateSliderPos = -> return if user_is_seeking if (time = mpd.status.time)? and mpd.status.current_item? and (mpd.status.state ? "stop") isnt "stop" disabled = false elapsed = getCurrentTrackPosition() slider_pos = elapsed / time else disabled = true elapsed = time = slider_pos = 0 $track_slider .slider("option", "disabled", disabled) .slider("option", "value", slider_pos) $nowplaying_elapsed.html Util.formatTime(elapsed) $nowplaying_left.html Util.formatTime(time) renderNowPlaying = -> # set window title if (track = mpd.status.current_item?.track)? track_display = "#{track.name} - #{track.artist_name}" if track.album_name.length track_display += " - " + track.album_name document.title = "#{track_display} - #{base_title}" # Easter time! if track.name.indexOf("<NAME>") is 0 $("html").addClass('groovebasin') else $("html").removeClass('groovebasin') if track.name.indexOf("Never Gonna Give You Up") is 0 and track.artist_name.indexOf("<NAME>") is 0 $("html").addClass('nggyu') else $("html").removeClass('nggyu') else track_display = "&nbsp;" document.title = base_title # set song title $("#track-display").html(track_display) state = mpd.status.state ? "stop" # set correct pause/play icon toggle_icon = play: ['ui-icon-play', 'ui-icon-pause'] stop: ['ui-icon-pause', 'ui-icon-play'] pause: ['ui-icon-pause', 'ui-icon-play'] [old_class, new_class] = toggle_icon[state] $nowplaying.find(".toggle span").removeClass(old_class).addClass(new_class) # hide seeker bar if stopped $track_slider.slider "option", "disabled", state is "stop" updateSliderPos() # update volume pos unless user_is_volume_sliding enabled = (vol = mpd.status.volume)? $vol_slider.slider 'option', 'value', vol if enabled $vol_slider.slider 'option', 'disabled', not enabled render = -> hide_main_err = load_status is LoadStatus.GoodToGo $("#playlist-window").toggle(hide_main_err) $("#left-window").toggle(hide_main_err) $("#nowplaying").toggle(hide_main_err) $main_err_msg.toggle(not hide_main_err) unless hide_main_err document.title = base_title $main_err_msg_text.text(LoadStatusMsg[load_status]) return renderPlaylist() renderPlaylistButtons() renderLibrary() renderNowPlaying() renderChat() renderSettings() handleResize() toggleExpansion = ($li) -> $div = $li.find("> div") $ul = $li.find("> ul") if $div.hasClass('artist') if not $li.data('cached') $li.data 'cached', true $ul.html Handlebars.templates.albums albums: mpd.getArtistAlbums($div.find("span").text()) $ul.toggle() refreshSelection() $ul.toggle() old_class = 'ui-icon-triangle-1-se' new_class = 'ui-icon-triangle-1-e' [new_class, old_class] = [old_class, new_class] if $ul.is(":visible") $div.find("div").removeClass(old_class).addClass(new_class) return false confirmDelete = (files_list) -> list_text = files_list.slice(0, 7).join("\n ") if files_list.length > 7 list_text += "\n ..." song_text = if files_list.length is 1 then "song" else "songs" confirm """ You are about to delete #{files_list.length} #{song_text} permanently: #{list_text} """ handleDeletePressed = (shift) -> if selection.isLibrary() files_list = selectionToFiles() if not confirmDelete(files_list) then return socket.emit 'DeleteFromLibrary', JSON.stringify(files_list) else if selection.isPlaylist() if shift # delete from library files_list = (mpd.playlist.item_table[id].track.file for id of selection.ids.playlist) if not confirmDelete(files_list) then return socket.emit 'DeleteFromLibrary', JSON.stringify(files_list) # fall through and also remove the items from the playlist # remove items from playlist and select the item next in the list pos = mpd.playlist.item_table[selection.cursor].pos mpd.removeIds (id for id of selection.ids.playlist) pos = mpd.playlist.item_list.length - 1 if pos >= mpd.playlist.item_list.length selection.selectOnly 'playlist', mpd.playlist.item_list[pos].id if pos > -1 refreshSelection() toggleStreamStatus = -> return unless server_status?.stream_httpd_port? trying_to_stream = not trying_to_stream renderStreamButton() updateStreamingPlayer() return false updateStreamingPlayer = -> should_stream = trying_to_stream and mpd.status.state is "play" return if actually_streaming is should_stream if should_stream format = server_status.stream_httpd_format port = server_status?.stream_httpd_port stream_url = "#{location.protocol}//#{location.hostname}:#{port}/stream.#{format}" soundManager.destroySound('stream') sound = soundManager.createSound id: 'stream' url: stream_url onbufferchange: -> streaming_buffering = sound.isBuffering renderStreamButton() sound.play() streaming_buffering = sound.isBuffering else soundManager.destroySound('stream') streaming_buffering = false actually_streaming = should_stream renderStreamButton() togglePlayback = -> if mpd.status.state is 'play' mpd.pause() else mpd.play() setDynamicMode = (value) -> args = dynamic_mode: value socket.emit 'DynamicMode', JSON.stringify(args) toggleDynamicMode = -> setDynamicMode not server_status.dynamic_mode getRepeatStateName = -> if not mpd.status.repeat "Off" else if mpd.status.repeat and not mpd.status.single "All" else "One" nextRepeatState = -> if not mpd.status.repeat mpd.changeStatus repeat: true single: true else if mpd.status.repeat and not mpd.status.single mpd.changeStatus repeat: false single: false else mpd.changeStatus repeat: true single: false keyboard_handlers = do -> upDownHandler = (event) -> if event.keyCode is 38 # up default_index = mpd.playlist.item_list.length - 1 dir = -1 else default_index = 0 dir = 1 if event.ctrlKey if selection.isPlaylist() # re-order playlist items mpd.shiftIds (id for id of selection.ids.playlist), dir else # change selection if selection.isPlaylist() next_pos = mpd.playlist.item_table[selection.cursor].pos + dir return if next_pos < 0 or next_pos >= mpd.playlist.item_list.length selection.cursor = mpd.playlist.item_list[next_pos].id selection.clear() unless event.shiftKey selection.ids.playlist[selection.cursor] = true else if selection.isLibrary() next_pos = getLibSelPos(selection.type, selection.cursor) if dir > 0 then nextLibPos(next_pos) else prevLibPos(next_pos) return if not next_pos.artist? selection.clear() unless event.shiftKey if next_pos.track? selection.type = 'track' selection.cursor = next_pos.track.file else if next_pos.album? selection.type = 'album' selection.cursor = next_pos.album.key else selection.type = 'artist' selection.cursor = mpd.artistKey(next_pos.artist.name) selection.ids[selection.type][selection.cursor] = true else selection.selectOnly 'playlist', mpd.playlist.item_list[default_index].id refreshSelection() scrollPlaylistToSelection() if selection.isPlaylist() scrollLibraryToSelection() if selection.isLibrary() leftRightHandler = (event) -> dir = if event.keyCode is 37 then -1 else 1 if selection.isLibrary() return unless (helpers = getSelHelpers()) [ids, table, $getDiv] = helpers[selection.type] selected_item = table[selection.cursor] is_expanded_funcs = artist: isArtistExpanded album: isAlbumExpanded track: -> true is_expanded = is_expanded_funcs[selection.type](selected_item) $li = $getDiv(selection.cursor).closest("li") cursor_pos = getLibSelPos(selection.type, selection.cursor) if dir > 0 # expand and jump to child toggleExpansion $li unless is_expanded else # collapse; if already collapsed, jump to parent toggleExpansion $li if is_expanded else if event.ctrlKey if dir > 0 then mpd.next() else mpd.prev() else if event.shiftKey mpd.seek getCurrentTrackPosition() + dir * mpd.status.time * 0.10 else mpd.seek getCurrentTrackPosition() + dir * 10 handlers = 13: # enter ctrl: no alt: null shift: null handler: (event) -> if selection.isPlaylist() mpd.playId selection.cursor else if selection.isLibrary() queueLibSelection event 27: # escape ctrl: no alt: no shift: no handler: -> # if the user is dragging, abort the drag if started_drag abortDrag() return # if there's a menu, only remove that if $("#menu").get().length > 0 removeContextMenu() return selection.fullClear() refreshSelection() 32: # space ctrl: no alt: no shift: no handler: togglePlayback 37: # left ctrl: null alt: no shift: null handler: leftRightHandler 38: # up ctrl: null alt: no shift: null handler: upDownHandler 39: # right ctrl: null alt: no shift: null handler: leftRightHandler 40: # down ctrl: null alt: no shift: null handler: upDownHandler 46: # delete ctrl: no alt: no shift: null handler: (event) -> handleDeletePressed(event.shiftKey) 67: # 'c' ctrl: no alt: no shift: yes handler: -> mpd.clear() 68: # 'd' ctrl: no alt: no shift: no handler: toggleDynamicMode 72: # 'h' ctrl: no alt: no shift: yes handler: -> mpd.shuffle() 76: # 'l' ctrl: no alt: no shift: no handler: -> clickTab 'library' 82: # 'r' ctrl: no alt: no shift: no handler: nextRepeatState 83: # 's' ctrl: no alt: no shift: no handler: toggleStreamStatus 84: # 't' ctrl: no alt: no shift: no handler: -> clickTab 'chat' $("#chat-input").focus().select() 85: # 'u' ctrl: no alt: no shift: no handler: -> clickTab 'upload' $upload_by_url.focus().select() 187: # '=' or '+' ctrl: no alt: no shift: null handler: -> mpd.setVolume mpd.status.volume + 0.10 188: # ',' or '<' ctrl: no alt: no shift: null handler: -> mpd.prev() 189: # '-' or '_' ctrl: no alt: no shift: null handler: -> mpd.setVolume mpd.status.volume - 0.10 190: # '.' or '>' ctrl: no alt: no shift: null handler: -> mpd.next() 191: # '/' or '?' ctrl: no alt: no shift: null handler: (event) -> if event.shiftKey $(Handlebars.templates.shortcuts()).appendTo(document.body) $("#shortcuts").dialog modal: true title: "Keyboard Shortcuts" minWidth: 600 height: $document.height() - 40 close: -> $("#shortcuts").remove() else clickTab 'library' $("#lib-filter").focus().select() removeContextMenu = -> $("#menu").remove() isArtistExpanded = (artist) -> $li = $("#lib-artist-#{Util.toHtmlId(mpd.artistKey(artist.name))}").closest("li") return false unless $li.data('cached') return $li.find("> ul").is(":visible") isAlbumExpanded = (album) -> $li = $("#lib-album-#{Util.toHtmlId(album.key)}").closest("li") return $li.find("> ul").is(":visible") getTrackSelPos = (track) -> artist: track.album.artist album: track.album track: track getLibSelPos = (type, key) -> val = artist: null album: null track: null if key? switch type when 'track' val.track = mpd.search_results.track_table[key] val.album = val.track.album val.artist = val.album.artist when 'album' val.album = mpd.search_results.album_table[key] val.artist = val.album.artist when 'artist' val.artist = mpd.search_results.artist_table[key] else val.artist = mpd.search_results.artists[0] return val libPosToArr = (lib_pos) -> [lib_pos.artist?.pos, lib_pos.album?.pos, lib_pos.track?.pos] # modifies in place prevLibPos = (lib_pos) -> if lib_pos.track? lib_pos.track = lib_pos.track.album.tracks[lib_pos.track.pos - 1] else if lib_pos.album? lib_pos.album = lib_pos.artist.albums[lib_pos.album.pos - 1] if lib_pos.album? and isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[lib_pos.album.tracks.length - 1] else if lib_pos.artist? lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos - 1] if lib_pos.artist? and isArtistExpanded(lib_pos.artist) lib_pos.album = lib_pos.artist.albums[lib_pos.artist.albums.length - 1] if lib_pos.album? and isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[lib_pos.album.tracks.length - 1] # modifies in place nextLibPos = (lib_pos) -> if lib_pos.track? lib_pos.track = lib_pos.track.album.tracks[lib_pos.track.pos + 1] if not lib_pos.track? lib_pos.album = lib_pos.artist.albums[lib_pos.album.pos + 1] if not lib_pos.album? lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] else if lib_pos.album? if isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[0] else lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] lib_pos.album = null else if lib_pos.artist? if isArtistExpanded(lib_pos.artist) lib_pos.album = lib_pos.artist.albums[0] else lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] selectLibraryPosition = (lib_pos) -> if lib_pos.track? selection.ids.track[lib_pos.track.file] = true else if lib_pos.album? selection.ids.album[lib_pos.album.key] = true else if lib_pos.artist? selection.ids.artist[mpd.artistKey(lib_pos.artist.name)] = true queueFilesPos = -> pos = mpd.playlist.item_list.length return pos unless server_status? for item, i in mpd.playlist.item_list return i if server_status.random_ids[item.id]? queueLibSelection = (event) -> files = selectionToFiles(event.altKey) if event.shiftKey mpd.queueFilesNext files else mpd.queueFiles files, queueFilesPos() return false settings_ui = auth: show_edit: false password: "" sendAuth = -> pass = localStorage.auth_password return unless pass? mpd.authenticate pass, (err) -> if err delete localStorage.auth_password renderSettings() socket.emit 'Password', pass settingsAuthSave = -> settings_ui.auth.show_edit = false $text_box = $("#auth-password") localStorage.auth_password = $text_box.val() # try to auth renderSettings() sendAuth() settingsAuthCancel = -> settings_ui.auth.show_edit = false renderSettings() performDrag = (event, callbacks) -> abortDrag() start_drag_x = event.pageX start_drag_y = event.pageY abortDrag = -> $document .off('mousemove', onDragMove) .off('mouseup', onDragEnd) if started_drag $playlist_items.find(".pl-item").removeClass('border-top').removeClass('border-bottom') started_drag = false abortDrag = -> onDragMove = (event) -> if not started_drag dist = Math.pow(event.pageX - start_drag_x, 2) + Math.pow(event.pageY - start_drag_y, 2) started_drag = true if dist > 64 return unless started_drag result = getDragPosition(event.pageX, event.pageY) $playlist_items.find(".pl-item").removeClass('border-top').removeClass('border-bottom') $("#playlist-track-#{result.track_id}").addClass "border-#{result.direction}" onDragEnd = (event) -> return false unless event.button is 0 if started_drag callbacks.complete getDragPosition(event.pageX, event.pageY), event else callbacks.cancel() abortDrag() $document .on('mousemove', onDragMove) .on('mouseup', onDragEnd) onDragMove event setUpUi = -> $document.on 'mouseover', '.hoverable', (event) -> $(this).addClass "ui-state-hover" $document.on 'mouseout', '.hoverable', (event) -> $(this).removeClass "ui-state-hover" $(".jquery-button").button() $pl_window = $("#playlist-window") $pl_window.on 'click', 'button.clear', -> mpd.clear() $pl_window.on 'click', 'button.shuffle', -> mpd.shuffle() $pl_btn_repeat.on 'click', -> nextRepeatState() $dynamic_mode.on 'click', -> value = $(this).prop("checked") setDynamicMode(value) return false $playlist_items.on 'dblclick', '.pl-item', (event) -> track_id = $(this).data('id') mpd.playId track_id $playlist_items.on 'contextmenu', (event) -> return event.altKey $playlist_items.on 'mousedown', '.pl-item', (event) -> return true if started_drag # if any text box has focus, unfocus it $(document.activeElement).blur() if event.button is 0 event.preventDefault() # selecting / unselecting removeContextMenu() track_id = $(this).data('id') skip_drag = false if not selection.isPlaylist() selection.selectOnly 'playlist', track_id else if event.ctrlKey or event.shiftKey skip_drag = true if event.shiftKey and not event.ctrlKey selection.clear() if event.shiftKey old_pos = if selection.cursor? then mpd.playlist.item_table[selection.cursor].pos else 0 new_pos = mpd.playlist.item_table[track_id].pos for i in [old_pos..new_pos] selection.ids.playlist[mpd.playlist.item_list[i].id] = true else if event.ctrlKey if selection.ids.playlist[track_id]? delete selection.ids.playlist[track_id] else selection.ids.playlist[track_id] = true selection.cursor = track_id else if not selection.ids.playlist[track_id]? selection.selectOnly 'playlist', track_id refreshSelection() # dragging if not skip_drag performDrag event, complete: (result, event) -> delta = top: 0 bottom: 1 new_pos = mpd.playlist.item_table[result.track_id].pos + delta[result.direction] mpd.moveIds (id for id of selection.ids.playlist), new_pos cancel: -> # we didn't end up dragging, select the item selection.selectOnly 'playlist', track_id refreshSelection() else if event.button is 2 return if event.altKey event.preventDefault() # context menu removeContextMenu() track_id = parseInt($(this).data('id')) if not selection.isPlaylist() or not selection.ids.playlist[track_id]? selection.selectOnly 'playlist', track_id refreshSelection() # adds a new context menu to the document context = item: mpd.playlist.item_table[track_id] status: server_status permissions: permissions $(Handlebars.templates.playlist_menu(context)) .appendTo(document.body) $menu = $("#menu") # get the newly created one $menu.offset left: event.pageX+1 top: event.pageY+1 # don't close menu when you click on the area next to a button $menu.on 'mousedown', -> false $menu.on 'click', '.remove', -> handleDeletePressed(false) removeContextMenu() return false $menu.on 'click', '.download', -> removeContextMenu() return true $menu.on 'click', '.delete', -> handleDeletePressed(true) removeContextMenu() return false # don't remove selection in playlist click $playlist_items.on 'mousedown', -> false # delete context menu $document.on 'mousedown', -> removeContextMenu() selection.type = null refreshSelection() $document.on 'keydown', (event) -> if (handler = keyboard_handlers[event.keyCode])? and (not handler.ctrl? or handler.ctrl is event.ctrlKey) and (not handler.alt? or handler.alt is event.altKey) and (not handler.shift? or handler.shift is event.shiftKey) handler.handler event return false return true $library.on 'mousedown', 'div.expandable > div.ui-icon', (event) -> toggleExpansion $(this).closest("li") return false # suppress double click on the icon $library.on 'dblclick', 'div.expandable > div.ui-icon', -> false $library.on 'dblclick', 'div.artist, div.album, div.track', queueLibSelection $library.on 'contextmenu', (event) -> return event.altKey libraryMouseDown = (event, sel_name, key) -> # if any text box has focus, unfocus it $(document.activeElement).blur() if event.button is 0 event.preventDefault() removeContextMenu() skip_drag = false if not selection.isLibrary() selection.selectOnly sel_name, key else if event.ctrlKey or event.shiftKey skip_drag = true if event.shiftKey and not event.ctrlKey selection.clear() if event.shiftKey old_pos = getLibSelPos(selection.type, selection.cursor) new_pos = getLibSelPos(sel_name, key) # swap if positions are out of order new_arr = libPosToArr(new_pos) old_arr = libPosToArr(old_pos) [old_pos, new_pos] = [new_pos, old_pos] if Util.compareArrays(old_arr, new_arr) > 0 libraryPositionEqual = (old_pos, new_pos) -> old_arr = libPosToArr(old_pos) new_arr = libPosToArr(new_pos) return Util.compareArrays(old_arr, new_arr) is 0 while old_pos.artist? selectLibraryPosition old_pos break if libraryPositionEqual(old_pos, new_pos) nextLibPos old_pos else if event.ctrlKey if selection.ids[sel_name][key]? delete selection.ids[sel_name][key] else selection.ids[sel_name][key] = true selection.cursor = key selection.type = sel_name else if not selection.ids[sel_name][key]? selection.selectOnly sel_name, key refreshSelection() # dragging if not skip_drag performDrag event, complete: (result, event) -> delta = top: 0 bottom: 1 new_pos = mpd.playlist.item_table[result.track_id].pos + delta[result.direction] files = selectionToFiles(event.altKey) mpd.queueFiles files, new_pos cancel: -> # we didn't end up dragging, select the item selection.selectOnly sel_name, key refreshSelection() else if event.button = 2 return if event.altKey event.preventDefault() removeContextMenu() if not selection.isLibrary() or not selection.ids[sel_name][key]? selection.selectOnly sel_name, key refreshSelection() # adds a new context menu to the document context = status: server_status permissions: permissions if sel_name is 'track' context.track = mpd.search_results.track_table[key] $(Handlebars.templates.library_menu(context)).appendTo(document.body) $menu = $("#menu") # get the newly created one $menu.offset left: event.pageX+1 # +1 so we don't immediately close the menu by clicking it top: event.pageY+1 # don't close menu when you click on the area next to a button $menu.on 'mousedown', -> false $menu.on 'click', '.queue', -> mpd.queueFiles selectionToFiles() removeContextMenu() return false $menu.on 'click', '.queue-next', -> mpd.queueFilesNext selectionToFiles() removeContextMenu() return false $menu.on 'click', '.queue-random', -> mpd.queueFiles selectionToFiles(true) removeContextMenu() return false $menu.on 'click', '.queue-next-random', -> mpd.queueFilesNext selectionToFiles(true) removeContextMenu() return false $menu.on 'click', '.download', -> removeContextMenu() return true $menu.on 'click', '.delete', -> handleDeletePressed(true) removeContextMenu() return false $library.on 'mousedown', '.artist', (event) -> artist_key = mpd.artistKey($(this).find("span").text()) libraryMouseDown event, 'artist', artist_key $library.on 'mousedown', '.album', (event) -> libraryMouseDown event, 'album', $(this).data('key') $library.on 'mousedown', '.track', (event) -> libraryMouseDown event, 'track', $(this).data('file') $library.on 'mousedown', -> false $lib_filter = $("#lib-filter") $lib_filter.on 'keydown', (event) -> event.stopPropagation() switch event.keyCode when 27 # if the box is blank, remove focus if $(event.target).val().length is 0 $(event.target).blur() else # defer the setting of the text box until after the event loop to # work around a firefox bug Util.wait 0, -> $(event.target).val("") mpd.search "" return false when 13 # queue all the search results files = [] for artist in mpd.search_results.artists for album in artist.albums for track in album.tracks files.push track.file if event.altKey Util.shuffle(files) if files.length > 2000 return false unless confirm("You are about to queue #{files.length} songs.") if event.shiftKey mpd.queueFilesNext files else mpd.queueFiles files, queueFilesPos() return false when 40 # down # select the first item in the library selection.selectOnly 'artist', mpd.artistKey(mpd.search_results.artists[0].name) refreshSelection() $lib_filter.blur() return false when 38 # up # select the last item in the library selection.selectOnly 'artist', mpd.artistKey(mpd.search_results.artists[mpd.search_results.artists.length - 1].name) refreshSelection() $lib_filter.blur() return false $lib_filter.on 'keyup', (event) -> mpd.search $(event.target).val() $chat_name_input = $("#chat-name-input") $chat_user_id_span.on 'click', (event) -> $chat_input.attr "disabled", "disabled" chat_name_input_visible = true $chat_name_input.show().val("").focus().select() renderChat() $chat_name_input.on 'keydown', (event) -> event.stopPropagation() if event.keyCode is 27 # cancel done = true else if event.keyCode is 13 # accept done = true setUserName $(event.target).val() if done chat_name_input_visible = false $chat_name_input.hide() $chat_input.removeAttr("disabled").focus().select() renderChat() return false $chat_input = $("#chat-input") $chat_input.on 'keydown', (event) -> event.stopPropagation() if event.keyCode is 27 $(event.target).blur() return false else if event.keyCode is 13 message = $.trim($(event.target).val()) Util.wait 0, -> $(event.target).val("") return false if message is "" unless haveUserName() new_user_name = message NICK = "/nick " if message.substr(0, NICK.length) is NICK new_user_name = message.substr(NICK.length) if new_user_name? setUserName new_user_name return false socket.emit 'Chat', message return false actions = 'toggle': togglePlayback 'prev': -> mpd.prev() 'next': -> mpd.next() 'stop': -> mpd.stop() $nowplaying = $("#nowplaying") for cls, action of actions do (cls, action) -> $nowplaying.on 'mousedown', "li.#{cls}", (event) -> action() return false $track_slider.slider step: 0.0001 min: 0 max: 1 change: (event, ui) -> return if not event.originalEvent? mpd.seek ui.value * mpd.status.time slide: (event, ui) -> $nowplaying_elapsed.html Util.formatTime(ui.value * mpd.status.time) start: (event, ui) -> user_is_seeking = true stop: (event, ui) -> user_is_seeking = false setVol = (event, ui) -> return if not event.originalEvent? mpd.setVolume ui.value $vol_slider.slider step: 0.01 min: 0 max: 1 change: setVol start: (event, ui) -> user_is_volume_sliding = true stop: (event, ui) -> user_is_volume_sliding = false # move the slider along the path Util.schedule 100, updateSliderPos $stream_btn.button icons: primary: "ui-icon-signal-diag" $stream_btn.on 'click', toggleStreamStatus $lib_tabs.on 'mouseover', 'li', (event) -> $(this).addClass 'ui-state-hover' $lib_tabs.on 'mouseout', 'li', (event) -> $(this).removeClass 'ui-state-hover' tabs = [ 'library' 'upload' 'chat' 'settings' ] unselectTabs = -> $lib_tabs.find('li').removeClass 'ui-state-active' for tab in tabs $("##{tab}-tab").hide() clickTab = (name) -> return if name is 'upload' and not server_status?.upload_enabled unselectTabs() $lib_tabs.find("li.#{name}-tab").addClass 'ui-state-active' $("##{name}-tab").show() handleResize() renderChat() if name is 'chat' for tab in tabs do (tab) -> $lib_tabs.on 'click', "li.#{tab}-tab", (event) -> clickTab tab uploader = new qq.FileUploader element: document.getElementById("upload-widget") action: '/upload' encoding: 'multipart' $settings.on 'click', '.signout', (event) -> delete localStorage?.lastfm_username delete localStorage?.lastfm_session_key delete localStorage?.lastfm_scrobbling_on renderSettings() return false $settings.on 'click', '#toggle-scrobble', (event) -> value = $(this).prop("checked") if value msg = 'LastfmScrobblersAdd' localStorage?.lastfm_scrobbling_on = true else msg = 'LastfmScrobblersRemove' delete localStorage?.lastfm_scrobbling_on params = username: localStorage?.lastfm_username session_key: localStorage?.lastfm_session_key socket.emit msg, JSON.stringify(params) renderSettings() return false $settings.on 'click', '.auth-edit', (event) -> settings_ui.auth.show_edit = true renderSettings() $text_box = $("#auth-password") $text_box.focus().val(localStorage.auth_password ? "").select() $settings.on 'click', '.auth-clear', (event) -> delete localStorage.auth_password settings_ui.auth.password = "" renderSettings() $settings.on 'click', '.auth-save', (event) -> settingsAuthSave() $settings.on 'click', '.auth-cancel', (event) -> settingsAuthCancel() $settings.on 'keydown', '#auth-password', (event) -> $text_box = $(this) event.stopPropagation() settings_ui.auth.password = $text_box.val() if event.which is 27 settingsAuthCancel() else if event.which is 13 settingsAuthSave() $settings.on 'keyup', '#auth-password', (event) -> settings_ui.auth.password = $(this).val() $upload_by_url.on 'keydown', (event) -> event.stopPropagation() if event.which is 27 $upload_by_url.val("").blur() else if event.which is 13 url = $upload_by_url.val() $upload_by_url.val("").blur() socket.emit 'ImportTrackUrl', url # end setUpUi initHandlebars = -> Handlebars.registerHelper 'time', Util.formatTime Handlebars.registerHelper 'artistid', (s) -> "lib-artist-#{Util.toHtmlId(mpd.artistKey(s))}" Handlebars.registerHelper 'albumid', (s) -> "lib-album-#{Util.toHtmlId(s)}" Handlebars.registerHelper 'trackid', (s) -> "lib-track-#{Util.toHtmlId(s)}" handleResize = -> $nowplaying = $("#nowplaying") $left_window = $("#left-window") $pl_window = $("#playlist-window") # go really small to make the window as small as possible $nowplaying.width MARGIN $pl_window.height MARGIN $left_window.height MARGIN # then fit back up to the window $nowplaying.width $document.width() - MARGIN * 2 second_layer_top = $nowplaying.offset().top + $nowplaying.height() + MARGIN $left_window.offset left: MARGIN top: second_layer_top $pl_window.offset left: $left_window.offset().left + $left_window.width() + MARGIN top: second_layer_top $pl_window.width $(window).width() - $pl_window.offset().left - MARGIN $left_window.height $(window).height() - $left_window.offset().top $pl_window.height $left_window.height() - MARGIN # make the inside containers fit $lib_header = $("#library-tab .window-header") $library.height $left_window.height() - $lib_header.position().top - $lib_header.height() - MARGIN tab_contents_height = $left_window.height() - $lib_tabs.height() - MARGIN $("#upload").height tab_contents_height resizeChat() $pl_header = $pl_window.find("#playlist .header") $playlist_items.height $pl_window.height() - $pl_header.position().top - $pl_header.height() resizeChat = -> height_overshoot = $("#chat-tab").height() - $("#upload").height() $chat_list.height $chat_list.height() - height_overshoot initStreaming = -> soundManager.setup url: "/vendor/soundmanager2/" flashVersion: 9 debugMode: false window.WEB_SOCKET_SWF_LOCATION = "/vendor/socket.io/WebSocketMain.swf" $document.ready -> if localStorage?.my_user_ids? my_user_ids = JSON.parse localStorage.my_user_ids socket = io.connect() # special case when we get the callback from Last.fm. # tell the server the token and save the session in localStorage. # then refresh but remove the "?token=*" from the URL. if (token = Util.parseQuery(location.search.substring(1))?.token)? socket.emit 'LastfmGetSession', token refreshPage = -> location.href = "#{location.protocol}//#{location.host}/" socket.on 'LastfmGetSessionSuccess', (data) -> params = JSON.parse(data) localStorage?.lastfm_username = params.session.name localStorage?.lastfm_session_key = params.session.key delete localStorage?.lastfm_scrobbling_on refreshPage() socket.on 'LastfmGetSessionError', (data) -> params = JSON.parse(data) alert "Error authenticating: #{params.message}" refreshPage() return socket.on 'connect', -> load_status = LoadStatus.NoMpd render() socket.on 'Identify', (data) -> my_user_id = data.toString() my_user_ids[my_user_id] = 1 storeMyUserIds() if (user_name = localStorage?.user_name)? setUserName user_name socket.on 'Permissions', (data) -> permissions = JSON.parse data.toString() renderSettings() socket.on 'Status', (data) -> server_status = JSON.parse data.toString() storeMyUserIds() renderPlaylistButtons() renderChat() labelPlaylistItems() renderSettings() window._debug_server_status = server_status mpd = new window.SocketMpd socket mpd.on 'libraryupdate', renderLibrary mpd.on 'playlistupdate', renderPlaylist mpd.on 'statusupdate', -> renderNowPlaying() renderPlaylistButtons() labelPlaylistItems() updateStreamingPlayer() mpd.on 'chat', renderChat mpd.on 'connect', -> sendAuth() load_status = LoadStatus.GoodToGo render() socket.on 'disconnect', -> load_status = LoadStatus.NoServer render() socket.on 'MpdDisconnect', -> load_status = LoadStatus.NoMpd render() setUpUi() initHandlebars() initStreaming() render() # do this last so that everything becomes the correct size. $(window).resize handleResize window._debug_mpd = mpd
true
#depend "util" #depend "socketmpd" #depend "jquery-1.7.1.min" bare #depend "jquery-ui-1.8.17.custom.min" bare #depend "soundmanager2/soundmanager2-nodebug-jsmin" bare #depend "fileuploader/fileuploader" bare #depend "socket.io/socket.io.min" bare selection = ids: playlist: {} # key is id, value is some dummy value artist: {} album: {} track: {} cursor: null # the last touched id type: null # 'playlist', 'artist', 'album', or 'track' isLibrary: -> return false if not this.type? return this.type isnt 'playlist' isPlaylist: -> return false if not this.type? return this.type is 'playlist' clear: -> this.ids.artist = {} this.ids.album = {} this.ids.track = {} this.ids.playlist = {} fullClear: -> this.clear() this.type = null this.cursor = null selectOnly: (sel_name, key) -> this.clear() this.type = sel_name this.ids[sel_name][key] = true this.cursor = key server_status = null permissions = {} socket = null mpd = null base_title = document.title user_is_seeking = false user_is_volume_sliding = false started_drag = false abortDrag = -> clickTab = null trying_to_stream = false actually_streaming = false streaming_buffering = false my_user_id = null my_user_ids = {} chat_name_input_visible = false MARGIN = 10 LoadStatus = Init: 0 NoMpd: 1 NoServer: 2 GoodToGo: 3 LoadStatusMsg = [ 'Loading...' 'mpd is not running on the server.' 'Server is down.' ] load_status = LoadStatus.Init # cache jQuery objects $document = $(document) $playlist_items = $("#playlist-items") $dynamic_mode = $("#dynamic-mode") $pl_btn_repeat = $("#pl-btn-repeat") $stream_btn = $("#stream-btn") $lib_tabs = $("#lib-tabs") $upload_tab = $("#lib-tabs .upload-tab") $chat_tab = $("#lib-tabs .chat-tab") $library = $("#library") $track_slider = $("#track-slider") $nowplaying = $("#nowplaying") $nowplaying_elapsed = $nowplaying.find(".elapsed") $nowplaying_left = $nowplaying.find(".left") $vol_slider = $("#vol-slider") $chat_user_list = $("#chat-user-list") $chat_list = $("#chat-list") $chat_user_id_span = $("#user-id") $settings = $("#settings") $upload_by_url = $("#upload-by-url") $main_err_msg = $("#main-err-msg") $main_err_msg_text = $("#main-err-msg-text") haveUserName = -> server_status?.user_names[my_user_id]? getUserName = -> userIdToUserName my_user_id userIdToUserName = (user_id) -> return user_id unless server_status? user_name = server_status.user_names[user_id] return user_name ? user_id storeMyUserIds = -> # scrub stale ids. TODO: this is broken. #if server_status? # for user_id of my_user_ids # delete my_user_ids[user_id] unless server_status.user_names[user_id]? localStorage?.my_user_ids = JSON.stringify my_user_ids setUserName = (new_name) -> new_name = $.trim new_name localStorage?.user_name = new_name socket.emit 'SetUserName', new_name scrollLibraryToSelection = -> return unless (helpers = getSelHelpers())? delete helpers.playlist scrollThingToSelection $library, helpers scrollPlaylistToSelection = -> return unless (helpers = getSelHelpers())? delete helpers.track delete helpers.artist delete helpers.album scrollThingToSelection $playlist_items, helpers scrollThingToSelection = ($scroll_area, helpers) -> top_pos = null bottom_pos = null for sel_name, [ids, table, $getDiv] of helpers for id of ids item_top = ($div = $getDiv(id)).offset().top item_bottom = item_top + $div.height() if not top_pos? or item_top < top_pos top_pos = item_top if not bottom_pos? or item_bottom > bottom_pos bottom_pos = item_bottom if top_pos? scroll_area_top = $scroll_area.offset().top selection_top = top_pos - scroll_area_top selection_bottom = bottom_pos - scroll_area_top - $scroll_area.height() scroll_amt = $scroll_area.scrollTop() if selection_top < 0 $scroll_area.scrollTop scroll_amt + selection_top else if selection_bottom > 0 $scroll_area.scrollTop scroll_amt + selection_bottom selectionToFiles = (random=false) -> # render selection into a single object by file to remove duplicates # works for library only track_set = {} selRenderArtist = (artist) -> selRenderAlbum album for album in artist.albums selRenderAlbum = (album) -> selRenderTrack track for track in album.tracks selRenderTrack = (track) -> track_set[track.file] = libPosToArr(getTrackSelPos(track)) selRenderArtist(mpd.search_results.artist_table[key]) for key of selection.ids.artist selRenderAlbum(mpd.search_results.album_table[key]) for key of selection.ids.album selRenderTrack(mpd.search_results.track_table[file]) for file of selection.ids.track if random files = (file for file of track_set) Util.shuffle files return files else track_arr = ({file: file, pos: pos} for file, pos of track_set) track_arr.sort (a, b) -> Util.compareArrays(a.pos, b.pos) return (track.file for track in track_arr) getDragPosition = (x, y) -> # loop over the playlist items and find where it fits best = track_id: null distance: null direction: null for item in $playlist_items.find(".pl-item").get() $item = $(item) pos = $item.offset() height = $item.height() track_id = parseInt($item.data('id')) # try the top of this element distance = Math.abs(pos.top - y) if not best.distance? or distance < best.distance best.distance = distance best.direction = "top" best.track_id = track_id # try the bottom distance = Math.abs(pos.top + height - y) if distance < best.distance best.distance = distance best.direction = "bottom" best.track_id = track_id return best renderSettings = -> return unless (api_key = server_status?.lastfm_api_key)? context = lastfm: auth_url: "http://www.last.fm/api/auth/?api_key=#{escape(api_key)}&cb=#{location.protocol}//#{location.host}/" username: localStorage.lastfm_username session_key: localStorage.lastfm_session_key scrobbling_on: localStorage.lastfm_scrobbling_on? auth: password: PI:PASSWORD:<PASSWORD>END_PI show_edit: not localStorage.auth_password? or settings_ui.auth.show_edit permissions: permissions $settings.html Handlebars.templates.settings(context) $settings.find(".signout").button() $settings.find("#toggle-scrobble").button() $settings.find(".auth-cancel").button() $settings.find(".auth-save").button() $settings.find(".auth-edit").button() $settings.find(".auth-clear").button() $settings.find("#auth-password").val(settings_ui.auth.password) scrollChatWindowToBottom = -> # for some reason, Infinity goes to the top :/ $chat_list.scrollTop 1000000 renderChat = -> chat_status_text = "" if (users = server_status?.users)? chat_status_text = " (#{users.length})" if users.length > 1 user_objects = ({ "class": if user_id is my_user_id then "chat-user-self" else "chat-user" user_name: userIdToUserName user_id } for user_id in users) # write everyone's name in the chat objects (too bad handlebars can't do this in the template) for chat_object in server_status.chats chat_object["class"] = if my_user_ids[chat_object.user_id]? then "chat-user-self" else "chat-user" chat_object.user_name = userIdToUserName chat_object.user_id $chat_user_list.html Handlebars.templates.chat_user_list users: user_objects $chat_list.html Handlebars.templates.chat_list chats: server_status.chats scrollChatWindowToBottom() $chat_user_id_span.text if chat_name_input_visible then "" else getUserName() + ": " $chat_tab.find("span").text("Chat#{chat_status_text}") resizeChat() renderStreamButton = -> label = if trying_to_stream if actually_streaming if streaming_buffering "Stream: Buffering" else "Stream: On" else "Stream: Paused" else "Stream: Off" # disable stream button if we don't have it set up $stream_btn .button("option", "disabled", not server_status?.stream_httpd_port?) .button("option", "label", label) .prop("checked", trying_to_stream) .button("refresh") renderPlaylistButtons = -> # set the state of dynamic mode button $dynamic_mode .prop("checked", if server_status?.dynamic_mode then true else false) .button("option", "disabled", not server_status?.dynamic_mode_enabled) .button("refresh") repeat_state = getRepeatStateName() $pl_btn_repeat .button("option", "label", "Repeat: #{repeat_state}") .prop("checked", repeat_state isnt 'Off') .button("refresh") renderStreamButton() # show/hide upload $upload_tab.removeClass("ui-state-disabled") $upload_tab.addClass("ui-state-disabled") if not server_status?.upload_enabled renderPlaylist = -> context = playlist: mpd.playlist.item_list server_status: server_status scroll_top = $playlist_items.scrollTop() $playlist_items.html Handlebars.templates.playlist(context) refreshSelection() labelPlaylistItems() $playlist_items.scrollTop(scroll_top) labelPlaylistItems = -> cur_item = mpd.status.current_item # label the old ones $playlist_items.find(".pl-item").removeClass('current').removeClass('old') if cur_item? and server_status?.dynamic_mode for pos in [0...cur_item.pos] id = mpd.playlist.item_list[pos].id $("#playlist-track-#{id}").addClass('old') # label the random ones if server_status?.random_ids? for item in mpd.playlist.item_list if server_status.random_ids[item.id] $("#playlist-track-#{item.id}").addClass('random') # label the current one $("#playlist-track-#{cur_item.id}").addClass('current') if cur_item? getSelHelpers = -> return null unless mpd?.playlist?.item_table? return null unless mpd?.search_results?.artist_table? return {} = playlist: [selection.ids.playlist, mpd.playlist.item_table, (id) -> $("#playlist-track-#{id}")] artist: [selection.ids.artist, mpd.search_results.artist_table, (id) -> $("#lib-artist-#{Util.toHtmlId(id)}")] album: [selection.ids.album, mpd.search_results.album_table, (id) -> $("#lib-album-#{Util.toHtmlId(id)}")] track: [selection.ids.track, mpd.search_results.track_table, (id) -> $("#lib-track-#{Util.toHtmlId(id)}")] refreshSelection = -> return unless (helpers = getSelHelpers())? # clear all selection $playlist_items.find(".pl-item").removeClass('selected').removeClass('cursor') $library.find(".artist").removeClass('selected').removeClass('cursor') $library.find(".album").removeClass('selected').removeClass('cursor') $library.find(".track").removeClass('selected').removeClass('cursor') return unless selection.type? for sel_name, [ids, table, $getDiv] of helpers # if any selected artists are not in mpd.search_results, unselect them delete ids[id] for id in (id for id of ids when not table[id]?) # highlight selected rows $getDiv(id).addClass 'selected' for id of ids if selection.cursor? and sel_name is selection.type $getDiv(selection.cursor).addClass('cursor') renderLibrary = -> context = artists: mpd.search_results.artists empty_library_message: if mpd.have_file_list_cache then "No Results" else "loading..." scroll_top = $library.scrollTop() $library.html Handlebars.templates.library(context) # auto expand small datasets $artists = $library.children("ul").children("li") node_count = $artists.length node_count_limit = 20 expand_stuff = ($li_set) -> for li in $li_set $li = $(li) return if node_count >= node_count_limit $ul = $li.children("ul") $sub_li_set = $ul.children("li") proposed_node_count = node_count + $sub_li_set.length if proposed_node_count <= node_count_limit toggleExpansion $li # get these vars again because they might have been dynamically added # by toggleExpansion $ul = $li.children("ul") $sub_li_set = $ul.children("li") node_count = proposed_node_count expand_stuff $sub_li_set expand_stuff $artists $library.scrollTop(scroll_top) refreshSelection() # returns how many seconds we are into the track getCurrentTrackPosition = -> if mpd.status.track_start_date? and mpd.status.state is "play" (new Date() - mpd.status.track_start_date) / 1000 else mpd.status.elapsed updateSliderPos = -> return if user_is_seeking if (time = mpd.status.time)? and mpd.status.current_item? and (mpd.status.state ? "stop") isnt "stop" disabled = false elapsed = getCurrentTrackPosition() slider_pos = elapsed / time else disabled = true elapsed = time = slider_pos = 0 $track_slider .slider("option", "disabled", disabled) .slider("option", "value", slider_pos) $nowplaying_elapsed.html Util.formatTime(elapsed) $nowplaying_left.html Util.formatTime(time) renderNowPlaying = -> # set window title if (track = mpd.status.current_item?.track)? track_display = "#{track.name} - #{track.artist_name}" if track.album_name.length track_display += " - " + track.album_name document.title = "#{track_display} - #{base_title}" # Easter time! if track.name.indexOf("PI:NAME:<NAME>END_PI") is 0 $("html").addClass('groovebasin') else $("html").removeClass('groovebasin') if track.name.indexOf("Never Gonna Give You Up") is 0 and track.artist_name.indexOf("PI:NAME:<NAME>END_PI") is 0 $("html").addClass('nggyu') else $("html").removeClass('nggyu') else track_display = "&nbsp;" document.title = base_title # set song title $("#track-display").html(track_display) state = mpd.status.state ? "stop" # set correct pause/play icon toggle_icon = play: ['ui-icon-play', 'ui-icon-pause'] stop: ['ui-icon-pause', 'ui-icon-play'] pause: ['ui-icon-pause', 'ui-icon-play'] [old_class, new_class] = toggle_icon[state] $nowplaying.find(".toggle span").removeClass(old_class).addClass(new_class) # hide seeker bar if stopped $track_slider.slider "option", "disabled", state is "stop" updateSliderPos() # update volume pos unless user_is_volume_sliding enabled = (vol = mpd.status.volume)? $vol_slider.slider 'option', 'value', vol if enabled $vol_slider.slider 'option', 'disabled', not enabled render = -> hide_main_err = load_status is LoadStatus.GoodToGo $("#playlist-window").toggle(hide_main_err) $("#left-window").toggle(hide_main_err) $("#nowplaying").toggle(hide_main_err) $main_err_msg.toggle(not hide_main_err) unless hide_main_err document.title = base_title $main_err_msg_text.text(LoadStatusMsg[load_status]) return renderPlaylist() renderPlaylistButtons() renderLibrary() renderNowPlaying() renderChat() renderSettings() handleResize() toggleExpansion = ($li) -> $div = $li.find("> div") $ul = $li.find("> ul") if $div.hasClass('artist') if not $li.data('cached') $li.data 'cached', true $ul.html Handlebars.templates.albums albums: mpd.getArtistAlbums($div.find("span").text()) $ul.toggle() refreshSelection() $ul.toggle() old_class = 'ui-icon-triangle-1-se' new_class = 'ui-icon-triangle-1-e' [new_class, old_class] = [old_class, new_class] if $ul.is(":visible") $div.find("div").removeClass(old_class).addClass(new_class) return false confirmDelete = (files_list) -> list_text = files_list.slice(0, 7).join("\n ") if files_list.length > 7 list_text += "\n ..." song_text = if files_list.length is 1 then "song" else "songs" confirm """ You are about to delete #{files_list.length} #{song_text} permanently: #{list_text} """ handleDeletePressed = (shift) -> if selection.isLibrary() files_list = selectionToFiles() if not confirmDelete(files_list) then return socket.emit 'DeleteFromLibrary', JSON.stringify(files_list) else if selection.isPlaylist() if shift # delete from library files_list = (mpd.playlist.item_table[id].track.file for id of selection.ids.playlist) if not confirmDelete(files_list) then return socket.emit 'DeleteFromLibrary', JSON.stringify(files_list) # fall through and also remove the items from the playlist # remove items from playlist and select the item next in the list pos = mpd.playlist.item_table[selection.cursor].pos mpd.removeIds (id for id of selection.ids.playlist) pos = mpd.playlist.item_list.length - 1 if pos >= mpd.playlist.item_list.length selection.selectOnly 'playlist', mpd.playlist.item_list[pos].id if pos > -1 refreshSelection() toggleStreamStatus = -> return unless server_status?.stream_httpd_port? trying_to_stream = not trying_to_stream renderStreamButton() updateStreamingPlayer() return false updateStreamingPlayer = -> should_stream = trying_to_stream and mpd.status.state is "play" return if actually_streaming is should_stream if should_stream format = server_status.stream_httpd_format port = server_status?.stream_httpd_port stream_url = "#{location.protocol}//#{location.hostname}:#{port}/stream.#{format}" soundManager.destroySound('stream') sound = soundManager.createSound id: 'stream' url: stream_url onbufferchange: -> streaming_buffering = sound.isBuffering renderStreamButton() sound.play() streaming_buffering = sound.isBuffering else soundManager.destroySound('stream') streaming_buffering = false actually_streaming = should_stream renderStreamButton() togglePlayback = -> if mpd.status.state is 'play' mpd.pause() else mpd.play() setDynamicMode = (value) -> args = dynamic_mode: value socket.emit 'DynamicMode', JSON.stringify(args) toggleDynamicMode = -> setDynamicMode not server_status.dynamic_mode getRepeatStateName = -> if not mpd.status.repeat "Off" else if mpd.status.repeat and not mpd.status.single "All" else "One" nextRepeatState = -> if not mpd.status.repeat mpd.changeStatus repeat: true single: true else if mpd.status.repeat and not mpd.status.single mpd.changeStatus repeat: false single: false else mpd.changeStatus repeat: true single: false keyboard_handlers = do -> upDownHandler = (event) -> if event.keyCode is 38 # up default_index = mpd.playlist.item_list.length - 1 dir = -1 else default_index = 0 dir = 1 if event.ctrlKey if selection.isPlaylist() # re-order playlist items mpd.shiftIds (id for id of selection.ids.playlist), dir else # change selection if selection.isPlaylist() next_pos = mpd.playlist.item_table[selection.cursor].pos + dir return if next_pos < 0 or next_pos >= mpd.playlist.item_list.length selection.cursor = mpd.playlist.item_list[next_pos].id selection.clear() unless event.shiftKey selection.ids.playlist[selection.cursor] = true else if selection.isLibrary() next_pos = getLibSelPos(selection.type, selection.cursor) if dir > 0 then nextLibPos(next_pos) else prevLibPos(next_pos) return if not next_pos.artist? selection.clear() unless event.shiftKey if next_pos.track? selection.type = 'track' selection.cursor = next_pos.track.file else if next_pos.album? selection.type = 'album' selection.cursor = next_pos.album.key else selection.type = 'artist' selection.cursor = mpd.artistKey(next_pos.artist.name) selection.ids[selection.type][selection.cursor] = true else selection.selectOnly 'playlist', mpd.playlist.item_list[default_index].id refreshSelection() scrollPlaylistToSelection() if selection.isPlaylist() scrollLibraryToSelection() if selection.isLibrary() leftRightHandler = (event) -> dir = if event.keyCode is 37 then -1 else 1 if selection.isLibrary() return unless (helpers = getSelHelpers()) [ids, table, $getDiv] = helpers[selection.type] selected_item = table[selection.cursor] is_expanded_funcs = artist: isArtistExpanded album: isAlbumExpanded track: -> true is_expanded = is_expanded_funcs[selection.type](selected_item) $li = $getDiv(selection.cursor).closest("li") cursor_pos = getLibSelPos(selection.type, selection.cursor) if dir > 0 # expand and jump to child toggleExpansion $li unless is_expanded else # collapse; if already collapsed, jump to parent toggleExpansion $li if is_expanded else if event.ctrlKey if dir > 0 then mpd.next() else mpd.prev() else if event.shiftKey mpd.seek getCurrentTrackPosition() + dir * mpd.status.time * 0.10 else mpd.seek getCurrentTrackPosition() + dir * 10 handlers = 13: # enter ctrl: no alt: null shift: null handler: (event) -> if selection.isPlaylist() mpd.playId selection.cursor else if selection.isLibrary() queueLibSelection event 27: # escape ctrl: no alt: no shift: no handler: -> # if the user is dragging, abort the drag if started_drag abortDrag() return # if there's a menu, only remove that if $("#menu").get().length > 0 removeContextMenu() return selection.fullClear() refreshSelection() 32: # space ctrl: no alt: no shift: no handler: togglePlayback 37: # left ctrl: null alt: no shift: null handler: leftRightHandler 38: # up ctrl: null alt: no shift: null handler: upDownHandler 39: # right ctrl: null alt: no shift: null handler: leftRightHandler 40: # down ctrl: null alt: no shift: null handler: upDownHandler 46: # delete ctrl: no alt: no shift: null handler: (event) -> handleDeletePressed(event.shiftKey) 67: # 'c' ctrl: no alt: no shift: yes handler: -> mpd.clear() 68: # 'd' ctrl: no alt: no shift: no handler: toggleDynamicMode 72: # 'h' ctrl: no alt: no shift: yes handler: -> mpd.shuffle() 76: # 'l' ctrl: no alt: no shift: no handler: -> clickTab 'library' 82: # 'r' ctrl: no alt: no shift: no handler: nextRepeatState 83: # 's' ctrl: no alt: no shift: no handler: toggleStreamStatus 84: # 't' ctrl: no alt: no shift: no handler: -> clickTab 'chat' $("#chat-input").focus().select() 85: # 'u' ctrl: no alt: no shift: no handler: -> clickTab 'upload' $upload_by_url.focus().select() 187: # '=' or '+' ctrl: no alt: no shift: null handler: -> mpd.setVolume mpd.status.volume + 0.10 188: # ',' or '<' ctrl: no alt: no shift: null handler: -> mpd.prev() 189: # '-' or '_' ctrl: no alt: no shift: null handler: -> mpd.setVolume mpd.status.volume - 0.10 190: # '.' or '>' ctrl: no alt: no shift: null handler: -> mpd.next() 191: # '/' or '?' ctrl: no alt: no shift: null handler: (event) -> if event.shiftKey $(Handlebars.templates.shortcuts()).appendTo(document.body) $("#shortcuts").dialog modal: true title: "Keyboard Shortcuts" minWidth: 600 height: $document.height() - 40 close: -> $("#shortcuts").remove() else clickTab 'library' $("#lib-filter").focus().select() removeContextMenu = -> $("#menu").remove() isArtistExpanded = (artist) -> $li = $("#lib-artist-#{Util.toHtmlId(mpd.artistKey(artist.name))}").closest("li") return false unless $li.data('cached') return $li.find("> ul").is(":visible") isAlbumExpanded = (album) -> $li = $("#lib-album-#{Util.toHtmlId(album.key)}").closest("li") return $li.find("> ul").is(":visible") getTrackSelPos = (track) -> artist: track.album.artist album: track.album track: track getLibSelPos = (type, key) -> val = artist: null album: null track: null if key? switch type when 'track' val.track = mpd.search_results.track_table[key] val.album = val.track.album val.artist = val.album.artist when 'album' val.album = mpd.search_results.album_table[key] val.artist = val.album.artist when 'artist' val.artist = mpd.search_results.artist_table[key] else val.artist = mpd.search_results.artists[0] return val libPosToArr = (lib_pos) -> [lib_pos.artist?.pos, lib_pos.album?.pos, lib_pos.track?.pos] # modifies in place prevLibPos = (lib_pos) -> if lib_pos.track? lib_pos.track = lib_pos.track.album.tracks[lib_pos.track.pos - 1] else if lib_pos.album? lib_pos.album = lib_pos.artist.albums[lib_pos.album.pos - 1] if lib_pos.album? and isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[lib_pos.album.tracks.length - 1] else if lib_pos.artist? lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos - 1] if lib_pos.artist? and isArtistExpanded(lib_pos.artist) lib_pos.album = lib_pos.artist.albums[lib_pos.artist.albums.length - 1] if lib_pos.album? and isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[lib_pos.album.tracks.length - 1] # modifies in place nextLibPos = (lib_pos) -> if lib_pos.track? lib_pos.track = lib_pos.track.album.tracks[lib_pos.track.pos + 1] if not lib_pos.track? lib_pos.album = lib_pos.artist.albums[lib_pos.album.pos + 1] if not lib_pos.album? lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] else if lib_pos.album? if isAlbumExpanded(lib_pos.album) lib_pos.track = lib_pos.album.tracks[0] else lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] lib_pos.album = null else if lib_pos.artist? if isArtistExpanded(lib_pos.artist) lib_pos.album = lib_pos.artist.albums[0] else lib_pos.artist = mpd.search_results.artists[lib_pos.artist.pos + 1] selectLibraryPosition = (lib_pos) -> if lib_pos.track? selection.ids.track[lib_pos.track.file] = true else if lib_pos.album? selection.ids.album[lib_pos.album.key] = true else if lib_pos.artist? selection.ids.artist[mpd.artistKey(lib_pos.artist.name)] = true queueFilesPos = -> pos = mpd.playlist.item_list.length return pos unless server_status? for item, i in mpd.playlist.item_list return i if server_status.random_ids[item.id]? queueLibSelection = (event) -> files = selectionToFiles(event.altKey) if event.shiftKey mpd.queueFilesNext files else mpd.queueFiles files, queueFilesPos() return false settings_ui = auth: show_edit: false password: "" sendAuth = -> pass = localStorage.auth_password return unless pass? mpd.authenticate pass, (err) -> if err delete localStorage.auth_password renderSettings() socket.emit 'Password', pass settingsAuthSave = -> settings_ui.auth.show_edit = false $text_box = $("#auth-password") localStorage.auth_password = $text_box.val() # try to auth renderSettings() sendAuth() settingsAuthCancel = -> settings_ui.auth.show_edit = false renderSettings() performDrag = (event, callbacks) -> abortDrag() start_drag_x = event.pageX start_drag_y = event.pageY abortDrag = -> $document .off('mousemove', onDragMove) .off('mouseup', onDragEnd) if started_drag $playlist_items.find(".pl-item").removeClass('border-top').removeClass('border-bottom') started_drag = false abortDrag = -> onDragMove = (event) -> if not started_drag dist = Math.pow(event.pageX - start_drag_x, 2) + Math.pow(event.pageY - start_drag_y, 2) started_drag = true if dist > 64 return unless started_drag result = getDragPosition(event.pageX, event.pageY) $playlist_items.find(".pl-item").removeClass('border-top').removeClass('border-bottom') $("#playlist-track-#{result.track_id}").addClass "border-#{result.direction}" onDragEnd = (event) -> return false unless event.button is 0 if started_drag callbacks.complete getDragPosition(event.pageX, event.pageY), event else callbacks.cancel() abortDrag() $document .on('mousemove', onDragMove) .on('mouseup', onDragEnd) onDragMove event setUpUi = -> $document.on 'mouseover', '.hoverable', (event) -> $(this).addClass "ui-state-hover" $document.on 'mouseout', '.hoverable', (event) -> $(this).removeClass "ui-state-hover" $(".jquery-button").button() $pl_window = $("#playlist-window") $pl_window.on 'click', 'button.clear', -> mpd.clear() $pl_window.on 'click', 'button.shuffle', -> mpd.shuffle() $pl_btn_repeat.on 'click', -> nextRepeatState() $dynamic_mode.on 'click', -> value = $(this).prop("checked") setDynamicMode(value) return false $playlist_items.on 'dblclick', '.pl-item', (event) -> track_id = $(this).data('id') mpd.playId track_id $playlist_items.on 'contextmenu', (event) -> return event.altKey $playlist_items.on 'mousedown', '.pl-item', (event) -> return true if started_drag # if any text box has focus, unfocus it $(document.activeElement).blur() if event.button is 0 event.preventDefault() # selecting / unselecting removeContextMenu() track_id = $(this).data('id') skip_drag = false if not selection.isPlaylist() selection.selectOnly 'playlist', track_id else if event.ctrlKey or event.shiftKey skip_drag = true if event.shiftKey and not event.ctrlKey selection.clear() if event.shiftKey old_pos = if selection.cursor? then mpd.playlist.item_table[selection.cursor].pos else 0 new_pos = mpd.playlist.item_table[track_id].pos for i in [old_pos..new_pos] selection.ids.playlist[mpd.playlist.item_list[i].id] = true else if event.ctrlKey if selection.ids.playlist[track_id]? delete selection.ids.playlist[track_id] else selection.ids.playlist[track_id] = true selection.cursor = track_id else if not selection.ids.playlist[track_id]? selection.selectOnly 'playlist', track_id refreshSelection() # dragging if not skip_drag performDrag event, complete: (result, event) -> delta = top: 0 bottom: 1 new_pos = mpd.playlist.item_table[result.track_id].pos + delta[result.direction] mpd.moveIds (id for id of selection.ids.playlist), new_pos cancel: -> # we didn't end up dragging, select the item selection.selectOnly 'playlist', track_id refreshSelection() else if event.button is 2 return if event.altKey event.preventDefault() # context menu removeContextMenu() track_id = parseInt($(this).data('id')) if not selection.isPlaylist() or not selection.ids.playlist[track_id]? selection.selectOnly 'playlist', track_id refreshSelection() # adds a new context menu to the document context = item: mpd.playlist.item_table[track_id] status: server_status permissions: permissions $(Handlebars.templates.playlist_menu(context)) .appendTo(document.body) $menu = $("#menu") # get the newly created one $menu.offset left: event.pageX+1 top: event.pageY+1 # don't close menu when you click on the area next to a button $menu.on 'mousedown', -> false $menu.on 'click', '.remove', -> handleDeletePressed(false) removeContextMenu() return false $menu.on 'click', '.download', -> removeContextMenu() return true $menu.on 'click', '.delete', -> handleDeletePressed(true) removeContextMenu() return false # don't remove selection in playlist click $playlist_items.on 'mousedown', -> false # delete context menu $document.on 'mousedown', -> removeContextMenu() selection.type = null refreshSelection() $document.on 'keydown', (event) -> if (handler = keyboard_handlers[event.keyCode])? and (not handler.ctrl? or handler.ctrl is event.ctrlKey) and (not handler.alt? or handler.alt is event.altKey) and (not handler.shift? or handler.shift is event.shiftKey) handler.handler event return false return true $library.on 'mousedown', 'div.expandable > div.ui-icon', (event) -> toggleExpansion $(this).closest("li") return false # suppress double click on the icon $library.on 'dblclick', 'div.expandable > div.ui-icon', -> false $library.on 'dblclick', 'div.artist, div.album, div.track', queueLibSelection $library.on 'contextmenu', (event) -> return event.altKey libraryMouseDown = (event, sel_name, key) -> # if any text box has focus, unfocus it $(document.activeElement).blur() if event.button is 0 event.preventDefault() removeContextMenu() skip_drag = false if not selection.isLibrary() selection.selectOnly sel_name, key else if event.ctrlKey or event.shiftKey skip_drag = true if event.shiftKey and not event.ctrlKey selection.clear() if event.shiftKey old_pos = getLibSelPos(selection.type, selection.cursor) new_pos = getLibSelPos(sel_name, key) # swap if positions are out of order new_arr = libPosToArr(new_pos) old_arr = libPosToArr(old_pos) [old_pos, new_pos] = [new_pos, old_pos] if Util.compareArrays(old_arr, new_arr) > 0 libraryPositionEqual = (old_pos, new_pos) -> old_arr = libPosToArr(old_pos) new_arr = libPosToArr(new_pos) return Util.compareArrays(old_arr, new_arr) is 0 while old_pos.artist? selectLibraryPosition old_pos break if libraryPositionEqual(old_pos, new_pos) nextLibPos old_pos else if event.ctrlKey if selection.ids[sel_name][key]? delete selection.ids[sel_name][key] else selection.ids[sel_name][key] = true selection.cursor = key selection.type = sel_name else if not selection.ids[sel_name][key]? selection.selectOnly sel_name, key refreshSelection() # dragging if not skip_drag performDrag event, complete: (result, event) -> delta = top: 0 bottom: 1 new_pos = mpd.playlist.item_table[result.track_id].pos + delta[result.direction] files = selectionToFiles(event.altKey) mpd.queueFiles files, new_pos cancel: -> # we didn't end up dragging, select the item selection.selectOnly sel_name, key refreshSelection() else if event.button = 2 return if event.altKey event.preventDefault() removeContextMenu() if not selection.isLibrary() or not selection.ids[sel_name][key]? selection.selectOnly sel_name, key refreshSelection() # adds a new context menu to the document context = status: server_status permissions: permissions if sel_name is 'track' context.track = mpd.search_results.track_table[key] $(Handlebars.templates.library_menu(context)).appendTo(document.body) $menu = $("#menu") # get the newly created one $menu.offset left: event.pageX+1 # +1 so we don't immediately close the menu by clicking it top: event.pageY+1 # don't close menu when you click on the area next to a button $menu.on 'mousedown', -> false $menu.on 'click', '.queue', -> mpd.queueFiles selectionToFiles() removeContextMenu() return false $menu.on 'click', '.queue-next', -> mpd.queueFilesNext selectionToFiles() removeContextMenu() return false $menu.on 'click', '.queue-random', -> mpd.queueFiles selectionToFiles(true) removeContextMenu() return false $menu.on 'click', '.queue-next-random', -> mpd.queueFilesNext selectionToFiles(true) removeContextMenu() return false $menu.on 'click', '.download', -> removeContextMenu() return true $menu.on 'click', '.delete', -> handleDeletePressed(true) removeContextMenu() return false $library.on 'mousedown', '.artist', (event) -> artist_key = mpd.artistKey($(this).find("span").text()) libraryMouseDown event, 'artist', artist_key $library.on 'mousedown', '.album', (event) -> libraryMouseDown event, 'album', $(this).data('key') $library.on 'mousedown', '.track', (event) -> libraryMouseDown event, 'track', $(this).data('file') $library.on 'mousedown', -> false $lib_filter = $("#lib-filter") $lib_filter.on 'keydown', (event) -> event.stopPropagation() switch event.keyCode when 27 # if the box is blank, remove focus if $(event.target).val().length is 0 $(event.target).blur() else # defer the setting of the text box until after the event loop to # work around a firefox bug Util.wait 0, -> $(event.target).val("") mpd.search "" return false when 13 # queue all the search results files = [] for artist in mpd.search_results.artists for album in artist.albums for track in album.tracks files.push track.file if event.altKey Util.shuffle(files) if files.length > 2000 return false unless confirm("You are about to queue #{files.length} songs.") if event.shiftKey mpd.queueFilesNext files else mpd.queueFiles files, queueFilesPos() return false when 40 # down # select the first item in the library selection.selectOnly 'artist', mpd.artistKey(mpd.search_results.artists[0].name) refreshSelection() $lib_filter.blur() return false when 38 # up # select the last item in the library selection.selectOnly 'artist', mpd.artistKey(mpd.search_results.artists[mpd.search_results.artists.length - 1].name) refreshSelection() $lib_filter.blur() return false $lib_filter.on 'keyup', (event) -> mpd.search $(event.target).val() $chat_name_input = $("#chat-name-input") $chat_user_id_span.on 'click', (event) -> $chat_input.attr "disabled", "disabled" chat_name_input_visible = true $chat_name_input.show().val("").focus().select() renderChat() $chat_name_input.on 'keydown', (event) -> event.stopPropagation() if event.keyCode is 27 # cancel done = true else if event.keyCode is 13 # accept done = true setUserName $(event.target).val() if done chat_name_input_visible = false $chat_name_input.hide() $chat_input.removeAttr("disabled").focus().select() renderChat() return false $chat_input = $("#chat-input") $chat_input.on 'keydown', (event) -> event.stopPropagation() if event.keyCode is 27 $(event.target).blur() return false else if event.keyCode is 13 message = $.trim($(event.target).val()) Util.wait 0, -> $(event.target).val("") return false if message is "" unless haveUserName() new_user_name = message NICK = "/nick " if message.substr(0, NICK.length) is NICK new_user_name = message.substr(NICK.length) if new_user_name? setUserName new_user_name return false socket.emit 'Chat', message return false actions = 'toggle': togglePlayback 'prev': -> mpd.prev() 'next': -> mpd.next() 'stop': -> mpd.stop() $nowplaying = $("#nowplaying") for cls, action of actions do (cls, action) -> $nowplaying.on 'mousedown', "li.#{cls}", (event) -> action() return false $track_slider.slider step: 0.0001 min: 0 max: 1 change: (event, ui) -> return if not event.originalEvent? mpd.seek ui.value * mpd.status.time slide: (event, ui) -> $nowplaying_elapsed.html Util.formatTime(ui.value * mpd.status.time) start: (event, ui) -> user_is_seeking = true stop: (event, ui) -> user_is_seeking = false setVol = (event, ui) -> return if not event.originalEvent? mpd.setVolume ui.value $vol_slider.slider step: 0.01 min: 0 max: 1 change: setVol start: (event, ui) -> user_is_volume_sliding = true stop: (event, ui) -> user_is_volume_sliding = false # move the slider along the path Util.schedule 100, updateSliderPos $stream_btn.button icons: primary: "ui-icon-signal-diag" $stream_btn.on 'click', toggleStreamStatus $lib_tabs.on 'mouseover', 'li', (event) -> $(this).addClass 'ui-state-hover' $lib_tabs.on 'mouseout', 'li', (event) -> $(this).removeClass 'ui-state-hover' tabs = [ 'library' 'upload' 'chat' 'settings' ] unselectTabs = -> $lib_tabs.find('li').removeClass 'ui-state-active' for tab in tabs $("##{tab}-tab").hide() clickTab = (name) -> return if name is 'upload' and not server_status?.upload_enabled unselectTabs() $lib_tabs.find("li.#{name}-tab").addClass 'ui-state-active' $("##{name}-tab").show() handleResize() renderChat() if name is 'chat' for tab in tabs do (tab) -> $lib_tabs.on 'click', "li.#{tab}-tab", (event) -> clickTab tab uploader = new qq.FileUploader element: document.getElementById("upload-widget") action: '/upload' encoding: 'multipart' $settings.on 'click', '.signout', (event) -> delete localStorage?.lastfm_username delete localStorage?.lastfm_session_key delete localStorage?.lastfm_scrobbling_on renderSettings() return false $settings.on 'click', '#toggle-scrobble', (event) -> value = $(this).prop("checked") if value msg = 'LastfmScrobblersAdd' localStorage?.lastfm_scrobbling_on = true else msg = 'LastfmScrobblersRemove' delete localStorage?.lastfm_scrobbling_on params = username: localStorage?.lastfm_username session_key: localStorage?.lastfm_session_key socket.emit msg, JSON.stringify(params) renderSettings() return false $settings.on 'click', '.auth-edit', (event) -> settings_ui.auth.show_edit = true renderSettings() $text_box = $("#auth-password") $text_box.focus().val(localStorage.auth_password ? "").select() $settings.on 'click', '.auth-clear', (event) -> delete localStorage.auth_password settings_ui.auth.password = "" renderSettings() $settings.on 'click', '.auth-save', (event) -> settingsAuthSave() $settings.on 'click', '.auth-cancel', (event) -> settingsAuthCancel() $settings.on 'keydown', '#auth-password', (event) -> $text_box = $(this) event.stopPropagation() settings_ui.auth.password = $text_box.val() if event.which is 27 settingsAuthCancel() else if event.which is 13 settingsAuthSave() $settings.on 'keyup', '#auth-password', (event) -> settings_ui.auth.password = $(this).val() $upload_by_url.on 'keydown', (event) -> event.stopPropagation() if event.which is 27 $upload_by_url.val("").blur() else if event.which is 13 url = $upload_by_url.val() $upload_by_url.val("").blur() socket.emit 'ImportTrackUrl', url # end setUpUi initHandlebars = -> Handlebars.registerHelper 'time', Util.formatTime Handlebars.registerHelper 'artistid', (s) -> "lib-artist-#{Util.toHtmlId(mpd.artistKey(s))}" Handlebars.registerHelper 'albumid', (s) -> "lib-album-#{Util.toHtmlId(s)}" Handlebars.registerHelper 'trackid', (s) -> "lib-track-#{Util.toHtmlId(s)}" handleResize = -> $nowplaying = $("#nowplaying") $left_window = $("#left-window") $pl_window = $("#playlist-window") # go really small to make the window as small as possible $nowplaying.width MARGIN $pl_window.height MARGIN $left_window.height MARGIN # then fit back up to the window $nowplaying.width $document.width() - MARGIN * 2 second_layer_top = $nowplaying.offset().top + $nowplaying.height() + MARGIN $left_window.offset left: MARGIN top: second_layer_top $pl_window.offset left: $left_window.offset().left + $left_window.width() + MARGIN top: second_layer_top $pl_window.width $(window).width() - $pl_window.offset().left - MARGIN $left_window.height $(window).height() - $left_window.offset().top $pl_window.height $left_window.height() - MARGIN # make the inside containers fit $lib_header = $("#library-tab .window-header") $library.height $left_window.height() - $lib_header.position().top - $lib_header.height() - MARGIN tab_contents_height = $left_window.height() - $lib_tabs.height() - MARGIN $("#upload").height tab_contents_height resizeChat() $pl_header = $pl_window.find("#playlist .header") $playlist_items.height $pl_window.height() - $pl_header.position().top - $pl_header.height() resizeChat = -> height_overshoot = $("#chat-tab").height() - $("#upload").height() $chat_list.height $chat_list.height() - height_overshoot initStreaming = -> soundManager.setup url: "/vendor/soundmanager2/" flashVersion: 9 debugMode: false window.WEB_SOCKET_SWF_LOCATION = "/vendor/socket.io/WebSocketMain.swf" $document.ready -> if localStorage?.my_user_ids? my_user_ids = JSON.parse localStorage.my_user_ids socket = io.connect() # special case when we get the callback from Last.fm. # tell the server the token and save the session in localStorage. # then refresh but remove the "?token=*" from the URL. if (token = Util.parseQuery(location.search.substring(1))?.token)? socket.emit 'LastfmGetSession', token refreshPage = -> location.href = "#{location.protocol}//#{location.host}/" socket.on 'LastfmGetSessionSuccess', (data) -> params = JSON.parse(data) localStorage?.lastfm_username = params.session.name localStorage?.lastfm_session_key = params.session.key delete localStorage?.lastfm_scrobbling_on refreshPage() socket.on 'LastfmGetSessionError', (data) -> params = JSON.parse(data) alert "Error authenticating: #{params.message}" refreshPage() return socket.on 'connect', -> load_status = LoadStatus.NoMpd render() socket.on 'Identify', (data) -> my_user_id = data.toString() my_user_ids[my_user_id] = 1 storeMyUserIds() if (user_name = localStorage?.user_name)? setUserName user_name socket.on 'Permissions', (data) -> permissions = JSON.parse data.toString() renderSettings() socket.on 'Status', (data) -> server_status = JSON.parse data.toString() storeMyUserIds() renderPlaylistButtons() renderChat() labelPlaylistItems() renderSettings() window._debug_server_status = server_status mpd = new window.SocketMpd socket mpd.on 'libraryupdate', renderLibrary mpd.on 'playlistupdate', renderPlaylist mpd.on 'statusupdate', -> renderNowPlaying() renderPlaylistButtons() labelPlaylistItems() updateStreamingPlayer() mpd.on 'chat', renderChat mpd.on 'connect', -> sendAuth() load_status = LoadStatus.GoodToGo render() socket.on 'disconnect', -> load_status = LoadStatus.NoServer render() socket.on 'MpdDisconnect', -> load_status = LoadStatus.NoMpd render() setUpUi() initHandlebars() initStreaming() render() # do this last so that everything becomes the correct size. $(window).resize handleResize window._debug_mpd = mpd
[ { "context": "ideas turned into conventions and packages.\n \n - Ted Nelson\n\"\"\"\npublish:\n s3:\n basePath: \"public\"\ndepende", "end": 338, "score": 0.9998284578323364, "start": 328, "tag": "NAME", "value": "Ted Nelson" } ]
pixie.cson
STRd6/zine
12
title: "Whimsy Space - ZineOS v0.420.950a ⌊ALPHA⌉" version: "0.420.950a" description: """ I have long been alarmed by people’s sheeplike acceptance of the term ‘computer technology’ — it sounds so objective and inexorable — when most computer technology is really a bunch of ideas turned into conventions and packages. - Ted Nelson """ publish: s3: basePath: "public" dependencies: ajax: "distri/ajax:master" analytics: "distri/google-analytics:master" bindable: "distri/bindable:master" model: "distri/model:master" postmaster: "distri/postmaster:v0.6.0" ui: "STRd6/ui:master" "!system": "STRd6/system-client:master" remoteDependencies: [ "https://cdnjs.cloudflare.com/ajax/libs/dexie/2.0.0-beta.7/dexie.min.js" "https://cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min.js" "https://danielx.whimsy.space/cdn/cognito/sdk.min.js" "https://danielx.whimsy.space/cdn/cognito/identity.min.js" "https://sdk.amazonaws.com/js/aws-sdk-2.7.20.min.js" "https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js" ]
91900
title: "Whimsy Space - ZineOS v0.420.950a ⌊ALPHA⌉" version: "0.420.950a" description: """ I have long been alarmed by people’s sheeplike acceptance of the term ‘computer technology’ — it sounds so objective and inexorable — when most computer technology is really a bunch of ideas turned into conventions and packages. - <NAME> """ publish: s3: basePath: "public" dependencies: ajax: "distri/ajax:master" analytics: "distri/google-analytics:master" bindable: "distri/bindable:master" model: "distri/model:master" postmaster: "distri/postmaster:v0.6.0" ui: "STRd6/ui:master" "!system": "STRd6/system-client:master" remoteDependencies: [ "https://cdnjs.cloudflare.com/ajax/libs/dexie/2.0.0-beta.7/dexie.min.js" "https://cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min.js" "https://danielx.whimsy.space/cdn/cognito/sdk.min.js" "https://danielx.whimsy.space/cdn/cognito/identity.min.js" "https://sdk.amazonaws.com/js/aws-sdk-2.7.20.min.js" "https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js" ]
true
title: "Whimsy Space - ZineOS v0.420.950a ⌊ALPHA⌉" version: "0.420.950a" description: """ I have long been alarmed by people’s sheeplike acceptance of the term ‘computer technology’ — it sounds so objective and inexorable — when most computer technology is really a bunch of ideas turned into conventions and packages. - PI:NAME:<NAME>END_PI """ publish: s3: basePath: "public" dependencies: ajax: "distri/ajax:master" analytics: "distri/google-analytics:master" bindable: "distri/bindable:master" model: "distri/model:master" postmaster: "distri/postmaster:v0.6.0" ui: "STRd6/ui:master" "!system": "STRd6/system-client:master" remoteDependencies: [ "https://cdnjs.cloudflare.com/ajax/libs/dexie/2.0.0-beta.7/dexie.min.js" "https://cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min.js" "https://danielx.whimsy.space/cdn/cognito/sdk.min.js" "https://danielx.whimsy.space/cdn/cognito/identity.min.js" "https://sdk.amazonaws.com/js/aws-sdk-2.7.20.min.js" "https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js" ]
[ { "context": "# entry point of the renderer\n# Copyright (c) 2015 Lu Wang <coolwanglu@gmail.com>\n\nwindow.onload = ->\n try\n", "end": 72, "score": 0.9967571496963501, "start": 65, "tag": "NAME", "value": "Lu Wang" }, { "context": "int of the renderer\n# Copyright (c) 2015 Lu Wang ...
src/nvim/main.coffee
coolwanglu/neovim-e
252
# main.coffee # entry point of the renderer # Copyright (c) 2015 Lu Wang <coolwanglu@gmail.com> window.onload = -> try window.nvim = new (require('./nvim/nvim'))() catch error win = require('remote').getCurrentWindow() win.setSize 800, 600 win.center() win.show() win.openDevTools() console.log error.stack ? error
77364
# main.coffee # entry point of the renderer # Copyright (c) 2015 <NAME> <<EMAIL>> window.onload = -> try window.nvim = new (require('./nvim/nvim'))() catch error win = require('remote').getCurrentWindow() win.setSize 800, 600 win.center() win.show() win.openDevTools() console.log error.stack ? error
true
# main.coffee # entry point of the renderer # Copyright (c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> window.onload = -> try window.nvim = new (require('./nvim/nvim'))() catch error win = require('remote').getCurrentWindow() win.setSize 800, 600 win.center() win.show() win.openDevTools() console.log error.stack ? error
[ { "context": "\"Todd\"]', (done) ->\n l = new ALINQ [{first: \"Max\", last: \"Su\"}, {first: \"Todd\", last: \"Su\"}]\n ", "end": 4465, "score": 0.9854798316955566, "start": 4462, "tag": "NAME", "value": "Max" }, { "context": "ne) ->\n l = new ALINQ [{first: \"Max\", la...
node_modules/node-linq/test/ALINQ.coffee
wleorule/CloudBox
1
{ALINQ} = require '../' should = require 'should' require 'mocha' describe 'indexes', -> describe 'Count()', -> it 'should return 5', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Count().Execute (val) -> val.should.equal 5 done() it 'should return 0', (done) -> l = new ALINQ [] l.Count().Execute (val) -> val.should.equal 0 done() describe 'ElementAt()', -> it 'should return 3', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAt(2).Execute (val) -> val.should.equal 3 done() describe 'ElementAtOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAtOrDefault(2).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAtOrDefault(9001, 7).Execute (val) -> val.should.equal 7 done() describe 'Single()', -> it 'should return 3', (done) -> l = new ALINQ [3] l.Single().Execute (val) -> val.should.equal 3 done() describe 'SingleOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3] l.SingleOrDefault(7).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [] l.SingleOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'First()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.First().Execute (val) -> val.should.equal 3 done() describe 'FirstOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.FirstOrDefault(7).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [] l.FirstOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'Last()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.Last().Execute (val) -> val.should.equal 5 done() describe 'LastOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.LastOrDefault(7).Execute (val) -> val.should.equal 5 done() it 'should return 7', (done) -> l = new ALINQ [] l.LastOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'DefaultIfEmpty()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.DefaultIfEmpty(7).Execute (val) -> val.should.eql [3, 4, 5] done() it 'should return 7', (done) -> l = new ALINQ [] l.DefaultIfEmpty(7).Execute (val) -> val.should.equal 7 done() describe 'selects', -> describe 'Where()', -> it 'should return [3, 4, 5]', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Where((num, cb) -> cb num > 2).Execute (val) -> val.should.eql [3, 4, 5] done() describe 'Distinct()', -> it 'should return [1, 2, 3, 4, 5]', (done) -> l = new ALINQ [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] l.Distinct().Execute (val) -> val.should.eql [1, 2, 3, 4, 5] done() describe 'Except()', -> it 'should return [6]', (done) -> except = [1, 2, 3, 4, 5] l = new ALINQ [1, 2, 3, 4, 5, 6] l.Except(except).Execute (val) -> val.should.eql [6] done() it 'should return [6] with selector', (done) -> except = [1, 2, 3, 4, 5] l = new ALINQ [1, 2, 3, 4, 5, 6] sel = (i) -> i l.Except(except, sel).Execute (val) -> val.should.eql [6] done() describe 'OfType()', -> it 'should return [6]', (done) -> l = new ALINQ ['str', {}, null, 6] l.OfType('number').Execute (val) -> val.should.eql [6] done() it 'should return ["str"]', (done) -> l = new ALINQ ['str', {}, null, 6] l.OfType('string').Execute (val) -> val.should.eql ['str'] done() describe 'Cast()', -> it 'should return [6, 6]', (done) -> l = new ALINQ ['6', 6] l.Cast(parseInt).Execute (val) -> val.should.eql [6, 6] done() it 'should return ["6", "6"]', (done) -> l = new ALINQ ['6', 6] l.Cast(String).Execute (val) -> val.should.eql ['6', '6'] done() describe 'Select()', -> it 'should return ["Max", "Todd"]', (done) -> l = new ALINQ [{first: "Max", last: "Su"}, {first: "Todd", last: "Su"}] expected = ["Max", "Todd"] l.Select((item, cb) -> cb item.first).Execute (val) -> val.should.eql expected done() describe 'SelectMany()', -> it 'should return ["Max", "Todd"]', (done) -> l = new ALINQ [{first: "Max", last: "Su"}, {first: "Todd", last: "Su"}] expected = ["Max", "Su", "Todd", "Su"] l.SelectMany((item, cb) -> cb [item.first, item.last]).Execute (val) -> val.should.eql expected done() describe 'computation', -> describe 'Max()', -> it 'should return 5', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Max().Execute (val) -> val.should.equal 5 done() describe 'Min()', -> it 'should return 1', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Min().Execute (val) -> val.should.equal 1 done() describe 'Sum()', -> it 'should return 6', (done) -> l = new ALINQ [1, 2, 3] l.Sum().Execute (val) -> val.should.equal 6 done() describe 'Average()', -> it 'should return 2', (done) -> l = new ALINQ [1, 2, 3] l.Average().Execute (val) -> val.should.equal 2 done() describe 'ordering', -> describe 'Reverse()', -> it 'should return [3, 2, 1]', (done) -> l = new ALINQ [1, 2, 3] expected = [3, 2, 1] l.Reverse().Execute (val) -> val.should.eql expected done() describe 'OrderBy()', -> it 'should return ["Amanda", "Todd"]', (done) -> l = new ALINQ [{name: "Todd"}, {name: "Amanda"}] expected = [{name: "Amanda"}, {name: "Todd"}] l.OrderBy((item, cb) -> cb item.name).Execute (val) -> val.should.eql expected done() describe 'OrderByDescending()', -> it 'should return ["Todd", "Amanda"]', (done) -> l = new ALINQ [{name: "Amanda"}, {name: "Todd"}] expected = [{name: "Todd"}, {name: "Amanda"}] l.OrderByDescending((item, cb) -> cb item.name).Execute (val) -> val.should.eql expected done() describe 'conditions', -> describe 'Contains()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.Contains(1).Execute (val) -> val.should.equal true done() describe 'Contains()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.Contains(4).Execute (val) -> val.should.equal false done() describe 'Any()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.Any((item, cb) -> cb item is 1).Execute (val) -> val.should.equal true done() describe 'Any()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.Any((item, cb) -> cb item is 4).Execute (val) -> val.should.equal false done() describe 'All()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.All((item, cb) -> cb item > 0).Execute (val) -> val.should.equal true done() describe 'All()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.All((item, cb) -> cb item > 10).Execute (val) -> val.should.equal false done() describe 'modifications', -> describe 'Concat()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l2 = new ALINQ [1, 2, 3] expected = [1, 2, 3, 1, 2, 3] l.Concat(l2).Execute (val) -> val.should.eql expected done() describe 'Intersect()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3, 4] l2 = new ALINQ [1, 2, 3, 5] expected = [1, 2, 3] l.Intersect(l2).Execute (val) -> val.should.eql expected done() describe 'chaining', -> describe 'dogs and puppies', -> it 'should return correct', (done) -> dogs = [ {name: 'Toby', age: 2, type: 'Yorkie'}, {name: 'Max', age: 3, type: 'Labrador'}, {name: 'Lil Billy', age: 4, type: 'Labrador'}, {name: 'Choni', age: 5, type: 'Poodle'} ] puppies = [ {name: 'T-Bone', age: 1, type: 'Yorkie'}, {name: 'Lil Chili', age: 1, type: 'Labrador'} ] arr = new ALINQ(dogs) .Concat(puppies) .Where((dog, cb) -> cb dog.type is 'Labrador') .OrderBy((dog, cb) -> cb dog.age) .Select((dog, cb) -> cb dog.name) .Execute (arr) -> arr.should.eql [ 'Lil Chili', 'Max', 'Lil Billy' ] done()
67759
{ALINQ} = require '../' should = require 'should' require 'mocha' describe 'indexes', -> describe 'Count()', -> it 'should return 5', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Count().Execute (val) -> val.should.equal 5 done() it 'should return 0', (done) -> l = new ALINQ [] l.Count().Execute (val) -> val.should.equal 0 done() describe 'ElementAt()', -> it 'should return 3', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAt(2).Execute (val) -> val.should.equal 3 done() describe 'ElementAtOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAtOrDefault(2).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAtOrDefault(9001, 7).Execute (val) -> val.should.equal 7 done() describe 'Single()', -> it 'should return 3', (done) -> l = new ALINQ [3] l.Single().Execute (val) -> val.should.equal 3 done() describe 'SingleOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3] l.SingleOrDefault(7).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [] l.SingleOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'First()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.First().Execute (val) -> val.should.equal 3 done() describe 'FirstOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.FirstOrDefault(7).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [] l.FirstOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'Last()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.Last().Execute (val) -> val.should.equal 5 done() describe 'LastOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.LastOrDefault(7).Execute (val) -> val.should.equal 5 done() it 'should return 7', (done) -> l = new ALINQ [] l.LastOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'DefaultIfEmpty()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.DefaultIfEmpty(7).Execute (val) -> val.should.eql [3, 4, 5] done() it 'should return 7', (done) -> l = new ALINQ [] l.DefaultIfEmpty(7).Execute (val) -> val.should.equal 7 done() describe 'selects', -> describe 'Where()', -> it 'should return [3, 4, 5]', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Where((num, cb) -> cb num > 2).Execute (val) -> val.should.eql [3, 4, 5] done() describe 'Distinct()', -> it 'should return [1, 2, 3, 4, 5]', (done) -> l = new ALINQ [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] l.Distinct().Execute (val) -> val.should.eql [1, 2, 3, 4, 5] done() describe 'Except()', -> it 'should return [6]', (done) -> except = [1, 2, 3, 4, 5] l = new ALINQ [1, 2, 3, 4, 5, 6] l.Except(except).Execute (val) -> val.should.eql [6] done() it 'should return [6] with selector', (done) -> except = [1, 2, 3, 4, 5] l = new ALINQ [1, 2, 3, 4, 5, 6] sel = (i) -> i l.Except(except, sel).Execute (val) -> val.should.eql [6] done() describe 'OfType()', -> it 'should return [6]', (done) -> l = new ALINQ ['str', {}, null, 6] l.OfType('number').Execute (val) -> val.should.eql [6] done() it 'should return ["str"]', (done) -> l = new ALINQ ['str', {}, null, 6] l.OfType('string').Execute (val) -> val.should.eql ['str'] done() describe 'Cast()', -> it 'should return [6, 6]', (done) -> l = new ALINQ ['6', 6] l.Cast(parseInt).Execute (val) -> val.should.eql [6, 6] done() it 'should return ["6", "6"]', (done) -> l = new ALINQ ['6', 6] l.Cast(String).Execute (val) -> val.should.eql ['6', '6'] done() describe 'Select()', -> it 'should return ["Max", "Todd"]', (done) -> l = new ALINQ [{first: "<NAME>", last: "<NAME>"}, {first: "<NAME>", last: "<NAME>"}] expected = ["Max", "Todd"] l.Select((item, cb) -> cb item.first).Execute (val) -> val.should.eql expected done() describe 'SelectMany()', -> it 'should return ["<NAME>", "<NAME>"]', (done) -> l = new ALINQ [{first: "<NAME>", last: "<NAME>"}, {first: "<NAME>", last: "<NAME>"}] expected = ["<NAME>", "Su", "Todd", "Su"] l.SelectMany((item, cb) -> cb [item.first, item.last]).Execute (val) -> val.should.eql expected done() describe 'computation', -> describe 'Max()', -> it 'should return 5', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Max().Execute (val) -> val.should.equal 5 done() describe 'Min()', -> it 'should return 1', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Min().Execute (val) -> val.should.equal 1 done() describe 'Sum()', -> it 'should return 6', (done) -> l = new ALINQ [1, 2, 3] l.Sum().Execute (val) -> val.should.equal 6 done() describe 'Average()', -> it 'should return 2', (done) -> l = new ALINQ [1, 2, 3] l.Average().Execute (val) -> val.should.equal 2 done() describe 'ordering', -> describe 'Reverse()', -> it 'should return [3, 2, 1]', (done) -> l = new ALINQ [1, 2, 3] expected = [3, 2, 1] l.Reverse().Execute (val) -> val.should.eql expected done() describe 'OrderBy()', -> it 'should return ["<NAME>", "<NAME>"]', (done) -> l = new ALINQ [{name: "<NAME>"}, {name: "<NAME>"}] expected = [{name: "<NAME>"}, {name: "<NAME>"}] l.OrderBy((item, cb) -> cb item.name).Execute (val) -> val.should.eql expected done() describe 'OrderByDescending()', -> it 'should return ["<NAME>", "<NAME>"]', (done) -> l = new ALINQ [{name: "<NAME>"}, {name: "<NAME>"}] expected = [{name: "<NAME>"}, {name: "<NAME>"}] l.OrderByDescending((item, cb) -> cb item.name).Execute (val) -> val.should.eql expected done() describe 'conditions', -> describe 'Contains()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.Contains(1).Execute (val) -> val.should.equal true done() describe 'Contains()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.Contains(4).Execute (val) -> val.should.equal false done() describe 'Any()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.Any((item, cb) -> cb item is 1).Execute (val) -> val.should.equal true done() describe 'Any()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.Any((item, cb) -> cb item is 4).Execute (val) -> val.should.equal false done() describe 'All()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.All((item, cb) -> cb item > 0).Execute (val) -> val.should.equal true done() describe 'All()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.All((item, cb) -> cb item > 10).Execute (val) -> val.should.equal false done() describe 'modifications', -> describe 'Concat()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l2 = new ALINQ [1, 2, 3] expected = [1, 2, 3, 1, 2, 3] l.Concat(l2).Execute (val) -> val.should.eql expected done() describe 'Intersect()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3, 4] l2 = new ALINQ [1, 2, 3, 5] expected = [1, 2, 3] l.Intersect(l2).Execute (val) -> val.should.eql expected done() describe 'chaining', -> describe 'dogs and puppies', -> it 'should return correct', (done) -> dogs = [ {name: '<NAME>', age: 2, type: 'Yorkie'}, {name: '<NAME>', age: 3, type: 'Labrador'}, {name: '<NAME>', age: 4, type: 'Labrador'}, {name: '<NAME>', age: 5, type: 'Poodle'} ] puppies = [ {name: '<NAME>', age: 1, type: 'Yorkie'}, {name: '<NAME>', age: 1, type: 'Labrador'} ] arr = new ALINQ(dogs) .Concat(puppies) .Where((dog, cb) -> cb dog.type is 'Labrador') .OrderBy((dog, cb) -> cb dog.age) .Select((dog, cb) -> cb dog.name) .Execute (arr) -> arr.should.eql [ '<NAME>', '<NAME>', '<NAME>' ] done()
true
{ALINQ} = require '../' should = require 'should' require 'mocha' describe 'indexes', -> describe 'Count()', -> it 'should return 5', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Count().Execute (val) -> val.should.equal 5 done() it 'should return 0', (done) -> l = new ALINQ [] l.Count().Execute (val) -> val.should.equal 0 done() describe 'ElementAt()', -> it 'should return 3', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAt(2).Execute (val) -> val.should.equal 3 done() describe 'ElementAtOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAtOrDefault(2).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [1, 2, 3, 4] l.ElementAtOrDefault(9001, 7).Execute (val) -> val.should.equal 7 done() describe 'Single()', -> it 'should return 3', (done) -> l = new ALINQ [3] l.Single().Execute (val) -> val.should.equal 3 done() describe 'SingleOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3] l.SingleOrDefault(7).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [] l.SingleOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'First()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.First().Execute (val) -> val.should.equal 3 done() describe 'FirstOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.FirstOrDefault(7).Execute (val) -> val.should.equal 3 done() it 'should return 7', (done) -> l = new ALINQ [] l.FirstOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'Last()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.Last().Execute (val) -> val.should.equal 5 done() describe 'LastOrDefault()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.LastOrDefault(7).Execute (val) -> val.should.equal 5 done() it 'should return 7', (done) -> l = new ALINQ [] l.LastOrDefault(7).Execute (val) -> val.should.equal 7 done() describe 'DefaultIfEmpty()', -> it 'should return 3', (done) -> l = new ALINQ [3, 4, 5] l.DefaultIfEmpty(7).Execute (val) -> val.should.eql [3, 4, 5] done() it 'should return 7', (done) -> l = new ALINQ [] l.DefaultIfEmpty(7).Execute (val) -> val.should.equal 7 done() describe 'selects', -> describe 'Where()', -> it 'should return [3, 4, 5]', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Where((num, cb) -> cb num > 2).Execute (val) -> val.should.eql [3, 4, 5] done() describe 'Distinct()', -> it 'should return [1, 2, 3, 4, 5]', (done) -> l = new ALINQ [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] l.Distinct().Execute (val) -> val.should.eql [1, 2, 3, 4, 5] done() describe 'Except()', -> it 'should return [6]', (done) -> except = [1, 2, 3, 4, 5] l = new ALINQ [1, 2, 3, 4, 5, 6] l.Except(except).Execute (val) -> val.should.eql [6] done() it 'should return [6] with selector', (done) -> except = [1, 2, 3, 4, 5] l = new ALINQ [1, 2, 3, 4, 5, 6] sel = (i) -> i l.Except(except, sel).Execute (val) -> val.should.eql [6] done() describe 'OfType()', -> it 'should return [6]', (done) -> l = new ALINQ ['str', {}, null, 6] l.OfType('number').Execute (val) -> val.should.eql [6] done() it 'should return ["str"]', (done) -> l = new ALINQ ['str', {}, null, 6] l.OfType('string').Execute (val) -> val.should.eql ['str'] done() describe 'Cast()', -> it 'should return [6, 6]', (done) -> l = new ALINQ ['6', 6] l.Cast(parseInt).Execute (val) -> val.should.eql [6, 6] done() it 'should return ["6", "6"]', (done) -> l = new ALINQ ['6', 6] l.Cast(String).Execute (val) -> val.should.eql ['6', '6'] done() describe 'Select()', -> it 'should return ["Max", "Todd"]', (done) -> l = new ALINQ [{first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI"}, {first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI"}] expected = ["Max", "Todd"] l.Select((item, cb) -> cb item.first).Execute (val) -> val.should.eql expected done() describe 'SelectMany()', -> it 'should return ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]', (done) -> l = new ALINQ [{first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI"}, {first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI"}] expected = ["PI:NAME:<NAME>END_PI", "Su", "Todd", "Su"] l.SelectMany((item, cb) -> cb [item.first, item.last]).Execute (val) -> val.should.eql expected done() describe 'computation', -> describe 'Max()', -> it 'should return 5', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Max().Execute (val) -> val.should.equal 5 done() describe 'Min()', -> it 'should return 1', (done) -> l = new ALINQ [1, 2, 3, 4, 5] l.Min().Execute (val) -> val.should.equal 1 done() describe 'Sum()', -> it 'should return 6', (done) -> l = new ALINQ [1, 2, 3] l.Sum().Execute (val) -> val.should.equal 6 done() describe 'Average()', -> it 'should return 2', (done) -> l = new ALINQ [1, 2, 3] l.Average().Execute (val) -> val.should.equal 2 done() describe 'ordering', -> describe 'Reverse()', -> it 'should return [3, 2, 1]', (done) -> l = new ALINQ [1, 2, 3] expected = [3, 2, 1] l.Reverse().Execute (val) -> val.should.eql expected done() describe 'OrderBy()', -> it 'should return ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]', (done) -> l = new ALINQ [{name: "PI:NAME:<NAME>END_PI"}, {name: "PI:NAME:<NAME>END_PI"}] expected = [{name: "PI:NAME:<NAME>END_PI"}, {name: "PI:NAME:<NAME>END_PI"}] l.OrderBy((item, cb) -> cb item.name).Execute (val) -> val.should.eql expected done() describe 'OrderByDescending()', -> it 'should return ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]', (done) -> l = new ALINQ [{name: "PI:NAME:<NAME>END_PI"}, {name: "PI:NAME:<NAME>END_PI"}] expected = [{name: "PI:NAME:<NAME>END_PI"}, {name: "PI:NAME:<NAME>END_PI"}] l.OrderByDescending((item, cb) -> cb item.name).Execute (val) -> val.should.eql expected done() describe 'conditions', -> describe 'Contains()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.Contains(1).Execute (val) -> val.should.equal true done() describe 'Contains()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.Contains(4).Execute (val) -> val.should.equal false done() describe 'Any()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.Any((item, cb) -> cb item is 1).Execute (val) -> val.should.equal true done() describe 'Any()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.Any((item, cb) -> cb item is 4).Execute (val) -> val.should.equal false done() describe 'All()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l.All((item, cb) -> cb item > 0).Execute (val) -> val.should.equal true done() describe 'All()', -> it 'should return false', (done) -> l = new ALINQ [1, 2, 3] l.All((item, cb) -> cb item > 10).Execute (val) -> val.should.equal false done() describe 'modifications', -> describe 'Concat()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3] l2 = new ALINQ [1, 2, 3] expected = [1, 2, 3, 1, 2, 3] l.Concat(l2).Execute (val) -> val.should.eql expected done() describe 'Intersect()', -> it 'should return true', (done) -> l = new ALINQ [1, 2, 3, 4] l2 = new ALINQ [1, 2, 3, 5] expected = [1, 2, 3] l.Intersect(l2).Execute (val) -> val.should.eql expected done() describe 'chaining', -> describe 'dogs and puppies', -> it 'should return correct', (done) -> dogs = [ {name: 'PI:NAME:<NAME>END_PI', age: 2, type: 'Yorkie'}, {name: 'PI:NAME:<NAME>END_PI', age: 3, type: 'Labrador'}, {name: 'PI:NAME:<NAME>END_PI', age: 4, type: 'Labrador'}, {name: 'PI:NAME:<NAME>END_PI', age: 5, type: 'Poodle'} ] puppies = [ {name: 'PI:NAME:<NAME>END_PI', age: 1, type: 'Yorkie'}, {name: 'PI:NAME:<NAME>END_PI', age: 1, type: 'Labrador'} ] arr = new ALINQ(dogs) .Concat(puppies) .Where((dog, cb) -> cb dog.type is 'Labrador') .OrderBy((dog, cb) -> cb dog.age) .Select((dog, cb) -> cb dog.name) .Execute (arr) -> arr.should.eql [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' ] done()
[ { "context": "p, value } = metric\n ws.write\n key: \"metrics:#{id}:#{timestamp}\"\n value: value\n ws.end()\n", "end": 1783, "score": 0.9066787362098694, "start": 1756, "tag": "KEY", "value": "metrics:#{id}:#{timestamp}\"" } ]
src/metrics.coffee
charlo06/ast_final_project
0
level = require 'level' levelws = require 'level-ws' db = levelws level "#{__dirname}/../db" module.exports = # get(id, callback) # Get metrics # - id: metric's id # - callback: the callback function, callback(err, data) get: (callback) -> res = [] rs = db.createReadStream() # on data and if correct id, add the data to the result array rs.on 'data', (data) -> [ ..., dataId, dataTimestamp ] = data.key.split ":" # if corresponding id # push new object with id, timestamp and value properties res.push id: dataId timestamp: dataTimestamp value: data.value rs.on 'error', (err) -> callback err # on stream end, return the result rs.on 'end', () -> callback null, res getbyid: (id, callback) -> # result array res = [] rs = db.createReadStream() console.log(id) # on data and if correct id, add the data to the result array rs.on 'data', (data) -> [ ..., dataId, dataTimestamp ] = data.key.split ":" # if corresponding id if dataId == id # push new object with id, timestamp and value properties res.push id: dataId timestamp: dataTimestamp value: data.value rs.on 'error', (err) -> callback err # on stream end, return the result rs.on 'end', () -> callback null, res # save(id, metrics, callback) # Save given metrics # - id: metric id # - metrics: an array of { timestamp, value } # - callback: the callback function save: (id, metrics, callback) -> ws = db.createWriteStream() ws.on 'error', callback ws.on 'close', callback console.log(metrics) for metric in metrics { timestamp, value } = metric ws.write key: "metrics:#{id}:#{timestamp}" value: value ws.end()
172421
level = require 'level' levelws = require 'level-ws' db = levelws level "#{__dirname}/../db" module.exports = # get(id, callback) # Get metrics # - id: metric's id # - callback: the callback function, callback(err, data) get: (callback) -> res = [] rs = db.createReadStream() # on data and if correct id, add the data to the result array rs.on 'data', (data) -> [ ..., dataId, dataTimestamp ] = data.key.split ":" # if corresponding id # push new object with id, timestamp and value properties res.push id: dataId timestamp: dataTimestamp value: data.value rs.on 'error', (err) -> callback err # on stream end, return the result rs.on 'end', () -> callback null, res getbyid: (id, callback) -> # result array res = [] rs = db.createReadStream() console.log(id) # on data and if correct id, add the data to the result array rs.on 'data', (data) -> [ ..., dataId, dataTimestamp ] = data.key.split ":" # if corresponding id if dataId == id # push new object with id, timestamp and value properties res.push id: dataId timestamp: dataTimestamp value: data.value rs.on 'error', (err) -> callback err # on stream end, return the result rs.on 'end', () -> callback null, res # save(id, metrics, callback) # Save given metrics # - id: metric id # - metrics: an array of { timestamp, value } # - callback: the callback function save: (id, metrics, callback) -> ws = db.createWriteStream() ws.on 'error', callback ws.on 'close', callback console.log(metrics) for metric in metrics { timestamp, value } = metric ws.write key: "<KEY> value: value ws.end()
true
level = require 'level' levelws = require 'level-ws' db = levelws level "#{__dirname}/../db" module.exports = # get(id, callback) # Get metrics # - id: metric's id # - callback: the callback function, callback(err, data) get: (callback) -> res = [] rs = db.createReadStream() # on data and if correct id, add the data to the result array rs.on 'data', (data) -> [ ..., dataId, dataTimestamp ] = data.key.split ":" # if corresponding id # push new object with id, timestamp and value properties res.push id: dataId timestamp: dataTimestamp value: data.value rs.on 'error', (err) -> callback err # on stream end, return the result rs.on 'end', () -> callback null, res getbyid: (id, callback) -> # result array res = [] rs = db.createReadStream() console.log(id) # on data and if correct id, add the data to the result array rs.on 'data', (data) -> [ ..., dataId, dataTimestamp ] = data.key.split ":" # if corresponding id if dataId == id # push new object with id, timestamp and value properties res.push id: dataId timestamp: dataTimestamp value: data.value rs.on 'error', (err) -> callback err # on stream end, return the result rs.on 'end', () -> callback null, res # save(id, metrics, callback) # Save given metrics # - id: metric id # - metrics: an array of { timestamp, value } # - callback: the callback function save: (id, metrics, callback) -> ws = db.createWriteStream() ws.on 'error', callback ws.on 'close', callback console.log(metrics) for metric in metrics { timestamp, value } = metric ws.write key: "PI:KEY:<KEY>END_PI value: value ws.end()
[ { "context": "##\n * Federated Wiki : Node Server\n *\n * Copyright Ward Cunningham and other contributors\n * Licensed under the MIT ", "end": 67, "score": 0.9998735189437866, "start": 52, "tag": "NAME", "value": "Ward Cunningham" }, { "context": "nsed under the MIT license.\n * htt...
node_modules/wiki-server/lib/defaultargs.coffee
jpietrok-pnnl/wiki
0
### * Federated Wiki : Node Server * * Copyright Ward Cunningham and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki-server/blob/master/LICENSE.txt ### # **defaultargs.coffee** when called on the argv object this # module will create reasonable defaults for options not supplied, # based on what information is provided. path = require 'path' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE module.exports = (argv) -> argv or= {} argv.root or= __dirname # the directory that contains all the packages that makeup the wiki argv.packageDir or= path.join(argv.root, "..") argv.port or= 3000 argv.home or= 'welcome-visitors' argv.data or= path.join(getUserHome(), '.wiki') # see also cli argv.client or= path.join(argv.packageDir, 'wiki-client', 'client') argv.db or= path.join(argv.data, 'pages') argv.status or= path.join(argv.data, 'status') argv.assets or= path.join(argv.data, 'assets') argv.recycle or= path.join(argv.data, 'recycle') argv.url or= 'http://localhost' + (':' + argv.port) unless argv.port is 80 argv.id or= path.join(argv.status, 'owner.json') argv.uploadLimit or= '5mb' argv.cookieSecret or= require('crypto').randomBytes(64).toString('hex') argv.secure_cookie or= false argv.session_duration or= 7 argv.neighbors or= '' argv.debug or= false if typeof(argv.database) is 'string' argv.database = JSON.parse(argv.database) argv.database or= {} argv.database.type or= './page' if argv.database.type.charAt(0) is '.' if argv.database.type != './page' console.log "\n\nWARNING: This storage option is depeciated." console.log " See ReadMe for details of the changes required.\n\n" else argv.database.type = 'wiki-storage-' + argv.database.type argv.security_type or= './security' if argv.security_type is './security' console.log "\n\nWARNING: Using default security module." else argv.security_type = 'wiki-security-' + argv.security_type argv.security_legacy or= false #resolve all relative paths argv.root = path.resolve(argv.root) argv.packageDir = path.resolve(argv.packageDir) argv.data = path.resolve(argv.data) argv.client = path.resolve(argv.client) argv.db = path.resolve(argv.db) argv.status = path.resolve(argv.status) argv.id = path.resolve(argv.id) if /node_modules/.test(argv.data) console.log "\n\nWARNING : The dafault data path is not a safe place." console.log " : by using ", argv.data, " your pages will be lost when packages are updated." console.log " : You are strongly advised to use an alternative directory." console.log " : See the wiki package ReadMe for how to do this.\n\n" argv
157928
### * Federated Wiki : Node Server * * Copyright <NAME> and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki-server/blob/master/LICENSE.txt ### # **defaultargs.coffee** when called on the argv object this # module will create reasonable defaults for options not supplied, # based on what information is provided. path = require 'path' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE module.exports = (argv) -> argv or= {} argv.root or= __dirname # the directory that contains all the packages that makeup the wiki argv.packageDir or= path.join(argv.root, "..") argv.port or= 3000 argv.home or= 'welcome-visitors' argv.data or= path.join(getUserHome(), '.wiki') # see also cli argv.client or= path.join(argv.packageDir, 'wiki-client', 'client') argv.db or= path.join(argv.data, 'pages') argv.status or= path.join(argv.data, 'status') argv.assets or= path.join(argv.data, 'assets') argv.recycle or= path.join(argv.data, 'recycle') argv.url or= 'http://localhost' + (':' + argv.port) unless argv.port is 80 argv.id or= path.join(argv.status, 'owner.json') argv.uploadLimit or= '5mb' argv.cookieSecret or= require('crypto').randomBytes(64).toString('hex') argv.secure_cookie or= false argv.session_duration or= 7 argv.neighbors or= '' argv.debug or= false if typeof(argv.database) is 'string' argv.database = JSON.parse(argv.database) argv.database or= {} argv.database.type or= './page' if argv.database.type.charAt(0) is '.' if argv.database.type != './page' console.log "\n\nWARNING: This storage option is depeciated." console.log " See ReadMe for details of the changes required.\n\n" else argv.database.type = 'wiki-storage-' + argv.database.type argv.security_type or= './security' if argv.security_type is './security' console.log "\n\nWARNING: Using default security module." else argv.security_type = 'wiki-security-' + argv.security_type argv.security_legacy or= false #resolve all relative paths argv.root = path.resolve(argv.root) argv.packageDir = path.resolve(argv.packageDir) argv.data = path.resolve(argv.data) argv.client = path.resolve(argv.client) argv.db = path.resolve(argv.db) argv.status = path.resolve(argv.status) argv.id = path.resolve(argv.id) if /node_modules/.test(argv.data) console.log "\n\nWARNING : The dafault data path is not a safe place." console.log " : by using ", argv.data, " your pages will be lost when packages are updated." console.log " : You are strongly advised to use an alternative directory." console.log " : See the wiki package ReadMe for how to do this.\n\n" argv
true
### * Federated Wiki : Node Server * * Copyright PI:NAME:<NAME>END_PI and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki-server/blob/master/LICENSE.txt ### # **defaultargs.coffee** when called on the argv object this # module will create reasonable defaults for options not supplied, # based on what information is provided. path = require 'path' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE module.exports = (argv) -> argv or= {} argv.root or= __dirname # the directory that contains all the packages that makeup the wiki argv.packageDir or= path.join(argv.root, "..") argv.port or= 3000 argv.home or= 'welcome-visitors' argv.data or= path.join(getUserHome(), '.wiki') # see also cli argv.client or= path.join(argv.packageDir, 'wiki-client', 'client') argv.db or= path.join(argv.data, 'pages') argv.status or= path.join(argv.data, 'status') argv.assets or= path.join(argv.data, 'assets') argv.recycle or= path.join(argv.data, 'recycle') argv.url or= 'http://localhost' + (':' + argv.port) unless argv.port is 80 argv.id or= path.join(argv.status, 'owner.json') argv.uploadLimit or= '5mb' argv.cookieSecret or= require('crypto').randomBytes(64).toString('hex') argv.secure_cookie or= false argv.session_duration or= 7 argv.neighbors or= '' argv.debug or= false if typeof(argv.database) is 'string' argv.database = JSON.parse(argv.database) argv.database or= {} argv.database.type or= './page' if argv.database.type.charAt(0) is '.' if argv.database.type != './page' console.log "\n\nWARNING: This storage option is depeciated." console.log " See ReadMe for details of the changes required.\n\n" else argv.database.type = 'wiki-storage-' + argv.database.type argv.security_type or= './security' if argv.security_type is './security' console.log "\n\nWARNING: Using default security module." else argv.security_type = 'wiki-security-' + argv.security_type argv.security_legacy or= false #resolve all relative paths argv.root = path.resolve(argv.root) argv.packageDir = path.resolve(argv.packageDir) argv.data = path.resolve(argv.data) argv.client = path.resolve(argv.client) argv.db = path.resolve(argv.db) argv.status = path.resolve(argv.status) argv.id = path.resolve(argv.id) if /node_modules/.test(argv.data) console.log "\n\nWARNING : The dafault data path is not a safe place." console.log " : by using ", argv.data, " your pages will be lost when packages are updated." console.log " : You are strongly advised to use an alternative directory." console.log " : See the wiki package ReadMe for how to do this.\n\n" argv
[ { "context": "---------------------------------\n# Copyright 2013 Patrick Mueller\n#\n# Licensed under the Apache License, Version 2.", "end": 2238, "score": 0.9998291730880737, "start": 2223, "tag": "NAME", "value": "Patrick Mueller" } ]
test/utils.coffee
pmuellr/cat-source-map
1
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" require "shelljs/global" lib = path.resolve path.join __dirname, "..", "lib" node_modules = path.resolve path.join __dirname, "..", "node_modules" mkdir "-p", path.join(__dirname, "..", "tmp") #------------------------------------------------------------------------------- node_modules_bin = (cmd) -> path.join node_modules, ".bin", cmd #------------------------------------------------------------------------------- exports.coffee = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "coffee"} #{cmd}" #------------------------------------------------------------------------------- exports.coffeec = (cmd) -> cmd = normalizeCommand cmd exports.coffee "--compile --bare #{cmd}" #------------------------------------------------------------------------------- exports.browserify = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "browserify"} #{cmd}" #------------------------------------------------------------------------------- exports.uglifyjs = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "uglifyjs"} #{cmd}" #------------------------------------------------------------------------------- exports.cat_source_map = (cmd) -> exec "node #{path.join lib, "cli.js"} #{cmd}" #------------------------------------------------------------------------------- exports.cleanDir = (dir) -> mkdir "-p", dir rm "-rf", path.join(dir, "*") #------------------------------------------------------------------------------- exports.compareMaps = (testName, baseFile) -> actualFile = "#{baseFile}.js.map.json" expectedFile = path.join "..", "..", "expected", testName, actualFile actualContents = fs.readFileSync actualFile, "utf8" expectedContents = fs.readFileSync expectedFile, "utf8" return actualContents == expectedContents #------------------------------------------------------------------------------- normalizeCommand = (cmd) -> cmd.replace(/\s+/g," ").trim() #------------------------------------------------------------------------------- # Copyright 2013 Patrick Mueller # # 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. #-------------------------------------------------------------------------------
171916
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" require "shelljs/global" lib = path.resolve path.join __dirname, "..", "lib" node_modules = path.resolve path.join __dirname, "..", "node_modules" mkdir "-p", path.join(__dirname, "..", "tmp") #------------------------------------------------------------------------------- node_modules_bin = (cmd) -> path.join node_modules, ".bin", cmd #------------------------------------------------------------------------------- exports.coffee = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "coffee"} #{cmd}" #------------------------------------------------------------------------------- exports.coffeec = (cmd) -> cmd = normalizeCommand cmd exports.coffee "--compile --bare #{cmd}" #------------------------------------------------------------------------------- exports.browserify = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "browserify"} #{cmd}" #------------------------------------------------------------------------------- exports.uglifyjs = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "uglifyjs"} #{cmd}" #------------------------------------------------------------------------------- exports.cat_source_map = (cmd) -> exec "node #{path.join lib, "cli.js"} #{cmd}" #------------------------------------------------------------------------------- exports.cleanDir = (dir) -> mkdir "-p", dir rm "-rf", path.join(dir, "*") #------------------------------------------------------------------------------- exports.compareMaps = (testName, baseFile) -> actualFile = "#{baseFile}.js.map.json" expectedFile = path.join "..", "..", "expected", testName, actualFile actualContents = fs.readFileSync actualFile, "utf8" expectedContents = fs.readFileSync expectedFile, "utf8" return actualContents == expectedContents #------------------------------------------------------------------------------- normalizeCommand = (cmd) -> cmd.replace(/\s+/g," ").trim() #------------------------------------------------------------------------------- # Copyright 2013 <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. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" require "shelljs/global" lib = path.resolve path.join __dirname, "..", "lib" node_modules = path.resolve path.join __dirname, "..", "node_modules" mkdir "-p", path.join(__dirname, "..", "tmp") #------------------------------------------------------------------------------- node_modules_bin = (cmd) -> path.join node_modules, ".bin", cmd #------------------------------------------------------------------------------- exports.coffee = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "coffee"} #{cmd}" #------------------------------------------------------------------------------- exports.coffeec = (cmd) -> cmd = normalizeCommand cmd exports.coffee "--compile --bare #{cmd}" #------------------------------------------------------------------------------- exports.browserify = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "browserify"} #{cmd}" #------------------------------------------------------------------------------- exports.uglifyjs = (cmd) -> cmd = normalizeCommand cmd exec "node #{node_modules_bin "uglifyjs"} #{cmd}" #------------------------------------------------------------------------------- exports.cat_source_map = (cmd) -> exec "node #{path.join lib, "cli.js"} #{cmd}" #------------------------------------------------------------------------------- exports.cleanDir = (dir) -> mkdir "-p", dir rm "-rf", path.join(dir, "*") #------------------------------------------------------------------------------- exports.compareMaps = (testName, baseFile) -> actualFile = "#{baseFile}.js.map.json" expectedFile = path.join "..", "..", "expected", testName, actualFile actualContents = fs.readFileSync actualFile, "utf8" expectedContents = fs.readFileSync expectedFile, "utf8" return actualContents == expectedContents #------------------------------------------------------------------------------- normalizeCommand = (cmd) -> cmd.replace(/\s+/g," ").trim() #------------------------------------------------------------------------------- # Copyright 2013 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. #-------------------------------------------------------------------------------
[ { "context": "ipt Base62 encode/decoder\n # Copyright (c) 2013 Andrew Nesbitt\n # See LICENSE at https://github.com/andrew/ba", "end": 982, "score": 0.9998844265937805, "start": 968, "tag": "NAME", "value": "Andrew Nesbitt" }, { "context": "w Nesbitt\n # See LICENSE at https...
App.coffee
RallyRonnie/RallyPoker
0
Ext.define 'RallyPokerApp', { extend: 'Rally.app.App' id: 'RallyPokerApp' componentCls: 'app' models: [] layout: 'card' items: [{ id: 'storypicker' layout: # type: 'vbox' reserveScrollbar: true autoScroll: true dockedItems: [{ items: [{ id: 'iterationfilter' xtype: 'toolbar' # cls: 'header' }] }] }, { id: 'storyview' layout: reserveScrollbar: true autoScroll: true dockedItems: [{ items: [{ id: 'storyheader' xtype: 'toolbar' # cls: 'header' # tpl: '<h2>{FormattedID}: {Name}</h2>' items: [{ id: 'storyback' xtype: 'button' html: 'Back', # scale: 'small' # ui: 'back' }, { id: 'storytitle' xtype: 'component' }] }] }] }] Base62: do () -> # Adapted from Javascript Base62 encode/decoder # Copyright (c) 2013 Andrew Nesbitt # See LICENSE at https://github.com/andrew/base62.js # Library that obfuscates numeric strings as case-sensitive, # alphanumeric strings chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] { encode: (i) -> return if i == 0 s = '' while i > 0 s = chars[i % 62] + s i = Math.floor(i / 62) s decode: (a,b,c,d) -> `for ( b = c = (a === (/\W|_|^$/.test(a += "") || a)) - 1; d = a.charCodeAt(c++); ) { b = b * 62 + d - [, 48, 29, 87][d >> 5]; } return b` return } PokerMessage: do () -> # helper fn to escape RegEx-reserved strings esc = (str) -> str.replace /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&" # [strings] ==> encoded message + custom delimiters sep = ['/', '&'] msg = new RegExp "^" + sep[0] + "\\w+(?:" + sep[1] + "\\w+)+$" env = ['[[', ']]'] pkg = new RegExp esc(env[0]) + "(" + sep[0] + ".+?)" + esc(env[1]) { compile: (M) -> fn = arguments[1] || (x) -> x a = Ext.clone M a[0] = sep[0] + fn M[0] s = if a.length == 1 then a[0] else a.reduce (p, c, i) -> p + sep[1] + fn c env[0] + s + env[1] extract: (s) -> if s and a = s.match pkg then a.pop() else false parse: (s) -> return false if not msg.test s M = s.slice(1).split sep[1] if not arguments[1]? then M else arguments[1] i for i in M by 1 } launch: () -> @IterationsStore = Ext.create 'Rally.data.WsapiDataStore', { # id: 'iterationsStore' model: 'Iteration' fetch: ['Name'] sorters: [{ property: 'Name' direction: 'DESC' }] autoLoad: true listeners: load: (store, result, success) => # debugger @IterationFilter.setValue 'Deprecated' if success return } @IterationFilter = Ext.create 'Ext.form.ComboBox', { fieldLabel: 'Iteration' store: @IterationsStore queryMode: 'local' displayField: 'Name' valueField: 'Name' listeners: change: (field, newValue, oldValue, options) => @StoriesStore.load { filters: [{ property: 'Iteration.Name' value: newValue }] } return } @down('#iterationfilter').add @IterationFilter @StoriesStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'User Story' fetch: ['ObjectID', 'FormattedID', 'Name'] sorters: [{ property: 'Name' direction: 'DESC' }] # listeners: # load: (store, result, success) -> # debugger # return } @StoryList = Ext.create 'Ext.view.View', { store: @StoriesStore tpl: new Ext.XTemplate( '<tpl for=".">', '<div style="padding: .5em 0;" class="storylistitem" data-id="{ObjectID}">', '<span class="storylistitem-id">{FormattedID}: {Name}</span>', '</div>', '</tpl>' ) itemSelector: 'div.storylistitem' emptyText: 'No stories available' listeners: click: element: 'el' fn: (e, t) => StoryListItem = Ext.get(Ext.get(t).findParent '.storylistitem') storyListItemName = StoryListItem.child('.storylistitem-id').getHTML() Ext.get('storytitle').update storyListItemName storyListItemId = StoryListItem.getAttribute 'data-id' @CurrentStory.load { filters: [{ property: 'ObjectID' value: storyListItemId }] } # always load the store so that its view is reprocessed. @DiscussionsStore.load { filters: [{ property: 'Artifact.ObjectID' value: storyListItemId }] } @getLayout().setActiveItem 'storyview' return } @down('#storypicker').add @StoryList Ext.getCmp('storyback').on 'click', () => @getLayout().setActiveItem 'storypicker' return @CurrentStory = Ext.create 'Rally.data.WsapiDataStore', { model: 'userstory' limit: 1, fetch: ['ObjectID', 'LastUpdateDate', 'Description', 'Attachments', 'Notes', 'Discussion'] } @StoryPage = Ext.create 'Ext.view.View', { store: @CurrentStory tpl: new Ext.XTemplate( '<tpl for=".">', '<div class="storydetail" data-id="{ObjectID}">', '<small class="storydetail-date">Last Updated: {[this.prettyDate(values.LastUpdateDate)]}</small>', '<div class="storydetail-description">', '{Description}', '</div>', '<div class="storydetail-attachments">', '<h3>Attachments<h3>{Attachments}', '</div>', '<div class="storydetail-notes">', '<h3>Notes<h3>{Notes}', '</div>', '</div>', '</tpl>', { # Adapted from JavaScript Pretty Date # Copyright (c) 2011 John Resig (ejohn.org) # Licensed under the MIT and GPL licenses. # Takes an ISO time and returns a string representing how # long ago the date represents. prettyDate: (date) -> diff = (((new Date()).getTime() - date.getTime()) / 1000) day_diff = Math.floor(diff / 86400) return if isNaN(day_diff) || day_diff < 0 || day_diff >= 31 day_diff == 0 && (diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 60) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + " hours ago") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago" } ) itemSelector: 'div.storydetail' } @down('#storyview').add @StoryPage # custom field definition to parse poker messages from discussion items. @DiscussionMessageField = new Ext.data.Field { name: 'Message' type: 'string' convert: (v, rec) => if message = @PokerMessage.extract rec.get 'Text' # Expected message contents: UserID + 4-bit point-selection value (@PokerMessage.parse message, @Base62.decode).pop() else false } Rally.data.ModelFactory.getModel { type: 'conversationpost' success: (Model) => @models['conversationpost'] = Ext.clone Model Model.prototype.fields.items.push @DiscussionMessageField Model.setFields Model.prototype.fields.items return } @DiscussionsStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'conversationpost' fetch: ['User', 'CreationDate', 'Text', 'Message'] } @DiscussionThread = Ext.create 'Ext.view.View', { store: @DiscussionsStore tpl: new Ext.XTemplate( '<tpl for=".">', '<tpl if="Message !== false">', '<tpl if="!this.shownMessages">{% this.shownMessages = true %}', '<div class="messagethread">', '<h3>Who\'s Voted</h3>', '<ul class="messageitems">', '</tpl>', '</tpl>', '<tpl if="xindex == xcount && this.shownMessages">', '<tpl for="whoVoted">', '<li>{name} at {when}</li>', '</tpl>' '</ul>', '</div>', '</tpl>', '</tpl>', '<div class="estimateselector"></div>' '<tpl for=".">', '<tpl if="Message === false">', '<tpl if="!this.shownDiscussion">{% this.shownDiscussion = true %}', '<div class="discussionthread">', '<h3>Discussion</h3>', '</tpl>' '<div class="discussionitem">', '<small class="discussionitem-id">{User._refObjectName}: {CreationDate}</small>', '<p class="discussionitem-text">{Text}</p>', '</div>', '</tpl>', '<tpl if="xindex == xcount && this.shownDiscussion">', '</div>', '</tpl>', '</tpl>', { accountVoted: false shownMessages: false shownDiscussion: false whoVoted: {} } ) itemSelector: 'div.discussionitem' accountRef: "/user/" + Rally.environment.getContext().getUser().ObjectID prepareData: (data, index, record) -> if data.Message `var timestamp = data.CreationDate.getTime()` if not @tpl.whoVoted[data.User._ref]? or timestamp > @tpl.whoVoted[data.User._ref].when @tpl.whoVoted[data.User._ref] = post: data.ObjectID when: timestamp user: data.User._ref name: data.User._refObjectName vote: data.Message if index == @store.data.length - 1 `var whenVoted = [], voteMap = {}` data.whoVoted = [] for k, V of @tpl.whoVoted @tpl.accountVoted = V if k == @accountRef if @tpl.whoVoted.hasOwnProperty k whenVoted.push V.when voteMap[V.when] = V whenVoted.sort() for k in whenVoted D = new Date voteMap[k].when voteMap[k].when = Ext.util.Format.date(D, 'g:iA') + ' on ' + Ext.util.Format.date(D, 'm-d-Y') data.whoVoted.push voteMap[k] # console.log whenVoted # console.log @tpl.whenVoted # console.log 'prepareData. accountVoted = ' + @tpl.accountVoted data listeners: scope: @ refresh: (view) -> StoryEstimator = Ext.create 'EstimateSelector', ParentApp: @ accountId: Rally.environment.getContext().getUser().ObjectID renderTo: Ext.query('.estimateselector')[0] # console.log 'refresh. accountVoted = ' + view.tpl.accountVoted StoryEstimator.update view.tpl.accountVoted # reset template variables for subsequent displays view.tpl.accountVoted = false view.tpl.shownMessages = false view.tpl.shownDiscussion = false view.tpl.whoVoted = {} return } @down('#storyview').add @DiscussionThread return } Ext.define 'EstimateSelector', { extend: 'Ext.Container' # cls: 'estimateselector' # constructor uses config to populate items. # items: [] config: accountId: 0 cipher: 0 # @cfg {Array} (required) # a list of values that can be used as story estimates deck: [ { value: `00`, label: '?' } { value: `01`, label: '0' } { value: `02`, label: '&#189;' } # "½" { value: `03`, label: '1' } { value: `04`, label: '2' } { value: `05`, label: '3' } { value: `06`, label: '5' } { value: `07`, label: '8' } { value: `010`, label: '13' } { value: `011`, label: '20' } { value: `012`, label: '40' } { value: `013`, label: '100' } # { value: `014`, label: '' } # { value: `015`, label: '' } # { value: `016`, label: '' } # { value: `017`, label: '' } ] constructor: (config) -> @mergeConfig config @config.cipher = config.accountId % 10 if config.accountId? @callParent [config] return # update gets called before the template is processed. update: (data) -> if data.vote # console.log 'update. vote = ' + data.vote # values in 'data' passed by reference and later used by template. data.vote = @_decipher(data.vote) @callParent [data] # add control to delete previous vote Ext.create 'Ext.Component', data: data tpl: new Ext.XTemplate( '<tpl for=".">', '<span data-id="{post}">select a new estimate</span>', '</tpl>' ) listeners: click: element: 'el' scope: @ fn: @_onReselect renderTo: @.getEl() else # console.log 'update. no vote' @callParent [data] # initialize cards. # @todo any way to create these on initComponent and show/hide instead? for C in @config.deck Ext.create 'Ext.Component', id: 'pokercard-' + C.value cls: 'pokercard' html: C.label config: C listeners: click: element: 'el' scope: @ fn: @_onCardClick renderTo: @.getEl() return tpl: new Ext.XTemplate( '<tpl for=".">', '<tpl if="vote">', '<h3>Your estimate: {vote}</h3>', '<tpl else>', '<h3>Select an estimate</h3>', '</tpl>', '</tpl>', ) # listeners: # beforerender: () -> # # debugger # console.log("beforerender. cipher = " + @config.cipher) # return # simple caesar cipher to obfuscate card values using last digit of user id. _encipher: (v) -> (v + @config.cipher) % @config.deck.length _decipher: (v) -> @config.deck[if (v = (v - @config.cipher) % @config.deck.length) < 0 then @config.deck.length + v else v].label # helper function bound to card's click event. _onCardClick: (e, t) -> selectedValue = @_encipher Ext.getCmp(t.id).config.value Message = [new Date().getTime(), @config.accountId, selectedValue] pokerMessage = @ParentApp.PokerMessage.compile Message, @ParentApp.Base62.encode Record = Ext.create @ParentApp.models['conversationpost'] Record.set Artifact: @ParentApp.CurrentStory.data.keys[0] User: @config.accountId Text: 'Pointed this story with RallyPoker. <span style="display:none">' + encodeURIComponent(pokerMessage) + '<\/span>' Record.save success: (b, o) => @ParentApp.DiscussionsStore.reload() return failure: (b, o) -> alert 'Error submitting your estimate. Please try again.' return return # helper functions bound to the "reselect" link. _onReselect: (e, t) -> EstimateStore = Ext.create 'Rally.data.WsapiDataStore', model: 'conversationpost' autoLoad: true filters: [{ property: 'ObjectID' value: t.getAttribute 'data-id' }] limit: 1 listeners: scope: @ load: @_onEstimateStoreLoad return _onEstimateStoreLoad: (store, result, success) -> if success store.data.items[0].destroy success: () => @ParentApp.DiscussionsStore.reload() return failure: () -> alert 'Error deleting your estimate. Please try again.' return return }
44799
Ext.define 'RallyPokerApp', { extend: 'Rally.app.App' id: 'RallyPokerApp' componentCls: 'app' models: [] layout: 'card' items: [{ id: 'storypicker' layout: # type: 'vbox' reserveScrollbar: true autoScroll: true dockedItems: [{ items: [{ id: 'iterationfilter' xtype: 'toolbar' # cls: 'header' }] }] }, { id: 'storyview' layout: reserveScrollbar: true autoScroll: true dockedItems: [{ items: [{ id: 'storyheader' xtype: 'toolbar' # cls: 'header' # tpl: '<h2>{FormattedID}: {Name}</h2>' items: [{ id: 'storyback' xtype: 'button' html: 'Back', # scale: 'small' # ui: 'back' }, { id: 'storytitle' xtype: 'component' }] }] }] }] Base62: do () -> # Adapted from Javascript Base62 encode/decoder # Copyright (c) 2013 <NAME> # See LICENSE at https://github.com/andrew/base62.js # Library that obfuscates numeric strings as case-sensitive, # alphanumeric strings chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] { encode: (i) -> return if i == 0 s = '' while i > 0 s = chars[i % 62] + s i = Math.floor(i / 62) s decode: (a,b,c,d) -> `for ( b = c = (a === (/\W|_|^$/.test(a += "") || a)) - 1; d = a.charCodeAt(c++); ) { b = b * 62 + d - [, 48, 29, 87][d >> 5]; } return b` return } PokerMessage: do () -> # helper fn to escape RegEx-reserved strings esc = (str) -> str.replace /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&" # [strings] ==> encoded message + custom delimiters sep = ['/', '&'] msg = new RegExp "^" + sep[0] + "\\w+(?:" + sep[1] + "\\w+)+$" env = ['[[', ']]'] pkg = new RegExp esc(env[0]) + "(" + sep[0] + ".+?)" + esc(env[1]) { compile: (M) -> fn = arguments[1] || (x) -> x a = Ext.clone M a[0] = sep[0] + fn M[0] s = if a.length == 1 then a[0] else a.reduce (p, c, i) -> p + sep[1] + fn c env[0] + s + env[1] extract: (s) -> if s and a = s.match pkg then a.pop() else false parse: (s) -> return false if not msg.test s M = s.slice(1).split sep[1] if not arguments[1]? then M else arguments[1] i for i in M by 1 } launch: () -> @IterationsStore = Ext.create 'Rally.data.WsapiDataStore', { # id: 'iterationsStore' model: 'Iteration' fetch: ['Name'] sorters: [{ property: 'Name' direction: 'DESC' }] autoLoad: true listeners: load: (store, result, success) => # debugger @IterationFilter.setValue 'Deprecated' if success return } @IterationFilter = Ext.create 'Ext.form.ComboBox', { fieldLabel: 'Iteration' store: @IterationsStore queryMode: 'local' displayField: 'Name' valueField: 'Name' listeners: change: (field, newValue, oldValue, options) => @StoriesStore.load { filters: [{ property: 'Iteration.Name' value: newValue }] } return } @down('#iterationfilter').add @IterationFilter @StoriesStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'User Story' fetch: ['ObjectID', 'FormattedID', 'Name'] sorters: [{ property: 'Name' direction: 'DESC' }] # listeners: # load: (store, result, success) -> # debugger # return } @StoryList = Ext.create 'Ext.view.View', { store: @StoriesStore tpl: new Ext.XTemplate( '<tpl for=".">', '<div style="padding: .5em 0;" class="storylistitem" data-id="{ObjectID}">', '<span class="storylistitem-id">{FormattedID}: {Name}</span>', '</div>', '</tpl>' ) itemSelector: 'div.storylistitem' emptyText: 'No stories available' listeners: click: element: 'el' fn: (e, t) => StoryListItem = Ext.get(Ext.get(t).findParent '.storylistitem') storyListItemName = StoryListItem.child('.storylistitem-id').getHTML() Ext.get('storytitle').update storyListItemName storyListItemId = StoryListItem.getAttribute 'data-id' @CurrentStory.load { filters: [{ property: 'ObjectID' value: storyListItemId }] } # always load the store so that its view is reprocessed. @DiscussionsStore.load { filters: [{ property: 'Artifact.ObjectID' value: storyListItemId }] } @getLayout().setActiveItem 'storyview' return } @down('#storypicker').add @StoryList Ext.getCmp('storyback').on 'click', () => @getLayout().setActiveItem 'storypicker' return @CurrentStory = Ext.create 'Rally.data.WsapiDataStore', { model: 'userstory' limit: 1, fetch: ['ObjectID', 'LastUpdateDate', 'Description', 'Attachments', 'Notes', 'Discussion'] } @StoryPage = Ext.create 'Ext.view.View', { store: @CurrentStory tpl: new Ext.XTemplate( '<tpl for=".">', '<div class="storydetail" data-id="{ObjectID}">', '<small class="storydetail-date">Last Updated: {[this.prettyDate(values.LastUpdateDate)]}</small>', '<div class="storydetail-description">', '{Description}', '</div>', '<div class="storydetail-attachments">', '<h3>Attachments<h3>{Attachments}', '</div>', '<div class="storydetail-notes">', '<h3>Notes<h3>{Notes}', '</div>', '</div>', '</tpl>', { # Adapted from JavaScript Pretty Date # Copyright (c) 2011 <NAME> (ejohn.org) # Licensed under the MIT and GPL licenses. # Takes an ISO time and returns a string representing how # long ago the date represents. prettyDate: (date) -> diff = (((new Date()).getTime() - date.getTime()) / 1000) day_diff = Math.floor(diff / 86400) return if isNaN(day_diff) || day_diff < 0 || day_diff >= 31 day_diff == 0 && (diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 60) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + " hours ago") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago" } ) itemSelector: 'div.storydetail' } @down('#storyview').add @StoryPage # custom field definition to parse poker messages from discussion items. @DiscussionMessageField = new Ext.data.Field { name: 'Message' type: 'string' convert: (v, rec) => if message = @PokerMessage.extract rec.get 'Text' # Expected message contents: UserID + 4-bit point-selection value (@PokerMessage.parse message, @Base62.decode).pop() else false } Rally.data.ModelFactory.getModel { type: 'conversationpost' success: (Model) => @models['conversationpost'] = Ext.clone Model Model.prototype.fields.items.push @DiscussionMessageField Model.setFields Model.prototype.fields.items return } @DiscussionsStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'conversationpost' fetch: ['User', 'CreationDate', 'Text', 'Message'] } @DiscussionThread = Ext.create 'Ext.view.View', { store: @DiscussionsStore tpl: new Ext.XTemplate( '<tpl for=".">', '<tpl if="Message !== false">', '<tpl if="!this.shownMessages">{% this.shownMessages = true %}', '<div class="messagethread">', '<h3>Who\'s Voted</h3>', '<ul class="messageitems">', '</tpl>', '</tpl>', '<tpl if="xindex == xcount && this.shownMessages">', '<tpl for="whoVoted">', '<li>{name} at {when}</li>', '</tpl>' '</ul>', '</div>', '</tpl>', '</tpl>', '<div class="estimateselector"></div>' '<tpl for=".">', '<tpl if="Message === false">', '<tpl if="!this.shownDiscussion">{% this.shownDiscussion = true %}', '<div class="discussionthread">', '<h3>Discussion</h3>', '</tpl>' '<div class="discussionitem">', '<small class="discussionitem-id">{User._refObjectName}: {CreationDate}</small>', '<p class="discussionitem-text">{Text}</p>', '</div>', '</tpl>', '<tpl if="xindex == xcount && this.shownDiscussion">', '</div>', '</tpl>', '</tpl>', { accountVoted: false shownMessages: false shownDiscussion: false whoVoted: {} } ) itemSelector: 'div.discussionitem' accountRef: "/user/" + Rally.environment.getContext().getUser().ObjectID prepareData: (data, index, record) -> if data.Message `var timestamp = data.CreationDate.getTime()` if not @tpl.whoVoted[data.User._ref]? or timestamp > @tpl.whoVoted[data.User._ref].when @tpl.whoVoted[data.User._ref] = post: data.ObjectID when: timestamp user: data.User._ref name: data.User._refObjectName vote: data.Message if index == @store.data.length - 1 `var whenVoted = [], voteMap = {}` data.whoVoted = [] for k, V of @tpl.whoVoted @tpl.accountVoted = V if k == @accountRef if @tpl.whoVoted.hasOwnProperty k whenVoted.push V.when voteMap[V.when] = V whenVoted.sort() for k in whenVoted D = new Date voteMap[k].when voteMap[k].when = Ext.util.Format.date(D, 'g:iA') + ' on ' + Ext.util.Format.date(D, 'm-d-Y') data.whoVoted.push voteMap[k] # console.log whenVoted # console.log @tpl.whenVoted # console.log 'prepareData. accountVoted = ' + @tpl.accountVoted data listeners: scope: @ refresh: (view) -> StoryEstimator = Ext.create 'EstimateSelector', ParentApp: @ accountId: Rally.environment.getContext().getUser().ObjectID renderTo: Ext.query('.estimateselector')[0] # console.log 'refresh. accountVoted = ' + view.tpl.accountVoted StoryEstimator.update view.tpl.accountVoted # reset template variables for subsequent displays view.tpl.accountVoted = false view.tpl.shownMessages = false view.tpl.shownDiscussion = false view.tpl.whoVoted = {} return } @down('#storyview').add @DiscussionThread return } Ext.define 'EstimateSelector', { extend: 'Ext.Container' # cls: 'estimateselector' # constructor uses config to populate items. # items: [] config: accountId: 0 cipher: 0 # @cfg {Array} (required) # a list of values that can be used as story estimates deck: [ { value: `00`, label: '?' } { value: `01`, label: '0' } { value: `02`, label: '&#189;' } # "½" { value: `03`, label: '1' } { value: `04`, label: '2' } { value: `05`, label: '3' } { value: `06`, label: '5' } { value: `07`, label: '8' } { value: `010`, label: '13' } { value: `011`, label: '20' } { value: `012`, label: '40' } { value: `013`, label: '100' } # { value: `014`, label: '' } # { value: `015`, label: '' } # { value: `016`, label: '' } # { value: `017`, label: '' } ] constructor: (config) -> @mergeConfig config @config.cipher = config.accountId % 10 if config.accountId? @callParent [config] return # update gets called before the template is processed. update: (data) -> if data.vote # console.log 'update. vote = ' + data.vote # values in 'data' passed by reference and later used by template. data.vote = @_decipher(data.vote) @callParent [data] # add control to delete previous vote Ext.create 'Ext.Component', data: data tpl: new Ext.XTemplate( '<tpl for=".">', '<span data-id="{post}">select a new estimate</span>', '</tpl>' ) listeners: click: element: 'el' scope: @ fn: @_onReselect renderTo: @.getEl() else # console.log 'update. no vote' @callParent [data] # initialize cards. # @todo any way to create these on initComponent and show/hide instead? for C in @config.deck Ext.create 'Ext.Component', id: 'pokercard-' + C.value cls: 'pokercard' html: C.label config: C listeners: click: element: 'el' scope: @ fn: @_onCardClick renderTo: @.getEl() return tpl: new Ext.XTemplate( '<tpl for=".">', '<tpl if="vote">', '<h3>Your estimate: {vote}</h3>', '<tpl else>', '<h3>Select an estimate</h3>', '</tpl>', '</tpl>', ) # listeners: # beforerender: () -> # # debugger # console.log("beforerender. cipher = " + @config.cipher) # return # simple caesar cipher to obfuscate card values using last digit of user id. _encipher: (v) -> (v + @config.cipher) % @config.deck.length _decipher: (v) -> @config.deck[if (v = (v - @config.cipher) % @config.deck.length) < 0 then @config.deck.length + v else v].label # helper function bound to card's click event. _onCardClick: (e, t) -> selectedValue = @_encipher Ext.getCmp(t.id).config.value Message = [new Date().getTime(), @config.accountId, selectedValue] pokerMessage = @ParentApp.PokerMessage.compile Message, @ParentApp.Base62.encode Record = Ext.create @ParentApp.models['conversationpost'] Record.set Artifact: @ParentApp.CurrentStory.data.keys[0] User: @config.accountId Text: 'Pointed this story with RallyPoker. <span style="display:none">' + encodeURIComponent(pokerMessage) + '<\/span>' Record.save success: (b, o) => @ParentApp.DiscussionsStore.reload() return failure: (b, o) -> alert 'Error submitting your estimate. Please try again.' return return # helper functions bound to the "reselect" link. _onReselect: (e, t) -> EstimateStore = Ext.create 'Rally.data.WsapiDataStore', model: 'conversationpost' autoLoad: true filters: [{ property: 'ObjectID' value: t.getAttribute 'data-id' }] limit: 1 listeners: scope: @ load: @_onEstimateStoreLoad return _onEstimateStoreLoad: (store, result, success) -> if success store.data.items[0].destroy success: () => @ParentApp.DiscussionsStore.reload() return failure: () -> alert 'Error deleting your estimate. Please try again.' return return }
true
Ext.define 'RallyPokerApp', { extend: 'Rally.app.App' id: 'RallyPokerApp' componentCls: 'app' models: [] layout: 'card' items: [{ id: 'storypicker' layout: # type: 'vbox' reserveScrollbar: true autoScroll: true dockedItems: [{ items: [{ id: 'iterationfilter' xtype: 'toolbar' # cls: 'header' }] }] }, { id: 'storyview' layout: reserveScrollbar: true autoScroll: true dockedItems: [{ items: [{ id: 'storyheader' xtype: 'toolbar' # cls: 'header' # tpl: '<h2>{FormattedID}: {Name}</h2>' items: [{ id: 'storyback' xtype: 'button' html: 'Back', # scale: 'small' # ui: 'back' }, { id: 'storytitle' xtype: 'component' }] }] }] }] Base62: do () -> # Adapted from Javascript Base62 encode/decoder # Copyright (c) 2013 PI:NAME:<NAME>END_PI # See LICENSE at https://github.com/andrew/base62.js # Library that obfuscates numeric strings as case-sensitive, # alphanumeric strings chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] { encode: (i) -> return if i == 0 s = '' while i > 0 s = chars[i % 62] + s i = Math.floor(i / 62) s decode: (a,b,c,d) -> `for ( b = c = (a === (/\W|_|^$/.test(a += "") || a)) - 1; d = a.charCodeAt(c++); ) { b = b * 62 + d - [, 48, 29, 87][d >> 5]; } return b` return } PokerMessage: do () -> # helper fn to escape RegEx-reserved strings esc = (str) -> str.replace /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&" # [strings] ==> encoded message + custom delimiters sep = ['/', '&'] msg = new RegExp "^" + sep[0] + "\\w+(?:" + sep[1] + "\\w+)+$" env = ['[[', ']]'] pkg = new RegExp esc(env[0]) + "(" + sep[0] + ".+?)" + esc(env[1]) { compile: (M) -> fn = arguments[1] || (x) -> x a = Ext.clone M a[0] = sep[0] + fn M[0] s = if a.length == 1 then a[0] else a.reduce (p, c, i) -> p + sep[1] + fn c env[0] + s + env[1] extract: (s) -> if s and a = s.match pkg then a.pop() else false parse: (s) -> return false if not msg.test s M = s.slice(1).split sep[1] if not arguments[1]? then M else arguments[1] i for i in M by 1 } launch: () -> @IterationsStore = Ext.create 'Rally.data.WsapiDataStore', { # id: 'iterationsStore' model: 'Iteration' fetch: ['Name'] sorters: [{ property: 'Name' direction: 'DESC' }] autoLoad: true listeners: load: (store, result, success) => # debugger @IterationFilter.setValue 'Deprecated' if success return } @IterationFilter = Ext.create 'Ext.form.ComboBox', { fieldLabel: 'Iteration' store: @IterationsStore queryMode: 'local' displayField: 'Name' valueField: 'Name' listeners: change: (field, newValue, oldValue, options) => @StoriesStore.load { filters: [{ property: 'Iteration.Name' value: newValue }] } return } @down('#iterationfilter').add @IterationFilter @StoriesStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'User Story' fetch: ['ObjectID', 'FormattedID', 'Name'] sorters: [{ property: 'Name' direction: 'DESC' }] # listeners: # load: (store, result, success) -> # debugger # return } @StoryList = Ext.create 'Ext.view.View', { store: @StoriesStore tpl: new Ext.XTemplate( '<tpl for=".">', '<div style="padding: .5em 0;" class="storylistitem" data-id="{ObjectID}">', '<span class="storylistitem-id">{FormattedID}: {Name}</span>', '</div>', '</tpl>' ) itemSelector: 'div.storylistitem' emptyText: 'No stories available' listeners: click: element: 'el' fn: (e, t) => StoryListItem = Ext.get(Ext.get(t).findParent '.storylistitem') storyListItemName = StoryListItem.child('.storylistitem-id').getHTML() Ext.get('storytitle').update storyListItemName storyListItemId = StoryListItem.getAttribute 'data-id' @CurrentStory.load { filters: [{ property: 'ObjectID' value: storyListItemId }] } # always load the store so that its view is reprocessed. @DiscussionsStore.load { filters: [{ property: 'Artifact.ObjectID' value: storyListItemId }] } @getLayout().setActiveItem 'storyview' return } @down('#storypicker').add @StoryList Ext.getCmp('storyback').on 'click', () => @getLayout().setActiveItem 'storypicker' return @CurrentStory = Ext.create 'Rally.data.WsapiDataStore', { model: 'userstory' limit: 1, fetch: ['ObjectID', 'LastUpdateDate', 'Description', 'Attachments', 'Notes', 'Discussion'] } @StoryPage = Ext.create 'Ext.view.View', { store: @CurrentStory tpl: new Ext.XTemplate( '<tpl for=".">', '<div class="storydetail" data-id="{ObjectID}">', '<small class="storydetail-date">Last Updated: {[this.prettyDate(values.LastUpdateDate)]}</small>', '<div class="storydetail-description">', '{Description}', '</div>', '<div class="storydetail-attachments">', '<h3>Attachments<h3>{Attachments}', '</div>', '<div class="storydetail-notes">', '<h3>Notes<h3>{Notes}', '</div>', '</div>', '</tpl>', { # Adapted from JavaScript Pretty Date # Copyright (c) 2011 PI:NAME:<NAME>END_PI (ejohn.org) # Licensed under the MIT and GPL licenses. # Takes an ISO time and returns a string representing how # long ago the date represents. prettyDate: (date) -> diff = (((new Date()).getTime() - date.getTime()) / 1000) day_diff = Math.floor(diff / 86400) return if isNaN(day_diff) || day_diff < 0 || day_diff >= 31 day_diff == 0 && (diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 60) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + " hours ago") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago" } ) itemSelector: 'div.storydetail' } @down('#storyview').add @StoryPage # custom field definition to parse poker messages from discussion items. @DiscussionMessageField = new Ext.data.Field { name: 'Message' type: 'string' convert: (v, rec) => if message = @PokerMessage.extract rec.get 'Text' # Expected message contents: UserID + 4-bit point-selection value (@PokerMessage.parse message, @Base62.decode).pop() else false } Rally.data.ModelFactory.getModel { type: 'conversationpost' success: (Model) => @models['conversationpost'] = Ext.clone Model Model.prototype.fields.items.push @DiscussionMessageField Model.setFields Model.prototype.fields.items return } @DiscussionsStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'conversationpost' fetch: ['User', 'CreationDate', 'Text', 'Message'] } @DiscussionThread = Ext.create 'Ext.view.View', { store: @DiscussionsStore tpl: new Ext.XTemplate( '<tpl for=".">', '<tpl if="Message !== false">', '<tpl if="!this.shownMessages">{% this.shownMessages = true %}', '<div class="messagethread">', '<h3>Who\'s Voted</h3>', '<ul class="messageitems">', '</tpl>', '</tpl>', '<tpl if="xindex == xcount && this.shownMessages">', '<tpl for="whoVoted">', '<li>{name} at {when}</li>', '</tpl>' '</ul>', '</div>', '</tpl>', '</tpl>', '<div class="estimateselector"></div>' '<tpl for=".">', '<tpl if="Message === false">', '<tpl if="!this.shownDiscussion">{% this.shownDiscussion = true %}', '<div class="discussionthread">', '<h3>Discussion</h3>', '</tpl>' '<div class="discussionitem">', '<small class="discussionitem-id">{User._refObjectName}: {CreationDate}</small>', '<p class="discussionitem-text">{Text}</p>', '</div>', '</tpl>', '<tpl if="xindex == xcount && this.shownDiscussion">', '</div>', '</tpl>', '</tpl>', { accountVoted: false shownMessages: false shownDiscussion: false whoVoted: {} } ) itemSelector: 'div.discussionitem' accountRef: "/user/" + Rally.environment.getContext().getUser().ObjectID prepareData: (data, index, record) -> if data.Message `var timestamp = data.CreationDate.getTime()` if not @tpl.whoVoted[data.User._ref]? or timestamp > @tpl.whoVoted[data.User._ref].when @tpl.whoVoted[data.User._ref] = post: data.ObjectID when: timestamp user: data.User._ref name: data.User._refObjectName vote: data.Message if index == @store.data.length - 1 `var whenVoted = [], voteMap = {}` data.whoVoted = [] for k, V of @tpl.whoVoted @tpl.accountVoted = V if k == @accountRef if @tpl.whoVoted.hasOwnProperty k whenVoted.push V.when voteMap[V.when] = V whenVoted.sort() for k in whenVoted D = new Date voteMap[k].when voteMap[k].when = Ext.util.Format.date(D, 'g:iA') + ' on ' + Ext.util.Format.date(D, 'm-d-Y') data.whoVoted.push voteMap[k] # console.log whenVoted # console.log @tpl.whenVoted # console.log 'prepareData. accountVoted = ' + @tpl.accountVoted data listeners: scope: @ refresh: (view) -> StoryEstimator = Ext.create 'EstimateSelector', ParentApp: @ accountId: Rally.environment.getContext().getUser().ObjectID renderTo: Ext.query('.estimateselector')[0] # console.log 'refresh. accountVoted = ' + view.tpl.accountVoted StoryEstimator.update view.tpl.accountVoted # reset template variables for subsequent displays view.tpl.accountVoted = false view.tpl.shownMessages = false view.tpl.shownDiscussion = false view.tpl.whoVoted = {} return } @down('#storyview').add @DiscussionThread return } Ext.define 'EstimateSelector', { extend: 'Ext.Container' # cls: 'estimateselector' # constructor uses config to populate items. # items: [] config: accountId: 0 cipher: 0 # @cfg {Array} (required) # a list of values that can be used as story estimates deck: [ { value: `00`, label: '?' } { value: `01`, label: '0' } { value: `02`, label: '&#189;' } # "½" { value: `03`, label: '1' } { value: `04`, label: '2' } { value: `05`, label: '3' } { value: `06`, label: '5' } { value: `07`, label: '8' } { value: `010`, label: '13' } { value: `011`, label: '20' } { value: `012`, label: '40' } { value: `013`, label: '100' } # { value: `014`, label: '' } # { value: `015`, label: '' } # { value: `016`, label: '' } # { value: `017`, label: '' } ] constructor: (config) -> @mergeConfig config @config.cipher = config.accountId % 10 if config.accountId? @callParent [config] return # update gets called before the template is processed. update: (data) -> if data.vote # console.log 'update. vote = ' + data.vote # values in 'data' passed by reference and later used by template. data.vote = @_decipher(data.vote) @callParent [data] # add control to delete previous vote Ext.create 'Ext.Component', data: data tpl: new Ext.XTemplate( '<tpl for=".">', '<span data-id="{post}">select a new estimate</span>', '</tpl>' ) listeners: click: element: 'el' scope: @ fn: @_onReselect renderTo: @.getEl() else # console.log 'update. no vote' @callParent [data] # initialize cards. # @todo any way to create these on initComponent and show/hide instead? for C in @config.deck Ext.create 'Ext.Component', id: 'pokercard-' + C.value cls: 'pokercard' html: C.label config: C listeners: click: element: 'el' scope: @ fn: @_onCardClick renderTo: @.getEl() return tpl: new Ext.XTemplate( '<tpl for=".">', '<tpl if="vote">', '<h3>Your estimate: {vote}</h3>', '<tpl else>', '<h3>Select an estimate</h3>', '</tpl>', '</tpl>', ) # listeners: # beforerender: () -> # # debugger # console.log("beforerender. cipher = " + @config.cipher) # return # simple caesar cipher to obfuscate card values using last digit of user id. _encipher: (v) -> (v + @config.cipher) % @config.deck.length _decipher: (v) -> @config.deck[if (v = (v - @config.cipher) % @config.deck.length) < 0 then @config.deck.length + v else v].label # helper function bound to card's click event. _onCardClick: (e, t) -> selectedValue = @_encipher Ext.getCmp(t.id).config.value Message = [new Date().getTime(), @config.accountId, selectedValue] pokerMessage = @ParentApp.PokerMessage.compile Message, @ParentApp.Base62.encode Record = Ext.create @ParentApp.models['conversationpost'] Record.set Artifact: @ParentApp.CurrentStory.data.keys[0] User: @config.accountId Text: 'Pointed this story with RallyPoker. <span style="display:none">' + encodeURIComponent(pokerMessage) + '<\/span>' Record.save success: (b, o) => @ParentApp.DiscussionsStore.reload() return failure: (b, o) -> alert 'Error submitting your estimate. Please try again.' return return # helper functions bound to the "reselect" link. _onReselect: (e, t) -> EstimateStore = Ext.create 'Rally.data.WsapiDataStore', model: 'conversationpost' autoLoad: true filters: [{ property: 'ObjectID' value: t.getAttribute 'data-id' }] limit: 1 listeners: scope: @ load: @_onEstimateStoreLoad return _onEstimateStoreLoad: (store, result, success) -> if success store.data.items[0].destroy success: () => @ParentApp.DiscussionsStore.reload() return failure: () -> alert 'Error deleting your estimate. Please try again.' return return }
[ { "context": "ne-eastern-sierra-reserve.html\"\n if name == \"Steele Burnand Anza-Borrego Desert Research Center\"\n return pr", "end": 3929, "score": 0.957476794719696, "start": 3910, "tag": "NAME", "value": "Steele Burnand Anza" }, { "context": "earch-center.html\"\n ...
scripts/newAreaOverview.coffee
mcclintock-lab/nrs-reports
0
ReportTab = require 'reportTab' templates = require '../templates/templates.js' _partials = require '../node_modules/seasketch-reporting-api/templates/templates.js' partials = [] for key, val of _partials partials[key.replace('node_modules/seasketch-reporting-api/', '')] = val d3 = window.d3 class NewAreaOverviewTab extends ReportTab name: 'Overview' className: 'newAreaOverview' template: templates.newAreaOverview dependencies:[ 'NewReserveHabitatToolbox' 'SizeToolbox' ] render: () -> # create random data for visualization habs = @recordSet('NewReserveHabitatToolbox', 'Habitat').toArray() missing_habs = @recordSet('NewReserveHabitatToolbox', 'MissingHabitat').toArray() console.log("missing: ", missing_habs) hab_count = @recordSet('NewReserveHabitatToolbox', 'HabitatCounts').toArray() isCollection = @model.isCollection() size = @recordSet('SizeToolbox', 'Size').float('Size') size_acres = size*0.000247105 if size_acres < 0.1 if size_acres < 0.01 aoi_size = "< 0.01" else aoi_size = @addCommas size_acres.toFixed(2) else aoi_size = @addCommas size_acres.toFixed(1) try res_name = @recordSet('SizeToolbox', 'ReserveName').raw('ResName') if res_name == null or isCollection aoi_res_name = "no sketches within an existing reserve" isWithinReserve = false aoi_res_url = "" else aoi_res_name = res_name.toString() isWithinReserve = true aoi_res_url = @getURL aoi_res_name catch err aoi_res_name = "no sketches within an existing reserve" isWithinReserve = false aoi_res_url = "" aoi_name = @model.attributes.name aoi_name = aoi_name.charAt(0).toUpperCase() + aoi_name.slice(1) try total_habs = hab_count[0].TOT found_habs = hab_count[0].FOUND missing_hab_count = hab_count[0].MISSING catch err console.log("err getting count ", err) if isCollection sketch_type = "Collection" else sketch_type = "Sketch" if window.d3 d3IsPresent = true else d3IsPresent = false sketch_name = @model.attributes.name found_color = "#b3cfa7" missing_color = "#e5cace" pie_data = @build_values("Habitats Found", found_habs, found_color, "Missing Habitats", missing_hab_count,missing_color) # setup context object with data and render the template from it context = sketch: @model.forTemplate() sketchClass: @sketchClass.forTemplate() attributes: @model.getAttributes() admin: @project.isAdmin window.user isCollection: isCollection d3IsPresent: d3IsPresent habs: habs total_habs: total_habs found_habs: found_habs missing_habs: missing_habs sketch_name: sketch_name sketch_type: sketch_type missing_hab_count: missing_hab_count isWithinReserve: isWithinReserve aoi_size: aoi_size aoi_res_name: aoi_res_name aoi_name: aoi_name aoi_res_url: aoi_res_url @$el.html @template.render(context, templates) @enableTablePaging() @drawPie(pie_data, '#hab_pie') roundData: (items) => for item in items item.AREA = Number(item.AREA).toFixed(1) items = _.sortBy items, (row) -> row.NAME return items build_values: (yes_label, yes_count, yes_color, no_label, no_count, no_color) => yes_val = {"label":yes_label+" ("+yes_count+")", "value":yes_count, "color":yes_color, "yval":50} no_val = {"label":no_label+" ("+no_count+")", "value":no_count, "color":no_color, "yval":75} return [yes_val, no_val] getURL: (name) => try console.log(name) prefix = "http://www.ucnrs.org/reserves/" if name == "Valentine Eastern Sierra Reserve -Valentine Camp" return prefix+"valentine-eastern-sierra-reserve.html" if name == "Steele Burnand Anza-Borrego Desert Research Center" return prefix+"steeleburnand-anza-borrego-desert-research-center.html" if name == "Burns Piñon Ridge Reserve" return prefix+"burns-pinon-ridge-reserve.html" lower = name.toLowerCase() if name == "Ano Nuevo Island" return prefix+"ano-nuevo-island-reserve.html" dashes = lower.replace(/\s+/g, "-") slashes = dashes.replace(/\//g, "") return prefix+slashes+".html" catch err console.log("err getting url: ", err) return "http://www.ucnrs.org/reserves.html" drawPie: (data, pie_name) => if window.d3 w = 160 h = 110 r = 50 vis_el = @$(pie_name)[0] vis = d3.select(vis_el).append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + (r*2) + "," + (r+5) + ")") pie = d3.layout.pie().value((d) -> return d.value) #declare an arc generator function arc = d3.svg.arc().outerRadius(r) #select paths, use arc generator to draw arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice") arcs.append("svg:path") .attr("fill", (d) -> return d.data.color) .attr("stroke", (d) -> return if d.data.value == 0 then "none" else "#545454") .attr("stroke-width", 0.25) .attr("d", (d) -> arc(d) ) el = @$(pie_name+"_legend")[0] chart = d3.select(el) legends = chart.selectAll(pie_name+"_legend") .data(data) .enter().insert("div") .attr("class", "legend-row") legends.append("span") .attr("class", "pie-label-swatch") .style('background-color', (d,i) -> d.color) legends.append("span") .text((d,i) -> return data[i].label) .attr("class", "pie-label") addCommas: (num_str) => num_str += '' x = num_str.split('.') x1 = x[0] x2 = if x.length > 1 then '.' + x[1] else '' rgx = /(\d+)(\d{3})/ while rgx.test(x1) x1 = x1.replace(rgx, '$1' + ',' + '$2') return x1 + x2 module.exports = NewAreaOverviewTab
104355
ReportTab = require 'reportTab' templates = require '../templates/templates.js' _partials = require '../node_modules/seasketch-reporting-api/templates/templates.js' partials = [] for key, val of _partials partials[key.replace('node_modules/seasketch-reporting-api/', '')] = val d3 = window.d3 class NewAreaOverviewTab extends ReportTab name: 'Overview' className: 'newAreaOverview' template: templates.newAreaOverview dependencies:[ 'NewReserveHabitatToolbox' 'SizeToolbox' ] render: () -> # create random data for visualization habs = @recordSet('NewReserveHabitatToolbox', 'Habitat').toArray() missing_habs = @recordSet('NewReserveHabitatToolbox', 'MissingHabitat').toArray() console.log("missing: ", missing_habs) hab_count = @recordSet('NewReserveHabitatToolbox', 'HabitatCounts').toArray() isCollection = @model.isCollection() size = @recordSet('SizeToolbox', 'Size').float('Size') size_acres = size*0.000247105 if size_acres < 0.1 if size_acres < 0.01 aoi_size = "< 0.01" else aoi_size = @addCommas size_acres.toFixed(2) else aoi_size = @addCommas size_acres.toFixed(1) try res_name = @recordSet('SizeToolbox', 'ReserveName').raw('ResName') if res_name == null or isCollection aoi_res_name = "no sketches within an existing reserve" isWithinReserve = false aoi_res_url = "" else aoi_res_name = res_name.toString() isWithinReserve = true aoi_res_url = @getURL aoi_res_name catch err aoi_res_name = "no sketches within an existing reserve" isWithinReserve = false aoi_res_url = "" aoi_name = @model.attributes.name aoi_name = aoi_name.charAt(0).toUpperCase() + aoi_name.slice(1) try total_habs = hab_count[0].TOT found_habs = hab_count[0].FOUND missing_hab_count = hab_count[0].MISSING catch err console.log("err getting count ", err) if isCollection sketch_type = "Collection" else sketch_type = "Sketch" if window.d3 d3IsPresent = true else d3IsPresent = false sketch_name = @model.attributes.name found_color = "#b3cfa7" missing_color = "#e5cace" pie_data = @build_values("Habitats Found", found_habs, found_color, "Missing Habitats", missing_hab_count,missing_color) # setup context object with data and render the template from it context = sketch: @model.forTemplate() sketchClass: @sketchClass.forTemplate() attributes: @model.getAttributes() admin: @project.isAdmin window.user isCollection: isCollection d3IsPresent: d3IsPresent habs: habs total_habs: total_habs found_habs: found_habs missing_habs: missing_habs sketch_name: sketch_name sketch_type: sketch_type missing_hab_count: missing_hab_count isWithinReserve: isWithinReserve aoi_size: aoi_size aoi_res_name: aoi_res_name aoi_name: aoi_name aoi_res_url: aoi_res_url @$el.html @template.render(context, templates) @enableTablePaging() @drawPie(pie_data, '#hab_pie') roundData: (items) => for item in items item.AREA = Number(item.AREA).toFixed(1) items = _.sortBy items, (row) -> row.NAME return items build_values: (yes_label, yes_count, yes_color, no_label, no_count, no_color) => yes_val = {"label":yes_label+" ("+yes_count+")", "value":yes_count, "color":yes_color, "yval":50} no_val = {"label":no_label+" ("+no_count+")", "value":no_count, "color":no_color, "yval":75} return [yes_val, no_val] getURL: (name) => try console.log(name) prefix = "http://www.ucnrs.org/reserves/" if name == "Valentine Eastern Sierra Reserve -Valentine Camp" return prefix+"valentine-eastern-sierra-reserve.html" if name == "<NAME>-Borrego Desert Research Center" return prefix+"steeleburnand-anza-borrego-desert-research-center.html" if name == "Burn<NAME> Piñon Ridge Reserve" return prefix+"burns-pinon-ridge-reserve.html" lower = name.toLowerCase() if name == "Ano Nuevo Island" return prefix+"ano-nuevo-island-reserve.html" dashes = lower.replace(/\s+/g, "-") slashes = dashes.replace(/\//g, "") return prefix+slashes+".html" catch err console.log("err getting url: ", err) return "http://www.ucnrs.org/reserves.html" drawPie: (data, pie_name) => if window.d3 w = 160 h = 110 r = 50 vis_el = @$(pie_name)[0] vis = d3.select(vis_el).append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + (r*2) + "," + (r+5) + ")") pie = d3.layout.pie().value((d) -> return d.value) #declare an arc generator function arc = d3.svg.arc().outerRadius(r) #select paths, use arc generator to draw arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice") arcs.append("svg:path") .attr("fill", (d) -> return d.data.color) .attr("stroke", (d) -> return if d.data.value == 0 then "none" else "#545454") .attr("stroke-width", 0.25) .attr("d", (d) -> arc(d) ) el = @$(pie_name+"_legend")[0] chart = d3.select(el) legends = chart.selectAll(pie_name+"_legend") .data(data) .enter().insert("div") .attr("class", "legend-row") legends.append("span") .attr("class", "pie-label-swatch") .style('background-color', (d,i) -> d.color) legends.append("span") .text((d,i) -> return data[i].label) .attr("class", "pie-label") addCommas: (num_str) => num_str += '' x = num_str.split('.') x1 = x[0] x2 = if x.length > 1 then '.' + x[1] else '' rgx = /(\d+)(\d{3})/ while rgx.test(x1) x1 = x1.replace(rgx, '$1' + ',' + '$2') return x1 + x2 module.exports = NewAreaOverviewTab
true
ReportTab = require 'reportTab' templates = require '../templates/templates.js' _partials = require '../node_modules/seasketch-reporting-api/templates/templates.js' partials = [] for key, val of _partials partials[key.replace('node_modules/seasketch-reporting-api/', '')] = val d3 = window.d3 class NewAreaOverviewTab extends ReportTab name: 'Overview' className: 'newAreaOverview' template: templates.newAreaOverview dependencies:[ 'NewReserveHabitatToolbox' 'SizeToolbox' ] render: () -> # create random data for visualization habs = @recordSet('NewReserveHabitatToolbox', 'Habitat').toArray() missing_habs = @recordSet('NewReserveHabitatToolbox', 'MissingHabitat').toArray() console.log("missing: ", missing_habs) hab_count = @recordSet('NewReserveHabitatToolbox', 'HabitatCounts').toArray() isCollection = @model.isCollection() size = @recordSet('SizeToolbox', 'Size').float('Size') size_acres = size*0.000247105 if size_acres < 0.1 if size_acres < 0.01 aoi_size = "< 0.01" else aoi_size = @addCommas size_acres.toFixed(2) else aoi_size = @addCommas size_acres.toFixed(1) try res_name = @recordSet('SizeToolbox', 'ReserveName').raw('ResName') if res_name == null or isCollection aoi_res_name = "no sketches within an existing reserve" isWithinReserve = false aoi_res_url = "" else aoi_res_name = res_name.toString() isWithinReserve = true aoi_res_url = @getURL aoi_res_name catch err aoi_res_name = "no sketches within an existing reserve" isWithinReserve = false aoi_res_url = "" aoi_name = @model.attributes.name aoi_name = aoi_name.charAt(0).toUpperCase() + aoi_name.slice(1) try total_habs = hab_count[0].TOT found_habs = hab_count[0].FOUND missing_hab_count = hab_count[0].MISSING catch err console.log("err getting count ", err) if isCollection sketch_type = "Collection" else sketch_type = "Sketch" if window.d3 d3IsPresent = true else d3IsPresent = false sketch_name = @model.attributes.name found_color = "#b3cfa7" missing_color = "#e5cace" pie_data = @build_values("Habitats Found", found_habs, found_color, "Missing Habitats", missing_hab_count,missing_color) # setup context object with data and render the template from it context = sketch: @model.forTemplate() sketchClass: @sketchClass.forTemplate() attributes: @model.getAttributes() admin: @project.isAdmin window.user isCollection: isCollection d3IsPresent: d3IsPresent habs: habs total_habs: total_habs found_habs: found_habs missing_habs: missing_habs sketch_name: sketch_name sketch_type: sketch_type missing_hab_count: missing_hab_count isWithinReserve: isWithinReserve aoi_size: aoi_size aoi_res_name: aoi_res_name aoi_name: aoi_name aoi_res_url: aoi_res_url @$el.html @template.render(context, templates) @enableTablePaging() @drawPie(pie_data, '#hab_pie') roundData: (items) => for item in items item.AREA = Number(item.AREA).toFixed(1) items = _.sortBy items, (row) -> row.NAME return items build_values: (yes_label, yes_count, yes_color, no_label, no_count, no_color) => yes_val = {"label":yes_label+" ("+yes_count+")", "value":yes_count, "color":yes_color, "yval":50} no_val = {"label":no_label+" ("+no_count+")", "value":no_count, "color":no_color, "yval":75} return [yes_val, no_val] getURL: (name) => try console.log(name) prefix = "http://www.ucnrs.org/reserves/" if name == "Valentine Eastern Sierra Reserve -Valentine Camp" return prefix+"valentine-eastern-sierra-reserve.html" if name == "PI:NAME:<NAME>END_PI-Borrego Desert Research Center" return prefix+"steeleburnand-anza-borrego-desert-research-center.html" if name == "BurnPI:NAME:<NAME>END_PI Piñon Ridge Reserve" return prefix+"burns-pinon-ridge-reserve.html" lower = name.toLowerCase() if name == "Ano Nuevo Island" return prefix+"ano-nuevo-island-reserve.html" dashes = lower.replace(/\s+/g, "-") slashes = dashes.replace(/\//g, "") return prefix+slashes+".html" catch err console.log("err getting url: ", err) return "http://www.ucnrs.org/reserves.html" drawPie: (data, pie_name) => if window.d3 w = 160 h = 110 r = 50 vis_el = @$(pie_name)[0] vis = d3.select(vis_el).append("svg:svg").data([data]).attr("width", w).attr("height", h).append("svg:g").attr("transform", "translate(" + (r*2) + "," + (r+5) + ")") pie = d3.layout.pie().value((d) -> return d.value) #declare an arc generator function arc = d3.svg.arc().outerRadius(r) #select paths, use arc generator to draw arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice") arcs.append("svg:path") .attr("fill", (d) -> return d.data.color) .attr("stroke", (d) -> return if d.data.value == 0 then "none" else "#545454") .attr("stroke-width", 0.25) .attr("d", (d) -> arc(d) ) el = @$(pie_name+"_legend")[0] chart = d3.select(el) legends = chart.selectAll(pie_name+"_legend") .data(data) .enter().insert("div") .attr("class", "legend-row") legends.append("span") .attr("class", "pie-label-swatch") .style('background-color', (d,i) -> d.color) legends.append("span") .text((d,i) -> return data[i].label) .attr("class", "pie-label") addCommas: (num_str) => num_str += '' x = num_str.split('.') x1 = x[0] x2 = if x.length > 1 then '.' + x[1] else '' rgx = /(\d+)(\d{3})/ while rgx.test(x1) x1 = x1.replace(rgx, '$1' + ',' + '$2') return x1 + x2 module.exports = NewAreaOverviewTab
[ { "context": "ons:\n query:\n key: serviceUuid,\n include_docs: true,\n ", "end": 2256, "score": 0.8012104034423828, "start": 2245, "tag": "KEY", "value": "serviceUuid" }, { "context": "if users.length > 0\n i...
_attachments/views/VerifyView.coffee
cmink-alone/sijariemas-webapp
0
VerifyView = Backbone.Marionette.ItemView.extend # template: "VerifyView" template: JST["_attachments/templates/VerifyView.handlebars"]() className: "itemView" # this class will be added to the wrapping div when you render the view events: "click #identifyIndividual": "identifyIndividual" "click #identifyAdmin": "identifyAdmin" "click #scan": "scanNewIndividual" "click #verifyYes": "displayNewUserRegistration" "click #verifyNo": "displayNewUserRegistration" "click #refresh": "refresh" "click #verifySendLogs": "sendLogs" "click #continueAfterFail": "continueAfterFail" nextUrl:null hasCordova:true currentOfflineUser:null initialize: -> @sync = new Sync() if typeof cordova is "undefined" # console.log "cordova is not defined." @hasCordova = false displayNewUserRegistration: -> Coconut.router.navigate "userRegistration", true return diplayNewReportMenu: -> scanNewIndividual:(e) -> # @scan e, "userRegistration" @scan e, "Enroll" return register:(e) -> @scan e, "Enroll" return identifyIndividual:(e) -> @scan e, "Identify", "Individual" return identifyAdmin:(e) -> @scan e, "Identify", "Admin" return scan: (event, method, user) -> this.eventUrl = @nextUrl display = (message) -> console.log "display message: " + message display = document.getElementById("message") # the message div lineBreak = document.createElement("br") # a line break label = document.createTextNode(message) # create the label display.appendChild lineBreak # add a line break display.appendChild label # add the message node return revealSlider = (event, method, user) => startLadda = (e) => l = Ladda.create(e.currentTarget) l.start() # if not typeof cordova is "undefined" findUserFromServiceUUID = (serviceUuid, prints) -> viewOptions = {} users = new SecondaryIndexCollection users.fetch fetch: 'query', options: query: key: serviceUuid, include_docs: true, fun: 'by_serviceUuid' success: => console.log 'by_serviceUuid returned: ' + JSON.stringify users l.stop() # Update the top nav strip # Controller.displaySiteNav() if users.length > 0 if user == "Admin" adminUser = users.first() console.log 'Coconut.currentAdmin: ' + JSON.stringify adminUser Coconut.currentAdmin = adminUser CoconutUtils.setSession('currentAdmin', adminUser.get('email')) Coconut.router.navigate "displayUserScanner", true else client = users.first() console.log 'Coconut.currentClient: ' + JSON.stringify client Coconut.currentClient = client CoconutUtils.setSession('currentClient', true) Coconut.router.navigate "displayClientRecords", true else message = 'Strange. This user was identified but is not registered. User: ' + user console.log message $('#progress').append "<br/>" + message uuid = CoconutUtils.uuidGenerator(30) Coconut.currentClient = new Result _id: uuid serviceUuid: serviceUuid # Template: scannerPayload.Template Fingerprints: prints console.log "currentClient: " + JSON.stringify Coconut.currentClient if user == "Admin" Coconut.currentAdmin = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: prints console.log "currentAdmin: " + JSON.stringify Coconut.currentAdmin CoconutUtils.setSession('currentAdmin', null) Coconut.trigger "displayAdminRegistrationForm" else Coconut.trigger "displayUserRegistrationForm" if @hasCordova console.log "method: " + method if (method == "Identify") cordova.plugins.SecugenPlugin.scan (results) => finger = $('#Finger').val(); payload = {} payload["Key"] = Coconut.config.get("AfisServerKey") payload["Name"] = Coconut.config.get("AfisProjectName") payload["Template"] = results payload["Finger"] = finger console.log "payload: " + JSON.stringify payload template = payload.Template # Set things up for future handling of multiple fingerprints fingerprint = {} fingerprint.template = template fingerprint.finger = finger prints = [] prints.push(fingerprint) # used when print upload fails and Continue button is pressed. Coconut.currentPrints = prints urlServer = Coconut.config.get("AfisServerUrl") + Coconut.config.get("AfisServerUrlFilepath") + "Identify"; timeout = 15000 $('#progress').append "<br/>Fingerprint scanned. Now uploading to server. User: " + user $('#progress').append "<br/>Server URL: " + urlServer $('#progress').append "<br/>Timeout: " + timeout $.ajaxSetup type:'POST' timeout:timeout error: (xhr)=> l.stop() @currentOfflineUser = user; if user == 'Admin' # Error uploading scan # Operating in offline-mode. Press Continue to scan a new patient. message = polyglot.t("errorUploadingScan") + ": " + xhr.statusText + " . " + polyglot.t("offlineScanContinueAdmin") else # Operating in offline-mode. Press Continue to enroll this new patient. message = polyglot.t("errorUploadingScan") + ": " + xhr.statusText + " . " + polyglot.t("offlineScanContinueNewPatient") $("#uploadFailedMessage").html(message) $("#uploadFailed").css({ "display": "block" }) console.log message console.log "Fingerprint server URL: " + urlServer $('#progress').append message $.post(urlServer, payload, (result) => console.log "response from service: " + JSON.stringify result $('#progress').append "<br/>Received response from service. StatusCode: " + statusCode try scannerPayload = payload["Template"] statusCode = result.StatusCode serviceUuid = result.UID console.log 'query for serviceUuid: ' + serviceUuid catch error console.log error $('#progress').append "<br/>Error uploading scan: " + error if statusCode != null && statusCode == 1 $('#progress').append "<br/>Locating user in local database." findUserFromServiceUUID(serviceUuid, prints) else if statusCode != null && statusCode == 4 $('#progress').append "<br/>User not in the local database." # Status Code 4 = No Person found l.stop() if user == 'Admin' CoconutUtils.setSession('currentAdmin', null) else CoconutUtils.setSession('currentClient', true) $('#progress').append "<br/>Enrolling new fingerprint. User: " + user urlServer = Coconut.config.get("AfisServerUrl") + Coconut.config.get("AfisServerUrlFilepath") + "Enroll"; $.post(urlServer, payload, (result) => console.log "response from service: " + JSON.stringify result statusCode = result.StatusCode serviceUuid = result.UID console.log "statusCode: " + statusCode if statusCode != null if statusCode == 1 # $( "#progress" ).html( 'Fingerprint enrolled. Success!' ); $('#progress').append "<br/>Fingerprint enrolled. Success! User: " + user @registerEnrolledPerson(serviceUuid, prints, user) else $( "#progress" ).append( 'Problem enrolling fingerprint. StatusCode: ' + statusCode); Coconut.trigger "displayEnroll" , "json") else l.stop() $( "#message").append("Problem processing fingerprint. StatusCode: " + statusCode) # Coconut.scannerPayload = payload log = new Log() log.save {message: "Problem processing fingerprint.", statusCode:statusCode}, success: () => $( "#message").append("<br/>Saved log about problem.") console.log("Saved log about problem.") , error: (model, err, cb) => console.log(JSON.stringify(err)) , "json") , (error) -> l.stop() console.log("SecugenPlugin.scan error: " + error) message = error if error == "Scan failed: Unable to capture fingerprint. Please kill the app in the Task Manager and restart the app." message = '<p>' + polyglot.t("scanFailed") + '<br/><a data-role="button" id="refresh" class="btn btn-primary btn-lg" data-style="expand-right">Refresh</a></p>' else message = '<p> Error: ' + error + " " + polyglot.t("scanFailed") + '<br/><a data-role="button" id="refresh" class="btn btn-primary btn-lg" data-style="expand-right">Refresh</a></p>' $("#message").html message log = new Log() log.save {message: "Problem scanning fingerprint.", error:error}, success: () => $( "#message").append("<br/>Saved log about problem.") console.log("Saved log about problem.") , error: (model, err, cb) => console.log(JSON.stringify(err)) else i=1 interval = setInterval => if i == 50 uuid = CoconutUtils.uuidGenerator(30) serviceUuid = CoconutUtils.uuidGenerator(30) console.log("Go to next page. Generated UUID: " + uuid) Coconut.scannerPayload = "Template":"46 4D 52 00 20 32 30 00 00 00 00 F0 00 00 01 04 01 2C 00 C5 00 C5 01 00 00 00 00 23 40 83 00 40 71 00 40 52 00 53 75 00 80 33 00 6B 8A 00 80 A9 00 6C 72 00 40 5B 00 81 7D 00 80 93 00 87 71 00 40 28 00 99 91 00 40 17 00 A1 11 00 40 44 00 A9 8D 00 40 81 00 B8 78 00 40 1B 00 BA 10 00 40 73 00 C2 80 00 40 3F 00 C3 94 00 40 DF 00 C7 E8 00 80 4B 00 CE 11 00 40 32 00 D6 91 00 40 16 00 D8 14 00 80 3D 00 E0 10 00 40 1A 00 E2 11 00 40 A3 00 E3 EE 00 40 38 00 F3 94 00 40 9E 00 F5 73 00 40 6D 00 FB 00 00 40 56 00 FC 93 00 40 A8 00 FC E3 00 40 26 00 FC 11 00 40 40 00 FD 10 00 40 7C 01 01 F8 00 80 C9 01 03 EA 00 40 38 01 04 9A 00 80 6D 01 07 7F 00 40 9E 01 0E 6C 00 40 32 01 10 17 00 40 88 01 11 EE 00 80 88 01 23 72 00 00 00 ", "Name":"Test CK", "email":"someone@somewhere.com", "Finger":1, "Key":"HH8XGFYSDU9QGZ833" Coconut.currentClient = new Result _id: uuid serviceUuid:serviceUuid $( "#message").html("Scanning complete!") if user == "Admin" Coconut.currentAdmin = Coconut.currentClient CoconutUtils.setSession('currentAdmin', Coconut.scannerPayload.email) l.stop() if @nextUrl? Coconut.router.navigate @nextUrl, true else Coconut.router.navigate "registration", true # window.setTimeout => # Coconut.router.navigate("registration") # , 2000 clearInterval(interval); i++ ,50 return false; console.log "revealSlider" progress = document.querySelector("paper-progress") button = document.querySelector("paper-button") # thisSliderId = sliderId if typeof sliderId isnt "undefined" # startProgress() startLadda(event) repeat = undefined maxRepeat = 5 # addEventListener "polymer-ready", -> # startProgress() # return # return revealSlider event, method, user display: (message) -> console.log "display message." display = document.getElementById("message") # the message div lineBreak = document.createElement("br") # a line break label = document.createTextNode(message) # create the label display.appendChild lineBreak # add a line break display.appendChild label # add the message node return refresh: -> Coconut.router.navigate("",false) location.reload() sendLogs: -> @sync.sendLogs('#progress') registerEnrolledPerson: (serviceUuid, prints, user, createdOffline) -> if createdOffline uuid = 'oflId-' + CoconutUtils.uuidGenerator(30) else uuid = CoconutUtils.uuidGenerator(30) Coconut.currentClient = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: prints if createdOffline Coconut.currentClient.createdOffline = true if typeof user != 'undefined' && user != null && user == 'Individual' Coconut.trigger "displayUserRegistrationForm" else Coconut.trigger "displayAdminRegistrationForm" continueAfterFail: -> serviceUuid = 'oflSid-' + CoconutUtils.uuidGenerator(30) user = @currentOfflineUser Coconut.offlineUser = true console.log('Continuing after the fail. User: ' + user) if user == "Admin" users = new SecondaryIndexCollection users.fetch fetch: 'query', options: query: include_docs: true, fun: 'by_AdminRegistration' success: => console.log 'by_AdminRegistration returned: ' + JSON.stringify users if users.length > 0 adminUser = users.first() console.log 'Coconut.currentAdmin: ' + JSON.stringify adminUser Coconut.currentAdmin = adminUser CoconutUtils.setSession('currentAdmin', adminUser.get('email')) Coconut.router.navigate "displayUserScanner", true else message = 'Strange. There should already be an Admin user. ' console.log message $('#progress').append "<br/>" + message uuid = 'oflId-' + CoconutUtils.uuidGenerator(30) Coconut.currentAdmin = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: Coconut.currentPrints console.log "currentAdmin: " + JSON.stringify Coconut.currentAdmin CoconutUtils.setSession('currentAdmin', null) Coconut.trigger "displayAdminRegistrationForm" else @registerEnrolledPerson(serviceUuid, Coconut.currentPrints, user, true)
186632
VerifyView = Backbone.Marionette.ItemView.extend # template: "VerifyView" template: JST["_attachments/templates/VerifyView.handlebars"]() className: "itemView" # this class will be added to the wrapping div when you render the view events: "click #identifyIndividual": "identifyIndividual" "click #identifyAdmin": "identifyAdmin" "click #scan": "scanNewIndividual" "click #verifyYes": "displayNewUserRegistration" "click #verifyNo": "displayNewUserRegistration" "click #refresh": "refresh" "click #verifySendLogs": "sendLogs" "click #continueAfterFail": "continueAfterFail" nextUrl:null hasCordova:true currentOfflineUser:null initialize: -> @sync = new Sync() if typeof cordova is "undefined" # console.log "cordova is not defined." @hasCordova = false displayNewUserRegistration: -> Coconut.router.navigate "userRegistration", true return diplayNewReportMenu: -> scanNewIndividual:(e) -> # @scan e, "userRegistration" @scan e, "Enroll" return register:(e) -> @scan e, "Enroll" return identifyIndividual:(e) -> @scan e, "Identify", "Individual" return identifyAdmin:(e) -> @scan e, "Identify", "Admin" return scan: (event, method, user) -> this.eventUrl = @nextUrl display = (message) -> console.log "display message: " + message display = document.getElementById("message") # the message div lineBreak = document.createElement("br") # a line break label = document.createTextNode(message) # create the label display.appendChild lineBreak # add a line break display.appendChild label # add the message node return revealSlider = (event, method, user) => startLadda = (e) => l = Ladda.create(e.currentTarget) l.start() # if not typeof cordova is "undefined" findUserFromServiceUUID = (serviceUuid, prints) -> viewOptions = {} users = new SecondaryIndexCollection users.fetch fetch: 'query', options: query: key: <KEY>, include_docs: true, fun: 'by_serviceUuid' success: => console.log 'by_serviceUuid returned: ' + JSON.stringify users l.stop() # Update the top nav strip # Controller.displaySiteNav() if users.length > 0 if user == "Admin" adminUser = users.first() console.log 'Coconut.currentAdmin: ' + JSON.stringify adminUser Coconut.currentAdmin = adminUser CoconutUtils.setSession('currentAdmin', adminUser.get('email')) Coconut.router.navigate "displayUserScanner", true else client = users.first() console.log 'Coconut.currentClient: ' + JSON.stringify client Coconut.currentClient = client CoconutUtils.setSession('currentClient', true) Coconut.router.navigate "displayClientRecords", true else message = 'Strange. This user was identified but is not registered. User: ' + user console.log message $('#progress').append "<br/>" + message uuid = CoconutUtils.uuidGenerator(30) Coconut.currentClient = new Result _id: uuid serviceUuid: serviceUuid # Template: scannerPayload.Template Fingerprints: prints console.log "currentClient: " + JSON.stringify Coconut.currentClient if user == "Admin" Coconut.currentAdmin = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: prints console.log "currentAdmin: " + JSON.stringify Coconut.currentAdmin CoconutUtils.setSession('currentAdmin', null) Coconut.trigger "displayAdminRegistrationForm" else Coconut.trigger "displayUserRegistrationForm" if @hasCordova console.log "method: " + method if (method == "Identify") cordova.plugins.SecugenPlugin.scan (results) => finger = $('#Finger').val(); payload = {} payload["Key"] = Coconut.config.get("AfisServerKey") payload["Name"] = Coconut.config.get("AfisProjectName") payload["Template"] = results payload["Finger"] = finger console.log "payload: " + JSON.stringify payload template = payload.Template # Set things up for future handling of multiple fingerprints fingerprint = {} fingerprint.template = template fingerprint.finger = finger prints = [] prints.push(fingerprint) # used when print upload fails and Continue button is pressed. Coconut.currentPrints = prints urlServer = Coconut.config.get("AfisServerUrl") + Coconut.config.get("AfisServerUrlFilepath") + "Identify"; timeout = 15000 $('#progress').append "<br/>Fingerprint scanned. Now uploading to server. User: " + user $('#progress').append "<br/>Server URL: " + urlServer $('#progress').append "<br/>Timeout: " + timeout $.ajaxSetup type:'POST' timeout:timeout error: (xhr)=> l.stop() @currentOfflineUser = user; if user == 'Admin' # Error uploading scan # Operating in offline-mode. Press Continue to scan a new patient. message = polyglot.t("errorUploadingScan") + ": " + xhr.statusText + " . " + polyglot.t("offlineScanContinueAdmin") else # Operating in offline-mode. Press Continue to enroll this new patient. message = polyglot.t("errorUploadingScan") + ": " + xhr.statusText + " . " + polyglot.t("offlineScanContinueNewPatient") $("#uploadFailedMessage").html(message) $("#uploadFailed").css({ "display": "block" }) console.log message console.log "Fingerprint server URL: " + urlServer $('#progress').append message $.post(urlServer, payload, (result) => console.log "response from service: " + JSON.stringify result $('#progress').append "<br/>Received response from service. StatusCode: " + statusCode try scannerPayload = payload["Template"] statusCode = result.StatusCode serviceUuid = result.UID console.log 'query for serviceUuid: ' + serviceUuid catch error console.log error $('#progress').append "<br/>Error uploading scan: " + error if statusCode != null && statusCode == 1 $('#progress').append "<br/>Locating user in local database." findUserFromServiceUUID(serviceUuid, prints) else if statusCode != null && statusCode == 4 $('#progress').append "<br/>User not in the local database." # Status Code 4 = No Person found l.stop() if user == 'Admin' CoconutUtils.setSession('currentAdmin', null) else CoconutUtils.setSession('currentClient', true) $('#progress').append "<br/>Enrolling new fingerprint. User: " + user urlServer = Coconut.config.get("AfisServerUrl") + Coconut.config.get("AfisServerUrlFilepath") + "Enroll"; $.post(urlServer, payload, (result) => console.log "response from service: " + JSON.stringify result statusCode = result.StatusCode serviceUuid = result.UID console.log "statusCode: " + statusCode if statusCode != null if statusCode == 1 # $( "#progress" ).html( 'Fingerprint enrolled. Success!' ); $('#progress').append "<br/>Fingerprint enrolled. Success! User: " + user @registerEnrolledPerson(serviceUuid, prints, user) else $( "#progress" ).append( 'Problem enrolling fingerprint. StatusCode: ' + statusCode); Coconut.trigger "displayEnroll" , "json") else l.stop() $( "#message").append("Problem processing fingerprint. StatusCode: " + statusCode) # Coconut.scannerPayload = payload log = new Log() log.save {message: "Problem processing fingerprint.", statusCode:statusCode}, success: () => $( "#message").append("<br/>Saved log about problem.") console.log("Saved log about problem.") , error: (model, err, cb) => console.log(JSON.stringify(err)) , "json") , (error) -> l.stop() console.log("SecugenPlugin.scan error: " + error) message = error if error == "Scan failed: Unable to capture fingerprint. Please kill the app in the Task Manager and restart the app." message = '<p>' + polyglot.t("scanFailed") + '<br/><a data-role="button" id="refresh" class="btn btn-primary btn-lg" data-style="expand-right">Refresh</a></p>' else message = '<p> Error: ' + error + " " + polyglot.t("scanFailed") + '<br/><a data-role="button" id="refresh" class="btn btn-primary btn-lg" data-style="expand-right">Refresh</a></p>' $("#message").html message log = new Log() log.save {message: "Problem scanning fingerprint.", error:error}, success: () => $( "#message").append("<br/>Saved log about problem.") console.log("Saved log about problem.") , error: (model, err, cb) => console.log(JSON.stringify(err)) else i=1 interval = setInterval => if i == 50 uuid = CoconutUtils.uuidGenerator(30) serviceUuid = CoconutUtils.uuidGenerator(30) console.log("Go to next page. Generated UUID: " + uuid) Coconut.scannerPayload = "Template":"46 4D 52 00 20 32 30 00 00 00 00 F0 00 00 01 04 01 2C 00 C5 00 C5 01 00 00 00 00 23 40 83 00 40 71 00 40 52 00 53 75 00 80 33 00 6B 8A 00 80 A9 00 6C 72 00 40 5B 00 81 7D 00 80 93 00 87 71 00 40 28 00 99 91 00 40 17 00 A1 11 00 40 44 00 A9 8D 00 40 81 00 B8 78 00 40 1B 00 BA 10 00 40 73 00 C2 80 00 40 3F 00 C3 94 00 40 DF 00 C7 E8 00 80 4B 00 CE 11 00 40 32 00 D6 91 00 40 16 00 D8 14 00 80 3D 00 E0 10 00 40 1A 00 E2 11 00 40 A3 00 E3 EE 00 40 38 00 F3 94 00 40 9E 00 F5 73 00 40 6D 00 FB 00 00 40 56 00 FC 93 00 40 A8 00 FC E3 00 40 26 00 FC 11 00 40 40 00 FD 10 00 40 7C 01 01 F8 00 80 C9 01 03 EA 00 40 38 01 04 9A 00 80 6D 01 07 7F 00 40 9E 01 0E 6C 00 40 32 01 10 17 00 40 88 01 11 EE 00 80 88 01 23 72 00 00 00 ", "Name":"<NAME>", "email":"<EMAIL>", "Finger":1, "Key":"<KEY>" Coconut.currentClient = new Result _id: uuid serviceUuid:serviceUuid $( "#message").html("Scanning complete!") if user == "Admin" Coconut.currentAdmin = Coconut.currentClient CoconutUtils.setSession('currentAdmin', Coconut.scannerPayload.email) l.stop() if @nextUrl? Coconut.router.navigate @nextUrl, true else Coconut.router.navigate "registration", true # window.setTimeout => # Coconut.router.navigate("registration") # , 2000 clearInterval(interval); i++ ,50 return false; console.log "revealSlider" progress = document.querySelector("paper-progress") button = document.querySelector("paper-button") # thisSliderId = sliderId if typeof sliderId isnt "undefined" # startProgress() startLadda(event) repeat = undefined maxRepeat = 5 # addEventListener "polymer-ready", -> # startProgress() # return # return revealSlider event, method, user display: (message) -> console.log "display message." display = document.getElementById("message") # the message div lineBreak = document.createElement("br") # a line break label = document.createTextNode(message) # create the label display.appendChild lineBreak # add a line break display.appendChild label # add the message node return refresh: -> Coconut.router.navigate("",false) location.reload() sendLogs: -> @sync.sendLogs('#progress') registerEnrolledPerson: (serviceUuid, prints, user, createdOffline) -> if createdOffline uuid = 'oflId-' + CoconutUtils.uuidGenerator(30) else uuid = CoconutUtils.uuidGenerator(30) Coconut.currentClient = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: prints if createdOffline Coconut.currentClient.createdOffline = true if typeof user != 'undefined' && user != null && user == 'Individual' Coconut.trigger "displayUserRegistrationForm" else Coconut.trigger "displayAdminRegistrationForm" continueAfterFail: -> serviceUuid = 'oflSid-' + CoconutUtils.uuidGenerator(30) user = @currentOfflineUser Coconut.offlineUser = true console.log('Continuing after the fail. User: ' + user) if user == "Admin" users = new SecondaryIndexCollection users.fetch fetch: 'query', options: query: include_docs: true, fun: 'by_AdminRegistration' success: => console.log 'by_AdminRegistration returned: ' + JSON.stringify users if users.length > 0 adminUser = users.first() console.log 'Coconut.currentAdmin: ' + JSON.stringify adminUser Coconut.currentAdmin = adminUser CoconutUtils.setSession('currentAdmin', adminUser.get('email')) Coconut.router.navigate "displayUserScanner", true else message = 'Strange. There should already be an Admin user. ' console.log message $('#progress').append "<br/>" + message uuid = 'oflId-' + CoconutUtils.uuidGenerator(30) Coconut.currentAdmin = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: Coconut.currentPrints console.log "currentAdmin: " + JSON.stringify Coconut.currentAdmin CoconutUtils.setSession('currentAdmin', null) Coconut.trigger "displayAdminRegistrationForm" else @registerEnrolledPerson(serviceUuid, Coconut.currentPrints, user, true)
true
VerifyView = Backbone.Marionette.ItemView.extend # template: "VerifyView" template: JST["_attachments/templates/VerifyView.handlebars"]() className: "itemView" # this class will be added to the wrapping div when you render the view events: "click #identifyIndividual": "identifyIndividual" "click #identifyAdmin": "identifyAdmin" "click #scan": "scanNewIndividual" "click #verifyYes": "displayNewUserRegistration" "click #verifyNo": "displayNewUserRegistration" "click #refresh": "refresh" "click #verifySendLogs": "sendLogs" "click #continueAfterFail": "continueAfterFail" nextUrl:null hasCordova:true currentOfflineUser:null initialize: -> @sync = new Sync() if typeof cordova is "undefined" # console.log "cordova is not defined." @hasCordova = false displayNewUserRegistration: -> Coconut.router.navigate "userRegistration", true return diplayNewReportMenu: -> scanNewIndividual:(e) -> # @scan e, "userRegistration" @scan e, "Enroll" return register:(e) -> @scan e, "Enroll" return identifyIndividual:(e) -> @scan e, "Identify", "Individual" return identifyAdmin:(e) -> @scan e, "Identify", "Admin" return scan: (event, method, user) -> this.eventUrl = @nextUrl display = (message) -> console.log "display message: " + message display = document.getElementById("message") # the message div lineBreak = document.createElement("br") # a line break label = document.createTextNode(message) # create the label display.appendChild lineBreak # add a line break display.appendChild label # add the message node return revealSlider = (event, method, user) => startLadda = (e) => l = Ladda.create(e.currentTarget) l.start() # if not typeof cordova is "undefined" findUserFromServiceUUID = (serviceUuid, prints) -> viewOptions = {} users = new SecondaryIndexCollection users.fetch fetch: 'query', options: query: key: PI:KEY:<KEY>END_PI, include_docs: true, fun: 'by_serviceUuid' success: => console.log 'by_serviceUuid returned: ' + JSON.stringify users l.stop() # Update the top nav strip # Controller.displaySiteNav() if users.length > 0 if user == "Admin" adminUser = users.first() console.log 'Coconut.currentAdmin: ' + JSON.stringify adminUser Coconut.currentAdmin = adminUser CoconutUtils.setSession('currentAdmin', adminUser.get('email')) Coconut.router.navigate "displayUserScanner", true else client = users.first() console.log 'Coconut.currentClient: ' + JSON.stringify client Coconut.currentClient = client CoconutUtils.setSession('currentClient', true) Coconut.router.navigate "displayClientRecords", true else message = 'Strange. This user was identified but is not registered. User: ' + user console.log message $('#progress').append "<br/>" + message uuid = CoconutUtils.uuidGenerator(30) Coconut.currentClient = new Result _id: uuid serviceUuid: serviceUuid # Template: scannerPayload.Template Fingerprints: prints console.log "currentClient: " + JSON.stringify Coconut.currentClient if user == "Admin" Coconut.currentAdmin = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: prints console.log "currentAdmin: " + JSON.stringify Coconut.currentAdmin CoconutUtils.setSession('currentAdmin', null) Coconut.trigger "displayAdminRegistrationForm" else Coconut.trigger "displayUserRegistrationForm" if @hasCordova console.log "method: " + method if (method == "Identify") cordova.plugins.SecugenPlugin.scan (results) => finger = $('#Finger').val(); payload = {} payload["Key"] = Coconut.config.get("AfisServerKey") payload["Name"] = Coconut.config.get("AfisProjectName") payload["Template"] = results payload["Finger"] = finger console.log "payload: " + JSON.stringify payload template = payload.Template # Set things up for future handling of multiple fingerprints fingerprint = {} fingerprint.template = template fingerprint.finger = finger prints = [] prints.push(fingerprint) # used when print upload fails and Continue button is pressed. Coconut.currentPrints = prints urlServer = Coconut.config.get("AfisServerUrl") + Coconut.config.get("AfisServerUrlFilepath") + "Identify"; timeout = 15000 $('#progress').append "<br/>Fingerprint scanned. Now uploading to server. User: " + user $('#progress').append "<br/>Server URL: " + urlServer $('#progress').append "<br/>Timeout: " + timeout $.ajaxSetup type:'POST' timeout:timeout error: (xhr)=> l.stop() @currentOfflineUser = user; if user == 'Admin' # Error uploading scan # Operating in offline-mode. Press Continue to scan a new patient. message = polyglot.t("errorUploadingScan") + ": " + xhr.statusText + " . " + polyglot.t("offlineScanContinueAdmin") else # Operating in offline-mode. Press Continue to enroll this new patient. message = polyglot.t("errorUploadingScan") + ": " + xhr.statusText + " . " + polyglot.t("offlineScanContinueNewPatient") $("#uploadFailedMessage").html(message) $("#uploadFailed").css({ "display": "block" }) console.log message console.log "Fingerprint server URL: " + urlServer $('#progress').append message $.post(urlServer, payload, (result) => console.log "response from service: " + JSON.stringify result $('#progress').append "<br/>Received response from service. StatusCode: " + statusCode try scannerPayload = payload["Template"] statusCode = result.StatusCode serviceUuid = result.UID console.log 'query for serviceUuid: ' + serviceUuid catch error console.log error $('#progress').append "<br/>Error uploading scan: " + error if statusCode != null && statusCode == 1 $('#progress').append "<br/>Locating user in local database." findUserFromServiceUUID(serviceUuid, prints) else if statusCode != null && statusCode == 4 $('#progress').append "<br/>User not in the local database." # Status Code 4 = No Person found l.stop() if user == 'Admin' CoconutUtils.setSession('currentAdmin', null) else CoconutUtils.setSession('currentClient', true) $('#progress').append "<br/>Enrolling new fingerprint. User: " + user urlServer = Coconut.config.get("AfisServerUrl") + Coconut.config.get("AfisServerUrlFilepath") + "Enroll"; $.post(urlServer, payload, (result) => console.log "response from service: " + JSON.stringify result statusCode = result.StatusCode serviceUuid = result.UID console.log "statusCode: " + statusCode if statusCode != null if statusCode == 1 # $( "#progress" ).html( 'Fingerprint enrolled. Success!' ); $('#progress').append "<br/>Fingerprint enrolled. Success! User: " + user @registerEnrolledPerson(serviceUuid, prints, user) else $( "#progress" ).append( 'Problem enrolling fingerprint. StatusCode: ' + statusCode); Coconut.trigger "displayEnroll" , "json") else l.stop() $( "#message").append("Problem processing fingerprint. StatusCode: " + statusCode) # Coconut.scannerPayload = payload log = new Log() log.save {message: "Problem processing fingerprint.", statusCode:statusCode}, success: () => $( "#message").append("<br/>Saved log about problem.") console.log("Saved log about problem.") , error: (model, err, cb) => console.log(JSON.stringify(err)) , "json") , (error) -> l.stop() console.log("SecugenPlugin.scan error: " + error) message = error if error == "Scan failed: Unable to capture fingerprint. Please kill the app in the Task Manager and restart the app." message = '<p>' + polyglot.t("scanFailed") + '<br/><a data-role="button" id="refresh" class="btn btn-primary btn-lg" data-style="expand-right">Refresh</a></p>' else message = '<p> Error: ' + error + " " + polyglot.t("scanFailed") + '<br/><a data-role="button" id="refresh" class="btn btn-primary btn-lg" data-style="expand-right">Refresh</a></p>' $("#message").html message log = new Log() log.save {message: "Problem scanning fingerprint.", error:error}, success: () => $( "#message").append("<br/>Saved log about problem.") console.log("Saved log about problem.") , error: (model, err, cb) => console.log(JSON.stringify(err)) else i=1 interval = setInterval => if i == 50 uuid = CoconutUtils.uuidGenerator(30) serviceUuid = CoconutUtils.uuidGenerator(30) console.log("Go to next page. Generated UUID: " + uuid) Coconut.scannerPayload = "Template":"46 4D 52 00 20 32 30 00 00 00 00 F0 00 00 01 04 01 2C 00 C5 00 C5 01 00 00 00 00 23 40 83 00 40 71 00 40 52 00 53 75 00 80 33 00 6B 8A 00 80 A9 00 6C 72 00 40 5B 00 81 7D 00 80 93 00 87 71 00 40 28 00 99 91 00 40 17 00 A1 11 00 40 44 00 A9 8D 00 40 81 00 B8 78 00 40 1B 00 BA 10 00 40 73 00 C2 80 00 40 3F 00 C3 94 00 40 DF 00 C7 E8 00 80 4B 00 CE 11 00 40 32 00 D6 91 00 40 16 00 D8 14 00 80 3D 00 E0 10 00 40 1A 00 E2 11 00 40 A3 00 E3 EE 00 40 38 00 F3 94 00 40 9E 00 F5 73 00 40 6D 00 FB 00 00 40 56 00 FC 93 00 40 A8 00 FC E3 00 40 26 00 FC 11 00 40 40 00 FD 10 00 40 7C 01 01 F8 00 80 C9 01 03 EA 00 40 38 01 04 9A 00 80 6D 01 07 7F 00 40 9E 01 0E 6C 00 40 32 01 10 17 00 40 88 01 11 EE 00 80 88 01 23 72 00 00 00 ", "Name":"PI:NAME:<NAME>END_PI", "email":"PI:EMAIL:<EMAIL>END_PI", "Finger":1, "Key":"PI:KEY:<KEY>END_PI" Coconut.currentClient = new Result _id: uuid serviceUuid:serviceUuid $( "#message").html("Scanning complete!") if user == "Admin" Coconut.currentAdmin = Coconut.currentClient CoconutUtils.setSession('currentAdmin', Coconut.scannerPayload.email) l.stop() if @nextUrl? Coconut.router.navigate @nextUrl, true else Coconut.router.navigate "registration", true # window.setTimeout => # Coconut.router.navigate("registration") # , 2000 clearInterval(interval); i++ ,50 return false; console.log "revealSlider" progress = document.querySelector("paper-progress") button = document.querySelector("paper-button") # thisSliderId = sliderId if typeof sliderId isnt "undefined" # startProgress() startLadda(event) repeat = undefined maxRepeat = 5 # addEventListener "polymer-ready", -> # startProgress() # return # return revealSlider event, method, user display: (message) -> console.log "display message." display = document.getElementById("message") # the message div lineBreak = document.createElement("br") # a line break label = document.createTextNode(message) # create the label display.appendChild lineBreak # add a line break display.appendChild label # add the message node return refresh: -> Coconut.router.navigate("",false) location.reload() sendLogs: -> @sync.sendLogs('#progress') registerEnrolledPerson: (serviceUuid, prints, user, createdOffline) -> if createdOffline uuid = 'oflId-' + CoconutUtils.uuidGenerator(30) else uuid = CoconutUtils.uuidGenerator(30) Coconut.currentClient = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: prints if createdOffline Coconut.currentClient.createdOffline = true if typeof user != 'undefined' && user != null && user == 'Individual' Coconut.trigger "displayUserRegistrationForm" else Coconut.trigger "displayAdminRegistrationForm" continueAfterFail: -> serviceUuid = 'oflSid-' + CoconutUtils.uuidGenerator(30) user = @currentOfflineUser Coconut.offlineUser = true console.log('Continuing after the fail. User: ' + user) if user == "Admin" users = new SecondaryIndexCollection users.fetch fetch: 'query', options: query: include_docs: true, fun: 'by_AdminRegistration' success: => console.log 'by_AdminRegistration returned: ' + JSON.stringify users if users.length > 0 adminUser = users.first() console.log 'Coconut.currentAdmin: ' + JSON.stringify adminUser Coconut.currentAdmin = adminUser CoconutUtils.setSession('currentAdmin', adminUser.get('email')) Coconut.router.navigate "displayUserScanner", true else message = 'Strange. There should already be an Admin user. ' console.log message $('#progress').append "<br/>" + message uuid = 'oflId-' + CoconutUtils.uuidGenerator(30) Coconut.currentAdmin = new Result _id: uuid serviceUuid: serviceUuid Fingerprints: Coconut.currentPrints console.log "currentAdmin: " + JSON.stringify Coconut.currentAdmin CoconutUtils.setSession('currentAdmin', null) Coconut.trigger "displayAdminRegistrationForm" else @registerEnrolledPerson(serviceUuid, Coconut.currentPrints, user, true)
[ { "context": "\n person:\n identity:\n name: \"John\"\n surname: null\n\n schema =\n pers", "end": 188, "score": 0.9997617602348328, "start": 184, "tag": "NAME", "value": "John" } ]
tests/20-nested-objects.coffee
jhiver/validate-nosuck
0
{ check, validate } = require '../lib/index' describe 'nested object', -> it 'should check lots of stuff', (done) -> object = person: identity: name: "John" surname: null schema = person: check().optional().schema( identity: check().schema( name: check().string() surname: check().string() ) ) validate(object) .with(schema) .then (errors) -> unless errors then return done("should have errors") unless errors.person.identity.surname is 'required' then return done("person.identity.surname should be required") return done() return null
20763
{ check, validate } = require '../lib/index' describe 'nested object', -> it 'should check lots of stuff', (done) -> object = person: identity: name: "<NAME>" surname: null schema = person: check().optional().schema( identity: check().schema( name: check().string() surname: check().string() ) ) validate(object) .with(schema) .then (errors) -> unless errors then return done("should have errors") unless errors.person.identity.surname is 'required' then return done("person.identity.surname should be required") return done() return null
true
{ check, validate } = require '../lib/index' describe 'nested object', -> it 'should check lots of stuff', (done) -> object = person: identity: name: "PI:NAME:<NAME>END_PI" surname: null schema = person: check().optional().schema( identity: check().schema( name: check().string() surname: check().string() ) ) validate(object) .with(schema) .then (errors) -> unless errors then return done("should have errors") unless errors.person.identity.surname is 'required' then return done("person.identity.surname should be required") return done() return null
[ { "context": "Aoede v1.0</div>\n <div id=\"subtitle\">Written by Pyraxo</div>\n </div>\n\"\"\"\n\nupdate: (output, domEl) ->\n ", "end": 1070, "score": 0.6806681156158447, "start": 1065, "tag": "NAME", "value": "Pyrax" } ]
Aoede.widget/index.coffee
Pyraxo/aoede
5
command: "osascript 'Aoede.widget/music.scpt'" refreshFrequency: 1000 style: """ @font-face font-family: NexaBold src: url(fonts/Nexa_Bold.ttf) @font-face font-family: NexaLight src: url(fonts/Nexa_Light.ttf) position: absolute bottom: 40px left: 40px color: rgb(255,255,255,0.8) display: flex #art>img height: 100px width: 100px // border-radius: 10% #content font-size: 0.8em position: absolute height: 100px width: calc(100vw - 80px) white-space: nowrap overflow: hidden #title font-family: NexaBold, Hiragino Kaku Gothic StdN W8 font-weight: 700 font-size: 2.7rem line-height: 80px padding-left: 20px text-transform: uppercase #subtitle font-family: NexaLight font-weight: 100 font-size: 1.8rem line-height: 5px position: absolute bottom: 20px padding-left: 20px text-transform: uppercase """ render: -> """ <div id="art"></div> <div id="content"> <div id="title">Aoede v1.0</div> <div id="subtitle">Written by Pyraxo</div> </div> """ update: (output, domEl) -> name_chars = 30 album_chars = 40 args = output.split("^") if $(domEl).find('#title').text().substring(0, 20) == args[0].substring(0, 20) return if args[0].length > name_chars args[0] = args[0].substring(0, 20)+" •••" if args[1].length > album_chars args[1] = args[1].substring(0, 25)+" ..." $(domEl).find('#title').text("#{args[0]}") $(domEl).find('#subtitle').text("#{args[1]}") if args[0] != " " && args[1] != " " $(domEl).find('#art').html("<img style=background:url('Aoede.widget/images/albumart.jpg');background-size:100px>") else $(domEl).find('#art').html("<img src='Aoede.widget/images/default.jpg'>")
185357
command: "osascript 'Aoede.widget/music.scpt'" refreshFrequency: 1000 style: """ @font-face font-family: NexaBold src: url(fonts/Nexa_Bold.ttf) @font-face font-family: NexaLight src: url(fonts/Nexa_Light.ttf) position: absolute bottom: 40px left: 40px color: rgb(255,255,255,0.8) display: flex #art>img height: 100px width: 100px // border-radius: 10% #content font-size: 0.8em position: absolute height: 100px width: calc(100vw - 80px) white-space: nowrap overflow: hidden #title font-family: NexaBold, Hiragino Kaku Gothic StdN W8 font-weight: 700 font-size: 2.7rem line-height: 80px padding-left: 20px text-transform: uppercase #subtitle font-family: NexaLight font-weight: 100 font-size: 1.8rem line-height: 5px position: absolute bottom: 20px padding-left: 20px text-transform: uppercase """ render: -> """ <div id="art"></div> <div id="content"> <div id="title">Aoede v1.0</div> <div id="subtitle">Written by <NAME>o</div> </div> """ update: (output, domEl) -> name_chars = 30 album_chars = 40 args = output.split("^") if $(domEl).find('#title').text().substring(0, 20) == args[0].substring(0, 20) return if args[0].length > name_chars args[0] = args[0].substring(0, 20)+" •••" if args[1].length > album_chars args[1] = args[1].substring(0, 25)+" ..." $(domEl).find('#title').text("#{args[0]}") $(domEl).find('#subtitle').text("#{args[1]}") if args[0] != " " && args[1] != " " $(domEl).find('#art').html("<img style=background:url('Aoede.widget/images/albumart.jpg');background-size:100px>") else $(domEl).find('#art').html("<img src='Aoede.widget/images/default.jpg'>")
true
command: "osascript 'Aoede.widget/music.scpt'" refreshFrequency: 1000 style: """ @font-face font-family: NexaBold src: url(fonts/Nexa_Bold.ttf) @font-face font-family: NexaLight src: url(fonts/Nexa_Light.ttf) position: absolute bottom: 40px left: 40px color: rgb(255,255,255,0.8) display: flex #art>img height: 100px width: 100px // border-radius: 10% #content font-size: 0.8em position: absolute height: 100px width: calc(100vw - 80px) white-space: nowrap overflow: hidden #title font-family: NexaBold, Hiragino Kaku Gothic StdN W8 font-weight: 700 font-size: 2.7rem line-height: 80px padding-left: 20px text-transform: uppercase #subtitle font-family: NexaLight font-weight: 100 font-size: 1.8rem line-height: 5px position: absolute bottom: 20px padding-left: 20px text-transform: uppercase """ render: -> """ <div id="art"></div> <div id="content"> <div id="title">Aoede v1.0</div> <div id="subtitle">Written by PI:NAME:<NAME>END_PIo</div> </div> """ update: (output, domEl) -> name_chars = 30 album_chars = 40 args = output.split("^") if $(domEl).find('#title').text().substring(0, 20) == args[0].substring(0, 20) return if args[0].length > name_chars args[0] = args[0].substring(0, 20)+" •••" if args[1].length > album_chars args[1] = args[1].substring(0, 25)+" ..." $(domEl).find('#title').text("#{args[0]}") $(domEl).find('#subtitle').text("#{args[1]}") if args[0] != " " && args[1] != " " $(domEl).find('#art').html("<img style=background:url('Aoede.widget/images/albumart.jpg');background-size:100px>") else $(domEl).find('#art').html("<img src='Aoede.widget/images/default.jpg'>")
[ { "context": "styles = \"\"\"\n/*\n * \"my love gift\"💕\n * Authored by 思伟\n */\n\nbody {\n background-color: #1a1c24; color: #", "end": 52, "score": 0.9578655362129211, "start": 50, "tag": "NAME", "value": "思伟" }, { "context": "key { color: #c66c75; }\n.key { color: #c7c...
src/index.coffee
Whisperwind-Siwei/Siwei
0
styles = """ /* * "my love gift"💕 * Authored by 思伟 */ body { background-color: #1a1c24; color: #fff; font-size: 1.0rem; line-height: 1.4; -webkit-font-smoothing: subpixel-antialiased; } /* * ... * ...hello? * 今天很想我的女朋友,该给她点什么呢~ * 写一个网页给君吧ww送她一颗小心心~ * 可是~要怎么做呢~ * 首先做一个框框来放我们的代码吧ww * 那么~开动啦!! */ pre { position: fixed; top: 30px; bottom: 30px; transition: left 500ms; overflow: auto; background-color: #313744; color: #a6c3d4; border: 1px solid rgba(0,0,0,0.2); padding: 24px 12px; box-sizing: border-box; border-radius: 3px; box-shadow: 0px 4px 0px 2px rgba(0,0,0,0.1); } /* * 不行不行,全是白色看代码都要看昏了 * 我需要语法高亮~那我们就动手实现一下它吧~ * Colors based on Base16 Ocean Dark */ pre em:not(.comment) { font-style: normal; } .comment { color: #707e84; } .selector { color: #c66c75; } .selector .key { color: #c66c75; } .key { color: #c7ccd4; } .value { color: #d5927b; } /* * 呦吼你看~代码高亮实现啦~接下来我们开工吧! * 首先我们把这个代码框移一下吧~它太占地方啦 * 由于是响应式布局~所以在手机上和电脑上有不同的显示效果呦 */ @media screen and (max-width: 768px) { pre { left: 6%;right: 6%;top: 50%; } } @media screen and (min-width: 768px) { pre { width: 48%;left: 50%;bottom: 30px; } } /* * 用代码做一颗小心心! */ @media screen and (max-width: 768px) { #heart, #echo { position: fixed; width: 300px; height: 300px; margin: 30px auto; left: 0; right: 0; text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } } @media screen and (min-width: 768px) { #heart, #echo { position: fixed; width: 300px; height: 300px; top: calc(50% - 150px); left: calc(25% - 150px); text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } } #heart { z-index: 8; } #echo { z-index: 7; } #heart::before, #heart::after, #echo::before, #echo::after { content: ''; position: absolute; top: 40px; width: 150px; height: 240px; background: #c66c75; border-radius: 150px 150px 0 0; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 100%; transform-origin: 0 100%; } #heart::before, #echo::before { left: 150px; } #heart::after, #echo::after { left: 0; -webkit-transform: rotate(45deg); transform: rotate(45deg); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; } /* 给它加上一点阴影ww */ #heart::after { box-shadow: inset -6px -6px 0px 6px rgba(255,255,255,0.1); } #heart::before { box-shadow: inset 6px 6px 0px 6px rgba(255,255,255,0.1); } /* * 这可是~我的小心心~ * 我要给它签上我的名字! * >v< */ #heart i::before { content: '思伟'; position: absolute; z-index: 9; width: 100%; top: 35%; left: 0; font-style: normal; color: rgba(255,255,255,0.8); font-weight: 100; font-size: 30px; text-shadow: -1px -1px 0px rgba(0,0,0,0.2); } /* * 接下来做什么呢~ * 我们让这颗心跳起来吧! */ @-webkit-keyframes heartbeat { 0%, 100% { -webkit-transform: scale(0.95); transform: scale(0.95); } 50% { -webkit-transform: scale(1.00); transform: scale(1.00); } } @keyframes heartbeat { 0%, 100% { transform: scale(0.95); } 50% { transform: scale(1.00); } } @-webkit-keyframes echo { 0% { opacity: 0.1; -webkit-transform: scale(1); transform: scale(1); } 100% { opacity: 0; -webkit-transform: scale(1.4); transform: scale(1.4); } } @keyframes echo { 0% { opacity: 0.1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.4); } } /* * 好哒!接下来准备让它跳起来吧ww */ #heart, #echo { -webkit-animation-duration: 2000ms; animation-duration: 2000ms; -webkit-animation-timing-function: cubic-bezier(0, 0, 0, 1.74); animation-timing-function: cubic-bezier(0, 0, 0, 1.74); -webkit-animation-delay: 500ms; animation-delay: 500ms; -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-play-state: paused; animation-play-state: paused; } #heart { -webkit-animation-name: heartbeat; animation-name: heartbeat; } #echo { -webkit-animation-name: echo; animation-name: echo; } /* * 准备好了嘛~! */ #heart, #echo { /* * ...3... * * ...2... * * ...1... * * 再等一下~略略略~ * */ -webkit-animation-play-state: running; animation-play-state: running; /* * ...来啦! */ } /* * 诶嘿~~ * 这样我的小心心就做好啦~ * 怎么样~ >v< 还好看吗~~ * 亲爱哒!每天都要快乐! * 爱你哦! * */ /* * "my love gift" * 谨以此网页献给我的女朋友汪淑君💕 * 你最可爱ww */ """ finalStyle = styles openComment = false isOn = true writeStyleChar = (which) -> # begin wrapping open comments if which == '/' && openComment == false openComment = true styles = $('#style-text').html() + which else if which == '/' && openComment == true openComment = false styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>') # wrap style declaration else if which == ':' styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:') # wrap style value else if which == ';' styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;') # wrap selector else if which == '{' styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{') else styles = $('#style-text').html() + which $('#style-text').html styles $('#style-tag').append which writeStyles = (message, index, interval) -> if index < message.length pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight writeStyleChar message[index++] if isOn setTimeout (-> writeStyles message, index, if openComment then commentTime else codeTime ), interval skip = () -> isOn = false setTimeout (-> $('#style-text').html finalStyle $('#style-tag').html finalStyle pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight ), 2*commentTime # appending the tags I'll need. $('body').append """ <style id="style-tag"></style> <span id="echo"></span> <span id="heart"><i></i></span> <pre id="style-text"></pre> <div style = 'position: fixed;left: 30px;bottom: 10px;'> <a id='skipAnimation'>跳过动画</a> <a style='color: #fff' href='http://love.idealclover.top'>重新播放</a> </div> """ # <a href='https://www.idealclover.top'>idealclover</a> # faster typing in small iframe on codepen homepage # time = if window.innerWidth <= 578 then 4 else 16 commentTime = 60 codeTime = 20 $(document).on 'ready page:load', -> $('#skipAnimation').click -> skip() # starting it off writeStyles(styles, 0, commentTime)
169638
styles = """ /* * "my love gift"💕 * Authored by <NAME> */ body { background-color: #1a1c24; color: #fff; font-size: 1.0rem; line-height: 1.4; -webkit-font-smoothing: subpixel-antialiased; } /* * ... * ...hello? * 今天很想我的女朋友,该给她点什么呢~ * 写一个网页给君吧ww送她一颗小心心~ * 可是~要怎么做呢~ * 首先做一个框框来放我们的代码吧ww * 那么~开动啦!! */ pre { position: fixed; top: 30px; bottom: 30px; transition: left 500ms; overflow: auto; background-color: #313744; color: #a6c3d4; border: 1px solid rgba(0,0,0,0.2); padding: 24px 12px; box-sizing: border-box; border-radius: 3px; box-shadow: 0px 4px 0px 2px rgba(0,0,0,0.1); } /* * 不行不行,全是白色看代码都要看昏了 * 我需要语法高亮~那我们就动手实现一下它吧~ * Colors based on Base16 Ocean Dark */ pre em:not(.comment) { font-style: normal; } .comment { color: #707e84; } .selector { color: #c66c75; } .selector .key { color: #c66c75; } .key { color: #c<KEY>ccd<KEY>; } .value { color: #d5927b; } /* * 呦吼你看~代码高亮实现啦~接下来我们开工吧! * 首先我们把这个代码框移一下吧~它太占地方啦 * 由于是响应式布局~所以在手机上和电脑上有不同的显示效果呦 */ @media screen and (max-width: 768px) { pre { left: 6%;right: 6%;top: 50%; } } @media screen and (min-width: 768px) { pre { width: 48%;left: 50%;bottom: 30px; } } /* * 用代码做一颗小心心! */ @media screen and (max-width: 768px) { #heart, #echo { position: fixed; width: 300px; height: 300px; margin: 30px auto; left: 0; right: 0; text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } } @media screen and (min-width: 768px) { #heart, #echo { position: fixed; width: 300px; height: 300px; top: calc(50% - 150px); left: calc(25% - 150px); text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } } #heart { z-index: 8; } #echo { z-index: 7; } #heart::before, #heart::after, #echo::before, #echo::after { content: ''; position: absolute; top: 40px; width: 150px; height: 240px; background: #c66c75; border-radius: 150px 150px 0 0; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 100%; transform-origin: 0 100%; } #heart::before, #echo::before { left: 150px; } #heart::after, #echo::after { left: 0; -webkit-transform: rotate(45deg); transform: rotate(45deg); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; } /* 给它加上一点阴影ww */ #heart::after { box-shadow: inset -6px -6px 0px 6px rgba(255,255,255,0.1); } #heart::before { box-shadow: inset 6px 6px 0px 6px rgba(255,255,255,0.1); } /* * 这可是~我的小心心~ * 我要给它签上我的名字! * >v< */ #heart i::before { content: '思伟'; position: absolute; z-index: 9; width: 100%; top: 35%; left: 0; font-style: normal; color: rgba(255,255,255,0.8); font-weight: 100; font-size: 30px; text-shadow: -1px -1px 0px rgba(0,0,0,0.2); } /* * 接下来做什么呢~ * 我们让这颗心跳起来吧! */ @-webkit-keyframes heartbeat { 0%, 100% { -webkit-transform: scale(0.95); transform: scale(0.95); } 50% { -webkit-transform: scale(1.00); transform: scale(1.00); } } @keyframes heartbeat { 0%, 100% { transform: scale(0.95); } 50% { transform: scale(1.00); } } @-webkit-keyframes echo { 0% { opacity: 0.1; -webkit-transform: scale(1); transform: scale(1); } 100% { opacity: 0; -webkit-transform: scale(1.4); transform: scale(1.4); } } @keyframes echo { 0% { opacity: 0.1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.4); } } /* * 好哒!接下来准备让它跳起来吧ww */ #heart, #echo { -webkit-animation-duration: 2000ms; animation-duration: 2000ms; -webkit-animation-timing-function: cubic-bezier(0, 0, 0, 1.74); animation-timing-function: cubic-bezier(0, 0, 0, 1.74); -webkit-animation-delay: 500ms; animation-delay: 500ms; -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-play-state: paused; animation-play-state: paused; } #heart { -webkit-animation-name: heartbeat; animation-name: heartbeat; } #echo { -webkit-animation-name: echo; animation-name: echo; } /* * 准备好了嘛~! */ #heart, #echo { /* * ...3... * * ...2... * * ...1... * * 再等一下~略略略~ * */ -webkit-animation-play-state: running; animation-play-state: running; /* * ...来啦! */ } /* * 诶嘿~~ * 这样我的小心心就做好啦~ * 怎么样~ >v< 还好看吗~~ * 亲爱哒!每天都要快乐! * 爱你哦! * */ /* * "my love gift" * 谨以此网页献给我的女朋友汪淑君💕 * 你最可爱ww */ """ finalStyle = styles openComment = false isOn = true writeStyleChar = (which) -> # begin wrapping open comments if which == '/' && openComment == false openComment = true styles = $('#style-text').html() + which else if which == '/' && openComment == true openComment = false styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>') # wrap style declaration else if which == ':' styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:') # wrap style value else if which == ';' styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;') # wrap selector else if which == '{' styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{') else styles = $('#style-text').html() + which $('#style-text').html styles $('#style-tag').append which writeStyles = (message, index, interval) -> if index < message.length pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight writeStyleChar message[index++] if isOn setTimeout (-> writeStyles message, index, if openComment then commentTime else codeTime ), interval skip = () -> isOn = false setTimeout (-> $('#style-text').html finalStyle $('#style-tag').html finalStyle pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight ), 2*commentTime # appending the tags I'll need. $('body').append """ <style id="style-tag"></style> <span id="echo"></span> <span id="heart"><i></i></span> <pre id="style-text"></pre> <div style = 'position: fixed;left: 30px;bottom: 10px;'> <a id='skipAnimation'>跳过动画</a> <a style='color: #fff' href='http://love.idealclover.top'>重新播放</a> </div> """ # <a href='https://www.idealclover.top'>idealclover</a> # faster typing in small iframe on codepen homepage # time = if window.innerWidth <= 578 then 4 else 16 commentTime = 60 codeTime = 20 $(document).on 'ready page:load', -> $('#skipAnimation').click -> skip() # starting it off writeStyles(styles, 0, commentTime)
true
styles = """ /* * "my love gift"💕 * Authored by PI:NAME:<NAME>END_PI */ body { background-color: #1a1c24; color: #fff; font-size: 1.0rem; line-height: 1.4; -webkit-font-smoothing: subpixel-antialiased; } /* * ... * ...hello? * 今天很想我的女朋友,该给她点什么呢~ * 写一个网页给君吧ww送她一颗小心心~ * 可是~要怎么做呢~ * 首先做一个框框来放我们的代码吧ww * 那么~开动啦!! */ pre { position: fixed; top: 30px; bottom: 30px; transition: left 500ms; overflow: auto; background-color: #313744; color: #a6c3d4; border: 1px solid rgba(0,0,0,0.2); padding: 24px 12px; box-sizing: border-box; border-radius: 3px; box-shadow: 0px 4px 0px 2px rgba(0,0,0,0.1); } /* * 不行不行,全是白色看代码都要看昏了 * 我需要语法高亮~那我们就动手实现一下它吧~ * Colors based on Base16 Ocean Dark */ pre em:not(.comment) { font-style: normal; } .comment { color: #707e84; } .selector { color: #c66c75; } .selector .key { color: #c66c75; } .key { color: #cPI:KEY:<KEY>END_PIccdPI:KEY:<KEY>END_PI; } .value { color: #d5927b; } /* * 呦吼你看~代码高亮实现啦~接下来我们开工吧! * 首先我们把这个代码框移一下吧~它太占地方啦 * 由于是响应式布局~所以在手机上和电脑上有不同的显示效果呦 */ @media screen and (max-width: 768px) { pre { left: 6%;right: 6%;top: 50%; } } @media screen and (min-width: 768px) { pre { width: 48%;left: 50%;bottom: 30px; } } /* * 用代码做一颗小心心! */ @media screen and (max-width: 768px) { #heart, #echo { position: fixed; width: 300px; height: 300px; margin: 30px auto; left: 0; right: 0; text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } } @media screen and (min-width: 768px) { #heart, #echo { position: fixed; width: 300px; height: 300px; top: calc(50% - 150px); left: calc(25% - 150px); text-align: center; -webkit-transform: scale(0.95); transform: scale(0.95); } } #heart { z-index: 8; } #echo { z-index: 7; } #heart::before, #heart::after, #echo::before, #echo::after { content: ''; position: absolute; top: 40px; width: 150px; height: 240px; background: #c66c75; border-radius: 150px 150px 0 0; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 100%; transform-origin: 0 100%; } #heart::before, #echo::before { left: 150px; } #heart::after, #echo::after { left: 0; -webkit-transform: rotate(45deg); transform: rotate(45deg); -webkit-transform-origin: 100% 100%; transform-origin: 100% 100%; } /* 给它加上一点阴影ww */ #heart::after { box-shadow: inset -6px -6px 0px 6px rgba(255,255,255,0.1); } #heart::before { box-shadow: inset 6px 6px 0px 6px rgba(255,255,255,0.1); } /* * 这可是~我的小心心~ * 我要给它签上我的名字! * >v< */ #heart i::before { content: '思伟'; position: absolute; z-index: 9; width: 100%; top: 35%; left: 0; font-style: normal; color: rgba(255,255,255,0.8); font-weight: 100; font-size: 30px; text-shadow: -1px -1px 0px rgba(0,0,0,0.2); } /* * 接下来做什么呢~ * 我们让这颗心跳起来吧! */ @-webkit-keyframes heartbeat { 0%, 100% { -webkit-transform: scale(0.95); transform: scale(0.95); } 50% { -webkit-transform: scale(1.00); transform: scale(1.00); } } @keyframes heartbeat { 0%, 100% { transform: scale(0.95); } 50% { transform: scale(1.00); } } @-webkit-keyframes echo { 0% { opacity: 0.1; -webkit-transform: scale(1); transform: scale(1); } 100% { opacity: 0; -webkit-transform: scale(1.4); transform: scale(1.4); } } @keyframes echo { 0% { opacity: 0.1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.4); } } /* * 好哒!接下来准备让它跳起来吧ww */ #heart, #echo { -webkit-animation-duration: 2000ms; animation-duration: 2000ms; -webkit-animation-timing-function: cubic-bezier(0, 0, 0, 1.74); animation-timing-function: cubic-bezier(0, 0, 0, 1.74); -webkit-animation-delay: 500ms; animation-delay: 500ms; -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-play-state: paused; animation-play-state: paused; } #heart { -webkit-animation-name: heartbeat; animation-name: heartbeat; } #echo { -webkit-animation-name: echo; animation-name: echo; } /* * 准备好了嘛~! */ #heart, #echo { /* * ...3... * * ...2... * * ...1... * * 再等一下~略略略~ * */ -webkit-animation-play-state: running; animation-play-state: running; /* * ...来啦! */ } /* * 诶嘿~~ * 这样我的小心心就做好啦~ * 怎么样~ >v< 还好看吗~~ * 亲爱哒!每天都要快乐! * 爱你哦! * */ /* * "my love gift" * 谨以此网页献给我的女朋友汪淑君💕 * 你最可爱ww */ """ finalStyle = styles openComment = false isOn = true writeStyleChar = (which) -> # begin wrapping open comments if which == '/' && openComment == false openComment = true styles = $('#style-text').html() + which else if which == '/' && openComment == true openComment = false styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>') # wrap style declaration else if which == ':' styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:') # wrap style value else if which == ';' styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;') # wrap selector else if which == '{' styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{') else styles = $('#style-text').html() + which $('#style-text').html styles $('#style-tag').append which writeStyles = (message, index, interval) -> if index < message.length pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight writeStyleChar message[index++] if isOn setTimeout (-> writeStyles message, index, if openComment then commentTime else codeTime ), interval skip = () -> isOn = false setTimeout (-> $('#style-text').html finalStyle $('#style-tag').html finalStyle pre = document.getElementById 'style-text' pre.scrollTop = pre.scrollHeight ), 2*commentTime # appending the tags I'll need. $('body').append """ <style id="style-tag"></style> <span id="echo"></span> <span id="heart"><i></i></span> <pre id="style-text"></pre> <div style = 'position: fixed;left: 30px;bottom: 10px;'> <a id='skipAnimation'>跳过动画</a> <a style='color: #fff' href='http://love.idealclover.top'>重新播放</a> </div> """ # <a href='https://www.idealclover.top'>idealclover</a> # faster typing in small iframe on codepen homepage # time = if window.innerWidth <= 578 then 4 else 16 commentTime = 60 codeTime = 20 $(document).on 'ready page:load', -> $('#skipAnimation').click -> skip() # starting it off writeStyles(styles, 0, commentTime)
[ { "context": "n: 'mock-region'\n credentials:\n accessKeyId: 'akid'\n secretAccessKey: 'secret'\n\n# Disable validat", "end": 698, "score": 0.9958013296127319, "start": 694, "tag": "KEY", "value": "akid" }, { "context": "ls:\n accessKeyId: 'akid'\n secretAccessKey: 'secr...
node_modules/aws-sdk/test/helpers.coffee
ellennewellevans/newsScraper
1
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. AWS = require('../lib/aws') # Mock credentials AWS.config.update region: 'mock-region' credentials: accessKeyId: 'akid' secretAccessKey: 'secret' # Disable validation AWS.EventListeners.Core.removeListener 'validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS # Disable setTimeout for tests # Warning: this might cause unpredictable results # TODO: refactor this out. `setTimeout = function(fn, delay) { fn(); }` AWS.HttpClient.getInstance = -> throw new Error('Unmocked HTTP request') flattenXML = (xml) -> if (!xml) return xml xml.split("\n").join(''). # remove newlines replace(/>\s+</g, '><'). # prunes whitespace between elements replace(/^\s+|\s+$/g, '') # trims whitespace from ends matchXML = (xml1, xml2) -> expect(flattenXML(xml1)).toEqual(flattenXML(xml2)) MockClient = AWS.util.inherit AWS.Client, constructor: (config) -> AWS.Client.call(this, config) @config.credentials = accessKeyId: 'akid', secretAccessKey: 'secret' @config.region = 'mock-region' setupRequestListeners: (request) -> request.on 'extractData', (resp) -> resp.data = resp.httpResponse.body.toString() request.on 'extractError', (resp) -> resp.error = code: resp.httpResponse.statusCode message: null api: endpointPrefix: 'mockservice' signatureVersion: 'v4' MockService = AWS.util.inherit AWS.Service, constructor: (config) -> AWS.Service.call(this, config) MockService.Client = MockClient mockHttpResponse = (status, headers, data) -> spyOn(AWS.HttpClient, 'getInstance') AWS.HttpClient.getInstance.andReturn handleRequest: (req, resp) -> if typeof status == 'number' req.emit('httpHeaders', [status, headers, resp]) str = str instanceof Array ? str : [str] AWS.util.arrayEach data, (str) -> req.emit('httpData', [new Buffer(str), resp]) req.emit('httpDone', [resp]) else req.emit('httpError', [status, resp]) mockIntermittentFailureResponse = (numFailures, status, headers, data) -> spyOn(AWS.HttpClient, 'getInstance') AWS.HttpClient.getInstance.andReturn handleRequest: (req, resp) -> if resp.retryCount < numFailures req.emit('httpError', [{code: 'NetworkingError', message: 'FAIL!'}, resp]) else req.emit('httpHeaders', [(resp.retryCount < numFailures ? 500 : status), headers, resp]) str = str instanceof Array ? str : [str] AWS.util.arrayEach data, (str) -> req.emit('httpData', [new Buffer(str), resp]) req.emit('httpDone', [resp]) module.exports = AWS: AWS matchXML: matchXML mockHttpResponse: mockHttpResponse mockIntermittentFailureResponse: mockIntermittentFailureResponse MockClient: MockClient MockService: MockService
15753
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. AWS = require('../lib/aws') # Mock credentials AWS.config.update region: 'mock-region' credentials: accessKeyId: '<KEY>' secretAccessKey: '<KEY>' # Disable validation AWS.EventListeners.Core.removeListener 'validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS # Disable setTimeout for tests # Warning: this might cause unpredictable results # TODO: refactor this out. `setTimeout = function(fn, delay) { fn(); }` AWS.HttpClient.getInstance = -> throw new Error('Unmocked HTTP request') flattenXML = (xml) -> if (!xml) return xml xml.split("\n").join(''). # remove newlines replace(/>\s+</g, '><'). # prunes whitespace between elements replace(/^\s+|\s+$/g, '') # trims whitespace from ends matchXML = (xml1, xml2) -> expect(flattenXML(xml1)).toEqual(flattenXML(xml2)) MockClient = AWS.util.inherit AWS.Client, constructor: (config) -> AWS.Client.call(this, config) @config.credentials = accessKeyId: '<KEY>', secretAccessKey: '<KEY>' @config.region = 'mock-region' setupRequestListeners: (request) -> request.on 'extractData', (resp) -> resp.data = resp.httpResponse.body.toString() request.on 'extractError', (resp) -> resp.error = code: resp.httpResponse.statusCode message: null api: endpointPrefix: 'mockservice' signatureVersion: 'v4' MockService = AWS.util.inherit AWS.Service, constructor: (config) -> AWS.Service.call(this, config) MockService.Client = MockClient mockHttpResponse = (status, headers, data) -> spyOn(AWS.HttpClient, 'getInstance') AWS.HttpClient.getInstance.andReturn handleRequest: (req, resp) -> if typeof status == 'number' req.emit('httpHeaders', [status, headers, resp]) str = str instanceof Array ? str : [str] AWS.util.arrayEach data, (str) -> req.emit('httpData', [new Buffer(str), resp]) req.emit('httpDone', [resp]) else req.emit('httpError', [status, resp]) mockIntermittentFailureResponse = (numFailures, status, headers, data) -> spyOn(AWS.HttpClient, 'getInstance') AWS.HttpClient.getInstance.andReturn handleRequest: (req, resp) -> if resp.retryCount < numFailures req.emit('httpError', [{code: 'NetworkingError', message: 'FAIL!'}, resp]) else req.emit('httpHeaders', [(resp.retryCount < numFailures ? 500 : status), headers, resp]) str = str instanceof Array ? str : [str] AWS.util.arrayEach data, (str) -> req.emit('httpData', [new Buffer(str), resp]) req.emit('httpDone', [resp]) module.exports = AWS: AWS matchXML: matchXML mockHttpResponse: mockHttpResponse mockIntermittentFailureResponse: mockIntermittentFailureResponse MockClient: MockClient MockService: MockService
true
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. AWS = require('../lib/aws') # Mock credentials AWS.config.update region: 'mock-region' credentials: accessKeyId: 'PI:KEY:<KEY>END_PI' secretAccessKey: 'PI:KEY:<KEY>END_PI' # Disable validation AWS.EventListeners.Core.removeListener 'validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS # Disable setTimeout for tests # Warning: this might cause unpredictable results # TODO: refactor this out. `setTimeout = function(fn, delay) { fn(); }` AWS.HttpClient.getInstance = -> throw new Error('Unmocked HTTP request') flattenXML = (xml) -> if (!xml) return xml xml.split("\n").join(''). # remove newlines replace(/>\s+</g, '><'). # prunes whitespace between elements replace(/^\s+|\s+$/g, '') # trims whitespace from ends matchXML = (xml1, xml2) -> expect(flattenXML(xml1)).toEqual(flattenXML(xml2)) MockClient = AWS.util.inherit AWS.Client, constructor: (config) -> AWS.Client.call(this, config) @config.credentials = accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI' @config.region = 'mock-region' setupRequestListeners: (request) -> request.on 'extractData', (resp) -> resp.data = resp.httpResponse.body.toString() request.on 'extractError', (resp) -> resp.error = code: resp.httpResponse.statusCode message: null api: endpointPrefix: 'mockservice' signatureVersion: 'v4' MockService = AWS.util.inherit AWS.Service, constructor: (config) -> AWS.Service.call(this, config) MockService.Client = MockClient mockHttpResponse = (status, headers, data) -> spyOn(AWS.HttpClient, 'getInstance') AWS.HttpClient.getInstance.andReturn handleRequest: (req, resp) -> if typeof status == 'number' req.emit('httpHeaders', [status, headers, resp]) str = str instanceof Array ? str : [str] AWS.util.arrayEach data, (str) -> req.emit('httpData', [new Buffer(str), resp]) req.emit('httpDone', [resp]) else req.emit('httpError', [status, resp]) mockIntermittentFailureResponse = (numFailures, status, headers, data) -> spyOn(AWS.HttpClient, 'getInstance') AWS.HttpClient.getInstance.andReturn handleRequest: (req, resp) -> if resp.retryCount < numFailures req.emit('httpError', [{code: 'NetworkingError', message: 'FAIL!'}, resp]) else req.emit('httpHeaders', [(resp.retryCount < numFailures ? 500 : status), headers, resp]) str = str instanceof Array ? str : [str] AWS.util.arrayEach data, (str) -> req.emit('httpData', [new Buffer(str), resp]) req.emit('httpDone', [resp]) module.exports = AWS: AWS matchXML: matchXML mockHttpResponse: mockHttpResponse mockIntermittentFailureResponse: mockIntermittentFailureResponse MockClient: MockClient MockService: MockService
[ { "context": "# Copyright © 2014–6 Brad Ackerman.\n#\n# Licensed under the Apache License, Version 2", "end": 34, "score": 0.9998468160629272, "start": 21, "tag": "NAME", "value": "Brad Ackerman" } ]
assets/coffee/routes.coffee
backerman/eveindy
2
# Copyright © 2014–6 Brad Ackerman. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'eveindy' .config ['$routeProvider', ($routeProvider) -> $routeProvider.when '/', templateUrl: 'view/reprocess.html' controller: 'ReprocessCtrl as ctrl' .when '/blueprints', templateUrl: 'view/blueprints.html' controller: 'BlueprintsCtrl as ctrl' .when '/settings', templateUrl: 'view/settings.html' controller: 'SettingsCtrl as ctrl' .otherwise redirectTo: '/' ]
67131
# Copyright © 2014–6 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'eveindy' .config ['$routeProvider', ($routeProvider) -> $routeProvider.when '/', templateUrl: 'view/reprocess.html' controller: 'ReprocessCtrl as ctrl' .when '/blueprints', templateUrl: 'view/blueprints.html' controller: 'BlueprintsCtrl as ctrl' .when '/settings', templateUrl: 'view/settings.html' controller: 'SettingsCtrl as ctrl' .otherwise redirectTo: '/' ]
true
# Copyright © 2014–6 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'eveindy' .config ['$routeProvider', ($routeProvider) -> $routeProvider.when '/', templateUrl: 'view/reprocess.html' controller: 'ReprocessCtrl as ctrl' .when '/blueprints', templateUrl: 'view/blueprints.html' controller: 'BlueprintsCtrl as ctrl' .when '/settings', templateUrl: 'view/settings.html' controller: 'SettingsCtrl as ctrl' .otherwise redirectTo: '/' ]
[ { "context": "module.exports = [{\n name: 'Fred Flinstone'\n type: 'Person'\n}, {\n name: 'French Friedstien", "end": 43, "score": 0.999829113483429, "start": 29, "tag": "NAME", "value": "Fred Flinstone" }, { "context": ": 'Fred Flinstone'\n type: 'Person'\n}, {\n name: 'French ...
spec/fixtures/people.coffee
ibykow/stargame
0
module.exports = [{ name: 'Fred Flinstone' type: 'Person' }, { name: 'French Friedstien' type: 'Person' }, { name: 'Chalk Chakara' type: 'Person' }]
212207
module.exports = [{ name: '<NAME>' type: 'Person' }, { name: '<NAME>' type: 'Person' }, { name: '<NAME>' type: 'Person' }]
true
module.exports = [{ name: 'PI:NAME:<NAME>END_PI' type: 'Person' }, { name: 'PI:NAME:<NAME>END_PI' type: 'Person' }, { name: 'PI:NAME:<NAME>END_PI' type: 'Person' }]
[ { "context": " formatting required\", ->\n _.each [\n \"password\"\n \"email\"\n \"number\"\n \"search", "end": 7415, "score": 0.6694848537445068, "start": 7407, "tag": "PASSWORD", "value": "password" }, { "context": "->\n cy.get(\"#email-wit...
packages/driver/test/cypress/integration/commands/actions/type_spec.coffee
Everworks/cypress
3
$ = Cypress.$.bind(Cypress) _ = Cypress._ Keyboard = Cypress.Keyboard Promise = Cypress.Promise $selection = require("../../../../../src/dom/selection") describe "src/cy/commands/actions/type", -> before -> cy .visit("/fixtures/dom.html") .then (win) -> @body = win.document.body.outerHTML beforeEach -> doc = cy.state("document") $(doc.body).empty().html(@body) context "#type", -> it "does not change the subject", -> input = cy.$$("input:first") cy.get("input:first").type("foo").then ($input) -> expect($input).to.match input it "changes the value", -> input = cy.$$("input:text:first") input.val("") ## make sure we are starting from a ## clean state expect(input).to.have.value("") cy.get("input:text:first").type("foo").then ($input) -> expect($input).to.have.value("foo") it "appends subsequent type commands", -> cy .get("input:first").type("123").type("456") .should("have.value", "123456") it "appends subsequent commands when value is changed in between", -> cy .get("input:first") .type("123") .then ($input) -> $input[0].value += '-' return $input .type("456") .should("have.value", "123-456") it "can type numbers", -> cy.get(":text:first").type(123).then ($text) -> expect($text).to.have.value("123") it "triggers focus event on the input", (done) -> cy.$$("input:text:first").focus -> done() cy.get("input:text:first").type("bar") it "lists the input as the focused element", -> $input = cy.$$("input:text:first") cy.get("input:text:first").type("bar").focused().then ($focused) -> expect($focused.get(0)).to.eq $input.get(0) it "causes previous input to receive blur", -> blurred = false cy.$$("input:text:first").blur -> blurred = true cy .get("input:text:first").type("foo") .get("input:text:last").type("bar") .then -> expect(blurred).to.be.true it "can type into contenteditable", -> oldText = cy.$$("#contenteditable").get(0).innerText cy.get("#contenteditable") .type(" foo") .then ($div) -> expect($div.get(0).innerText).to.eq (oldText + " foo") it "delays 50ms before resolving", -> cy.$$(":text:first").on "change", (e) => cy.spy(Promise, "delay") cy.get(":text:first").type("foo{enter}").then -> expect(Promise.delay).to.be.calledWith(50, "type") it "increases the timeout delta", -> cy.spy(cy, "timeout") cy.get(":text:first").type("foo{enter}").then -> expect(cy.timeout).to.be.calledWith(40, true, "type") expect(cy.timeout).to.be.calledWith(50, true, "type") it "accepts body as subject", -> cy.get("body").type("foo") it "does not click when body is subject", -> bodyClicked = false cy.$$("body").on "click", -> bodyClicked = true cy.get("body").type("foo").then -> expect(bodyClicked).to.be.false describe "actionability", -> it "can forcibly click even when element is invisible", -> $txt = cy.$$(":text:first").hide() expect($txt).not.to.have.value("foo") clicked = false $txt.on "click", -> clicked = true cy.get(":text:first").type("foo", {force: true}).then ($input) -> expect(clicked).to.be.true expect($input).to.have.value("foo") it "can forcibly click even when being covered by another element", -> $input = $("<input />") .attr("id", "input-covered-in-span") .css({ width: 50 }) .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) clicked = false $input.on "click", -> clicked = true cy.get("#input-covered-in-span").type("foo", {force: true}).then ($input) -> expect(clicked).to.be.true expect($input).to.have.value("foo") it "waits until element becomes visible", -> $txt = cy.$$(":text:first").hide() retried = false cy.on "command:retry", _.after 3, -> $txt.show() retried = true cy.get(":text:first").type("foo").then -> expect(retried).to.be.true it "waits until element is no longer disabled", -> $txt = cy.$$(":text:first").prop("disabled", true) retried = false clicks = 0 $txt.on "click", -> clicks += 1 cy.on "command:retry", _.after 3, -> $txt.prop("disabled", false) retried = true cy.get(":text:first").type("foo").then -> expect(clicks).to.eq(1) expect(retried).to.be.true it "waits until element stops animating", -> retries = 0 cy.on "command:retry", (obj) -> retries += 1 cy.stub(cy, "ensureElementIsNotAnimating") .throws(new Error("animating!")) .onThirdCall().returns() cy.get(":text:first").type("foo").then -> ## - retry animation coords ## - retry animation ## - retry animation expect(retries).to.eq(3) expect(cy.ensureElementIsNotAnimating).to.be.calledThrice it "does not throw when waiting for animations is disabled", -> cy.stub(cy, "ensureElementIsNotAnimating").throws(new Error("animating!")) Cypress.config("waitForAnimations", false) cy.get(":text:first").type("foo").then -> expect(cy.ensureElementIsNotAnimating).not.to.be.called it "does not throw when turning off waitForAnimations in options", -> cy.stub(cy, "ensureElementIsNotAnimating").throws(new Error("animating!")) cy.get(":text:first").type("foo", {waitForAnimations: false}).then -> expect(cy.ensureElementIsNotAnimating).not.to.be.called it "passes options.animationDistanceThreshold to cy.ensureElementIsNotAnimating", -> $txt = cy.$$(":text:first") { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($txt) cy.spy(cy, "ensureElementIsNotAnimating") cy.get(":text:first").type("foo", {animationDistanceThreshold: 1000}).then -> args = cy.ensureElementIsNotAnimating.firstCall.args expect(args[1]).to.deep.eq([fromWindow, fromWindow]) expect(args[2]).to.eq(1000) it "passes config.animationDistanceThreshold to cy.ensureElementIsNotAnimating", -> animationDistanceThreshold = Cypress.config("animationDistanceThreshold") $txt = cy.$$(":text:first") { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($txt) cy.spy(cy, "ensureElementIsNotAnimating") cy.get(":text:first").type("foo").then -> args = cy.ensureElementIsNotAnimating.firstCall.args expect(args[1]).to.deep.eq([fromWindow, fromWindow]) expect(args[2]).to.eq(animationDistanceThreshold) describe "input types where no extra formatting required", -> _.each [ "password" "email" "number" "search" "url" "tel" ], (type) -> it "accepts input [type=#{type}]", -> input = cy.$$("<input type='#{type}' id='input-type-#{type}' />") cy.$$("body").append(input) cy.get("#input-type-#{type}").type("1234").then ($input) -> expect($input).to.have.value "1234" expect($input.get(0)).to.eq $input.get(0) it "accepts type [type=#{type}], regardless of capitalization", -> input = cy.$$("<input type='#{type.toUpperCase()}' id='input-type-#{type}' />") cy.$$("body").append(input) cy.get("#input-type-#{type}").type("1234") describe "tabindex", -> beforeEach -> @$div = cy.$$("#tabindex") it "receives keydown, keyup, keypress", -> keydown = false keypress = false keyup = false @$div.keydown -> keydown = true @$div.keypress -> keypress = true @$div.keyup -> keyup = true cy.get("#tabindex").type("a").then -> expect(keydown).to.be.true expect(keypress).to.be.true expect(keyup).to.be.true it "does not receive textInput", -> textInput = false @$div.on "textInput", -> textInput = true cy.get("#tabindex").type("f").then -> expect(textInput).to.be.false it "does not receive input", -> input = false @$div.on "input", -> input = true cy.get("#tabindex").type("f").then -> expect(input).to.be.false it "does not receive change event", -> innerText = @$div.text() change = false @$div.on "change", -> change = true cy.get("#tabindex").type("foo{enter}").then ($el) -> expect(change).to.be.false expect($el.text()).to.eq(innerText) it "does not change inner text", -> innerText = @$div.text() cy.get("#tabindex").type("foo{leftarrow}{del}{rightarrow}{enter}").should("have.text", innerText) it "receives focus", -> focus = false @$div.focus -> focus = true cy.get("#tabindex").type("f").then -> expect(focus).to.be.true it "receives blur", -> blur = false @$div.blur -> blur = true cy .get("#tabindex").type("f") .get("input:first").focus().then -> expect(blur).to.be.true it "receives keydown and keyup for other special characters and keypress for enter and regular characters", -> keydowns = [] keyups = [] keypresses = [] @$div.keydown (e) -> keydowns.push(e) @$div.keypress (e) -> keypresses.push(e) @$div.keyup (e) -> keyups.push(e) cy .get("#tabindex").type("f{leftarrow}{rightarrow}{enter}") .then -> expect(keydowns).to.have.length(4) expect(keypresses).to.have.length(2) expect(keyups).to.have.length(4) describe "delay", -> it "adds delay to delta for each key sequence", -> cy.spy(cy, "timeout") cy .get(":text:first") .type("foo{enter}bar{leftarrow}", { delay: 5 }) .then -> expect(cy.timeout).to.be.calledWith(5 * 8, true, "type") it "can cancel additional keystrokes", (done) -> cy.stub(Cypress.runner, "stop") text = cy.$$(":text:first").keydown _.after 3, -> Cypress.stop() cy.on "stop", -> _.delay -> expect(text).to.have.value("foo") done() , 50 cy.get(":text:first").type("foo{enter}bar{leftarrow}") describe "events", -> it "receives keydown event", (done) -> $txt = cy.$$(":text:first") $txt.on "keydown", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 0 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 65 ## deprecated but fired by chrome always uppercase in the ASCII table layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keydown" view: cy.state("window") which: 65 ## deprecated but fired by chrome } done() cy.get(":text:first").type("a") it "receives keypress event", (done) -> $txt = cy.$$(":text:first") $txt.on "keypress", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 97 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 97 ## deprecated layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keypress" view: cy.state("window") which: 97 ## deprecated } done() cy.get(":text:first").type("a") it "receives keyup event", (done) -> $txt = cy.$$(":text:first") $txt.on "keyup", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 0 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 65 ## deprecated but fired by chrome always uppercase in the ASCII table layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keyup" view: cy.state("window") which: 65 ## deprecated but fired by chrome } done() cy.get(":text:first").type("a") it "receives textInput event", (done) -> $txt = cy.$$(":text:first") $txt.on "textInput", (e) => obj = _.pick e.originalEvent, "bubbles", "cancelable", "charCode", "data", "detail", "keyCode", "layerX", "layerY", "pageX", "pageY", "type", "view", "which" expect(obj).to.deep.eq { bubbles: true cancelable: true charCode: 0 data: "a" detail: 0 keyCode: 0 layerX: 0 layerY: 0 pageX: 0 pageY: 0 type: "textInput" view: cy.state("window") which: 0 } done() cy.get(":text:first").type("a") it "receives input event", (done) -> $txt = cy.$$(":text:first") $txt.on "input", (e) => obj = _.pick e.originalEvent, "bubbles", "cancelable", "type" expect(obj).to.deep.eq { bubbles: true cancelable: false type: "input" } done() cy.get(":text:first").type("a") it "fires events in the correct order" it "fires events for each key stroke" it "does fire input event when value changes", -> fired = false cy.$$(":text:first").on "input", -> fired = true fired = false cy.get(":text:first") .invoke("val", "bar") .type("{selectAll}{rightarrow}{backspace}") .then -> expect(fired).to.eq true fired = false cy.get(":text:first") .invoke("val", "bar") .type("{selectAll}{leftarrow}{del}") .then -> expect(fired).to.eq true cy.$$('[contenteditable]:first').on "input", () -> fired = true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{rightarrow}{backspace}') .then -> expect(fired).to.eq true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{leftarrow}{del}') .then -> expect(fired).to.eq true it "does not fire input event when value does not change", -> fired = false cy.$$(":text:first").on "input", (e) -> fired = true fired = false cy.get(":text:first") .invoke("val", "bar") .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get(":text:first") .invoke("val", "bar") .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false cy.$$("textarea:first").on "input", (e) -> fired = true fired = false cy.get("textarea:first") .invoke("val", "bar") .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get("textarea:first") .invoke("val", "bar") .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false cy.$$('[contenteditable]:first').on "input", () -> fired = true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false describe "maxlength", -> it "limits text entered to the maxlength attribute of a text input", -> $input = cy.$$(":text:first") $input.attr("maxlength", 5) cy.get(":text:first") .type("1234567890") .then (input) -> expect(input).to.have.value("12345") it "ignores an invalid maxlength attribute", -> $input = cy.$$(":text:first") $input.attr("maxlength", "five") cy.get(":text:first") .type("1234567890") .then (input) -> expect(input).to.have.value("1234567890") it "handles special characters", -> $input = cy.$$(":text:first") $input.attr("maxlength", 5) cy.get(":text:first") .type("12{selectall}") .then (input) -> expect(input).to.have.value("12") it "maxlength=0 events", -> events = [] push = (evt) -> return -> events.push(evt) cy .$$(":text:first") .attr("maxlength", 0) .on("keydown", push("keydown")) .on("keypress", push("keypress")) .on("textInput", push("textInput")) .on("input", push("input")) .on("keyup", push("keyup")) cy.get(":text:first") .type("1") .then -> expect(events).to.deep.eq([ "keydown", "keypress", "textInput", "keyup" ]) it "maxlength=1 events", -> events = [] push = (evt) -> return -> events.push(evt) cy .$$(":text:first") .attr("maxlength", 1) .on("keydown", push("keydown")) .on("keypress", push("keypress")) .on("textInput", push("textInput")) .on("input", push("input")) .on("keyup", push("keyup")) cy.get(":text:first") .type("12") .then -> expect(events).to.deep.eq([ "keydown", "keypress", "textInput", "input", "keyup" "keydown", "keypress", "textInput", "keyup" ]) describe "value changing", -> it "changes the elements value", -> cy.get("#input-without-value").type("a").then ($text) -> expect($text).to.have.value("a") it "changes the elements value for multiple keys", -> cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("foo") it "inserts text after existing text", -> cy.get("#input-with-value").type(" bar").then ($text) -> expect($text).to.have.value("foo bar") it "inserts text after existing text input by invoking val", -> cy.get("#input-without-value").invoke("val", "foo").type(" bar").then ($text) -> expect($text).to.have.value("foo bar") it "overwrites text when currently has selection", -> cy.get("#input-without-value").invoke('val', '0').then (el) -> el.select() cy.get("#input-without-value").type("50").then ($input) -> expect($input).to.have.value("50") it "overwrites text when selectAll in click handler", -> cy.$$("#input-without-value").val("0").click -> $(@).select() it "overwrites text when selectAll in mouseup handler", -> cy.$$("#input-without-value").val("0").mouseup -> $(@).select() it "overwrites text when selectAll in mouseup handler", -> cy.$$("#input-without-value").val("0").mouseup -> $(@).select() it "responsive to keydown handler", -> cy.$$("#input-without-value").val("1234").keydown -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("651234") it "responsive to keyup handler", -> cy.$$("#input-without-value").val("1234").keyup -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("612345") it "responsive to input handler", -> cy.$$("#input-without-value").val("1234").keyup -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("612345") it "responsive to change handler", -> cy.$$("#input-without-value").val("1234").change -> $(@).get(0).setSelectionRange(0,0) ## no change event should be fired cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("123456") it "automatically moves the caret to the end if value is changed manually", -> cy.$$("#input-without-value").keypress (e) -> e.preventDefault() key = String.fromCharCode(e.which) $input = $(e.target) val = $input.val() ## setting value updates cursor to the end of input $input.val(val + key + "-") cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("f-o-o-") it "automatically moves the caret to the end if value is changed manually asynchronously", -> cy.$$("#input-without-value").keypress (e) -> key = String.fromCharCode(e.which) $input = $(e.target) _.defer -> val = $input.val() $input.val(val + "-") cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("f-o-o-") it "does not fire keypress when keydown is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> done("should not have received keypress event") cy.$$("#input-without-value").get(0).addEventListener "keydown", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "does not insert key when keydown is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "keydown", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not insert key when keypress is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not fire textInput when keypress is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> done("should not have received textInput event") cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "does not insert key when textInput is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not fire input when textInput is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "input", (e) -> done("should not have received input event") cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "preventing default to input event should not affect anything", -> cy.$$("#input-without-value").get(0).addEventListener "input", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("foo") describe "input[type=number]", -> it "can change values", -> cy.get("#number-without-value").type("42").then ($text) -> expect($text).to.have.value("42") it "can input decimal", -> cy.get("#number-without-value").type("2.0").then ($input) -> expect($input).to.have.value("2.0") it "can utilize {selectall}", -> cy.get("#number-with-value").type("{selectall}99").then ($input) -> expect($input).to.have.value("99") it "can utilize arrows", -> cy.get("#number-with-value").type("{leftarrow}{leftarrow}{rightarrow}9").then ($input) -> expect($input).to.have.value("192") it "inserts text after existing text ", -> cy.get("#number-with-value").type("34").then ($text) -> expect($text).to.have.value("1234") it "inserts text after existing text input by invoking val", -> cy.get("#number-without-value").invoke("val", "12").type("34").then ($text) -> expect($text).to.have.value("1234") it "overwrites text on input[type=number] when input has existing text selected", -> cy.get("#number-without-value").invoke('val', "0").then (el) -> el.get(0).select() cy.get("#number-without-value").type("50").then ($input) -> expect($input).to.have.value("50") it "can type negative numbers", -> cy.get('#number-without-value') .type('-123.12') .should('have.value', '-123.12') it "type=number blurs consistently", -> blurred = 0 cy.$$("#number-without-value").blur -> blurred++ cy.get("#number-without-value") .type('200').blur() .then -> expect(blurred).to.eq 1 describe "input[type=email]", -> it "can change values", -> cy.get("#email-without-value").type("brian@foo.com").then ($text) -> expect($text).to.have.value("brian@foo.com") it "can utilize {selectall}", -> cy.get("#email-with-value").type("{selectall}brian@foo.com").then ($text) -> expect($text).to.have.value("brian@foo.com") it "can utilize arrows", -> cy.get("#email-with-value").type("{leftarrow}{rightarrow}om").then ($text) -> expect($text).to.have.value("brian@foo.com") it "inserts text after existing text", -> cy.get("#email-with-value").type("om").then ($text) -> expect($text).to.have.value("brian@foo.com") it "inserts text after existing text input by invoking val", -> cy.get("#email-without-value").invoke("val", "brian@foo.c").type("om").then ($text) -> expect($text).to.have.value("brian@foo.com") it "overwrites text when input has existing text selected", -> cy.get("#email-without-value").invoke('val', "foo@bar.com").invoke('select') cy.get("#email-without-value").type("bar@foo.com").then ($input) -> expect($input).to.have.value("bar@foo.com") it "type=email blurs consistently", -> blurred = 0 cy.$$("#email-without-value").blur -> blurred++ cy.get("#email-without-value") .type('foo@bar.com').blur() .then -> expect(blurred).to.eq 1 describe "input[type=password]", -> it "can change values", -> cy.get("#password-without-value").type("password").then ($text) -> expect($text).to.have.value("password") it "inserts text after existing text", -> cy.get("#password-with-value").type("word").then ($text) -> expect($text).to.have.value("password") it "inserts text after existing text input by invoking val", -> cy.get("#password-without-value").invoke("val", "secr").type("et").then ($text) -> expect($text).to.have.value("secret") it "overwrites text when input has existing text selected", -> cy.get("#password-without-value").invoke('val', "secret").invoke('select') cy.get("#password-without-value").type("agent").then ($input) -> expect($input).to.have.value("agent") it "overwrites text when input has selected range of text in click handler", -> cy.$$("#input-with-value").mouseup (e) -> # e.preventDefault() e.target.setSelectionRange(1, 1) select = (e) -> e.target.select() cy .$$("#password-without-value") .val("secret") .click(select) .keyup (e) -> switch e.key when "g" select(e) when "n" e.target.setSelectionRange(0, 1) cy.get("#password-without-value").type("agent").then ($input) -> expect($input).to.have.value("tn") describe "input[type=date]", -> it "can change values", -> cy.get("#date-without-value").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") it "overwrites existing value", -> cy.get("#date-with-value").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") it "overwrites existing value input by invoking val", -> cy.get("#date-without-value").invoke("val", "2016-01-01").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") describe "input[type=month]", -> it "can change values", -> cy.get("#month-without-value").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") it "overwrites existing value", -> cy.get("#month-with-value").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") it "overwrites existing value input by invoking val", -> cy.get("#month-without-value").invoke("val", "2016-01").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") describe "input[type=week]", -> it "can change values", -> cy.get("#week-without-value").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") it "overwrites existing value", -> cy.get("#week-with-value").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") it "overwrites existing value input by invoking val", -> cy.get("#week-without-value").invoke("val", "2016-W01").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") describe "input[type=time]", -> it "can change values", -> cy.get("#time-without-value").type("01:23:45").then ($text) -> expect($text).to.have.value("01:23:45") it "overwrites existing value", -> cy.get("#time-with-value").type("12:34:56").then ($text) -> expect($text).to.have.value("12:34:56") it "overwrites existing value input by invoking val", -> cy.get("#time-without-value").invoke("val", "01:23:45").type("12:34:56").then ($text) -> expect($text).to.have.value("12:34:56") it "can be formatted HH:mm", -> cy.get("#time-without-value").type("01:23").then ($text) -> expect($text).to.have.value("01:23") it "can be formatted HH:mm:ss", -> cy.get("#time-without-value").type("01:23:45").then ($text) -> expect($text).to.have.value("01:23:45") it "can be formatted HH:mm:ss.S", -> cy.get("#time-without-value").type("01:23:45.9").then ($text) -> expect($text).to.have.value("01:23:45.9") it "can be formatted HH:mm:ss.SS", -> cy.get("#time-without-value").type("01:23:45.99").then ($text) -> expect($text).to.have.value("01:23:45.99") it "can be formatted HH:mm:ss.SSS", -> cy.get("#time-without-value").type("01:23:45.999").then ($text) -> expect($text).to.have.value("01:23:45.999") describe "[contenteditable]", -> it "can change values", -> cy.get("#input-types [contenteditable]").type("foo").then ($div) -> expect($div).to.have.text("foo") it "inserts text after existing text", -> cy.get("#input-types [contenteditable]").invoke("text", "foo").type(" bar").then ($text) -> expect($text).to.have.text("foo bar") it "can type into [contenteditable] with existing <div>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>foo</div>' cy.get("[contenteditable]:first") .type("bar").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n") expect($div.get(0).textContent).to.eql("foobar") expect($div.get(0).innerHTML).to.eql("<div>foobar</div>") it "can type into [contenteditable] with existing <p>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<p>foo</p>' cy.get("[contenteditable]:first") .type("bar").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n\n") expect($div.get(0).textContent).to.eql("foobar") expect($div.get(0).innerHTML).to.eql("<p>foobar</p>") it "collapses selection to start on {leftarrow}", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>bar</div>' cy.get("[contenteditable]:first") .type("{selectall}{leftarrow}foo").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n") it "collapses selection to end on {rightarrow}", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>bar</div>' cy.get("[contenteditable]:first") .type("{selectall}{leftarrow}foo{selectall}{rightarrow}baz").then ($div) -> expect($div.get(0).innerText).to.eql("foobarbaz\n") it "can remove a placeholder <br>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div><br></div>' cy.get("[contenteditable]:first") .type("foobar").then ($div) -> expect($div.get(0).innerHTML).to.eql("<div>foobar</div>") it "can type into an iframe with designmode = 'on'", -> ## append a new iframe to the body cy.$$('<iframe id="generic-iframe" src="/fixtures/generic.html" style="height: 500px"></iframe>') .appendTo cy.$$('body') ## wait for iframe to load loaded = false cy.get('#generic-iframe') .then ($iframe) -> $iframe.load -> loaded = true .scrollIntoView() .should -> expect(loaded).to.eq true ## type text into iframe cy.get('#generic-iframe') .then ($iframe) -> $iframe[0].contentDocument.designMode = 'on' iframe = $iframe.contents() cy.wrap(iframe.find('html')).first() .type('{selectall}{del} foo bar baz{enter}ac{leftarrow}b') # assert that text was typed cy.get('#generic-iframe') .then ($iframe) -> iframeText = $iframe[0].contentDocument.body.innerText expect(iframeText).to.include('foo bar baz\nabc') ## TODO: fix this with 4.0 updates describe.skip "element reference loss", -> it 'follows the focus of the cursor', -> charCount = 0 cy.$$('input:first').keydown -> if charCount is 3 cy.$$('input').eq(1).focus() charCount++ cy.get('input:first').type('foobar').then -> cy.get('input:first').should('have.value', 'foo') cy.get('input').eq(1).should('have.value', 'bar') describe "specialChars", -> context "{{}", -> it "sets which and keyCode to 219", (done) -> cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 219 expect(e.keyCode).to.eq 219 done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires keypress event with 123 charCode", (done) -> cy.$$(":text:first").on "keypress", (e) -> expect(e.charCode).to.eq 123 expect(e.which).to.eq 123 expect(e.keyCode).to.eq 123 done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires textInput event with e.data", (done) -> cy.$$(":text:first").on "textInput", (e) -> expect(e.originalEvent.data).to.eq "{" done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires input event", (done) -> cy.$$(":text:first").on "input", (e) -> done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "can prevent default character insertion", -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 219 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{{}").then ($input) -> expect($input).to.have.value("foo") context "{esc}", -> it "sets which and keyCode to 27 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 27 expect(e.keyCode).to.eq 27 expect(e.key).to.eq "Escape" done() cy.get(":text:first").invoke("val", "ab").type("{esc}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{esc}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{esc}").then -> done() it "can prevent default esc movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 27 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("d{esc}").then ($input) -> expect($input).to.have.value("food") done() context "{backspace}", -> it "backspaces character to the left", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{backspace}u").then ($input) -> expect($input).to.have.value("bur") it "can backspace a selection range of characters", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'ar' characters $input.get(0).setSelectionRange(1,3) .get(":text:first").type("{backspace}").then ($input) -> expect($input).to.have.value("b") it "sets which and keyCode to 8 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 8 expect(e.keyCode).to.eq 8 expect(e.key).to.eq "Backspace" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}{backspace}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{backspace}").then -> done() it "can prevent default backspace movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 8 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{backspace}").then ($input) -> expect($input).to.have.value("foo") done() context "{del}", -> it "deletes character to the right", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{del}").then ($input) -> expect($input).to.have.value("ba") it "can delete a selection range of characters", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'ar' characters $input.get(0).setSelectionRange(1,3) .get(":text:first").type("{del}").then ($input) -> expect($input).to.have.value("b") it "sets which and keyCode to 46 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 46 expect(e.keyCode).to.eq 46 expect(e.key).to.eq "Delete" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}{del}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{del}").then -> done() it "does fire input event when value changes", (done) -> cy.$$(":text:first").on "input", (e) -> done() cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' characters $input.get(0).setSelectionRange(0,1) .get(":text:first").type("{del}") it "does not fire input event when value does not change", (done) -> cy.$$(":text:first").on "input", (e) -> done("should not have fired input") cy.get(":text:first").invoke("val", "ab").type("{del}").then -> done() it "can prevent default del movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 46 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{del}").then ($input) -> expect($input).to.have.value("foo") done() context "{leftarrow}", -> it "can move the cursor from the end to end - 1", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("banr") it "does not move the cursor if already at bounds 0", -> cy.get(":text:first").invoke("val", "bar").type("{selectall}{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets the cursor to the left bounds", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(1,2) .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("bnar") it "sets the cursor to the very beginning", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(0,1) .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets which and keyCode to 37 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 37 expect(e.keyCode).to.eq 37 expect(e.key).to.eq "ArrowLeft" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then -> done() it "can prevent default left arrow movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 37 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}d").then ($input) -> expect($input).to.have.value("food") done() context "{rightarrow}", -> it "can move the cursor from the beginning to beginning + 1", -> cy.get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the beginning $input.get(0).setSelectionRange(0,0) .get(":text:first").type("{rightarrow}n").then ($input) -> expect($input).to.have.value("bnar") it "does not move the cursor if already at end of bounds", -> cy.get(":text:first").invoke("val", "bar").type("{selectall}{rightarrow}n").then ($input) -> expect($input).to.have.value("barn") it "sets the cursor to the rights bounds", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(1,2) .get(":text:first").type("{rightarrow}n").then ($input) -> expect($input).to.have.value("banr") it "sets the cursor to the very beginning", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> $input.select() .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets which and keyCode to 39 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 39 expect(e.keyCode).to.eq 39 expect(e.key).to.eq "ArrowRight" done() cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then -> done() it "can prevent default right arrow movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 39 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{rightarrow}d").then ($input) -> expect($input).to.have.value("fodo") done() context "{uparrow}", -> beforeEach -> cy.$$("#comments").val("foo\nbar\nbaz") it "sets which and keyCode to 38 and does not fire keypress events", (done) -> cy.$$("#comments").on "keypress", -> done("should not have received keypress") cy.$$("#comments").on "keydown", (e) -> expect(e.which).to.eq 38 expect(e.keyCode).to.eq 38 expect(e.key).to.eq "ArrowUp" done() cy.get("#comments").type("{uparrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$("#comments").on "textInput", (e) -> done("textInput should not have fired") cy.get("#comments").type("{uparrow}").then -> done() it "does not fire input event", (done) -> cy.$$("#comments").on "input", (e) -> done("input should not have fired") cy.get("#comments").type("{uparrow}").then -> done() it "up and down arrow on contenteditable", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' cy.get("[contenteditable]:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33").then ($div) -> expect($div.get(0).innerText).to.eql("foo22\nb11ar\nbaz33\n") it "uparrow ignores current selection", -> ce = cy.$$('[contenteditable]:first').get(0) ce.innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' ## select 'bar' line = cy.$$('[contenteditable]:first div:nth-child(1)').get(0) cy.document().then (doc) -> ce.focus() doc.getSelection().selectAllChildren(line) cy.get("[contenteditable]:first") .type("{uparrow}11").then ($div) -> expect($div.get(0).innerText).to.eql("11foo\nbar\nbaz\n") it "up and down arrow on textarea", -> cy.$$('textarea:first').get(0).value = 'foo\nbar\nbaz' cy.get("textarea:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33").should('have.value', "foo22\nb11ar\nbaz33") it "increments input[type=number]", -> cy.get('input[type="number"]:first') .invoke('val', '12.34') .type('{uparrow}{uparrow}') .should('have.value', '14') context "{downarrow}", -> beforeEach -> cy.$$("#comments").val("foo\nbar\nbaz") it "sets which and keyCode to 40 and does not fire keypress events", (done) -> cy.$$("#comments").on "keypress", -> done("should not have received keypress") cy.$$("#comments").on "keydown", (e) -> expect(e.which).to.eq 40 expect(e.keyCode).to.eq 40 expect(e.key).to.eq "ArrowDown" done() cy.get("#comments").type("{downarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$("#comments").on "textInput", (e) -> done("textInput should not have fired") cy.get("#comments").type("{downarrow}").then -> done() it "does not fire input event", (done) -> cy.$$("#comments").on "input", (e) -> done("input should not have fired") cy.get("#comments").type("{downarrow}").then -> done() it "{downarrow} will move to EOL on textarea", -> cy.$$('textarea:first').get(0).value = 'foo\nbar\nbaz' cy.get("textarea:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33{leftarrow}{downarrow}44").should('have.value', "foo22\nb11ar\nbaz3344") it "decrements input[type='number']", -> cy.get('input[type="number"]:first') .invoke('val', '12.34') .type('{downarrow}{downarrow}') .should('have.value', '11') it "downarrow ignores current selection", -> ce = cy.$$('[contenteditable]:first').get(0) ce.innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' ## select 'foo' line = cy.$$('[contenteditable]:first div:first').get(0) cy.document().then (doc) -> ce.focus() doc.getSelection().selectAllChildren(line) cy.get("[contenteditable]:first") .type("{downarrow}22").then ($div) -> expect($div.get(0).innerText).to.eql("foo\n22bar\nbaz\n") context "{selectall}{del}", -> it "can select all the text and delete", -> cy.get(":text:first").invoke("val", "1234").type("{selectall}{del}").type("foo").then ($text) -> expect($text).to.have.value("foo") it "can select all [contenteditable] and delete", -> cy.get("#input-types [contenteditable]").invoke("text", "1234").type("{selectall}{del}").type("foo").then ($div) -> expect($div).to.have.text("foo") context "{selectall} then type something", -> it "replaces the text", -> cy.get("#input-with-value").type("{selectall}new").then ($text) -> expect($text).to.have.value("new") context "{enter}", -> it "sets which and keyCode to 13 and prevents EOL insertion", (done) -> cy.$$("#input-types textarea").on "keypress", _.after 2, (e) -> done("should not have received keypress event") cy.$$("#input-types textarea").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 13 expect(e.keyCode).to.eq 13 expect(e.key).to.eq "Enter" e.preventDefault() cy.get("#input-types textarea").invoke("val", "foo").type("d{enter}").then ($textarea) -> expect($textarea).to.have.value("food") done() it "sets which and keyCode and charCode to 13 and prevents EOL insertion", (done) -> cy.$$("#input-types textarea").on "keypress", _.after 2, (e) -> expect(e.which).to.eq 13 expect(e.keyCode).to.eq 13 expect(e.charCode).to.eq 13 expect(e.key).to.eq "Enter" e.preventDefault() cy.get("#input-types textarea").invoke("val", "foo").type("d{enter}").then ($textarea) -> expect($textarea).to.have.value("food") done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{enter}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{enter}").then -> done() it "inserts new line into textarea", -> cy.get("#input-types textarea").invoke("val", "foo").type("bar{enter}baz{enter}quux").then ($textarea) -> expect($textarea).to.have.value("foobar\nbaz\nquux") it "inserts new line into [contenteditable] ", -> cy.get("#input-types [contenteditable]:first").invoke("text", "foo") .type("bar{enter}baz{enter}{enter}{enter}quux").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\nbaz\n\n\nquux\n") expect($div.get(0).textContent).to.eql("foobarbazquux") expect($div.get(0).innerHTML).to.eql("foobar<div>baz</div><div><br></div><div><br></div><div>quux</div>") it "inserts new line into [contenteditable] from midline", -> cy.get("#input-types [contenteditable]:first").invoke("text", "foo") .type("bar{leftarrow}{enter}baz{leftarrow}{enter}quux").then ($div) -> expect($div.get(0).innerText).to.eql("fooba\nba\nquuxzr\n") expect($div.get(0).textContent).to.eql("foobabaquuxzr") expect($div.get(0).innerHTML).to.eql("fooba<div>ba</div><div>quuxzr</div>") describe "modifiers", -> describe "activating modifiers", -> it "sends keydown event for modifiers in order", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy.get("input:text:first").type("{shift}{ctrl}").then -> expect(events[0].shiftKey).to.be.true expect(events[0].which).to.equal(16) expect(events[1].ctrlKey).to.be.true expect(events[1].which).to.equal(17) $input.off("keydown") done() it "maintains modifiers for subsequent characters", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy.get("input:text:first").type("{command}{control}ok").then -> expect(events[2].metaKey).to.be.true expect(events[2].ctrlKey).to.be.true expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.true expect(events[3].ctrlKey).to.be.true expect(events[3].which).to.equal(75) $input.off("keydown") done() it "does not maintain modifiers for subsequent type commands", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy .get("input:text:first") .type("{command}{control}") .type("ok") .then -> expect(events[2].metaKey).to.be.false expect(events[2].ctrlKey).to.be.false expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.false expect(events[3].ctrlKey).to.be.false expect(events[3].which).to.equal(75) $input.off("keydown") done() it "does not maintain modifiers for subsequent click commands", (done) -> $button = cy.$$("button:first") mouseDownEvent = null mouseUpEvent = null clickEvent = null $button.on "mousedown", (e)-> mouseDownEvent = e $button.on "mouseup", (e)-> mouseUpEvent = e $button.on "click", (e)-> clickEvent = e cy .get("input:text:first") .type("{cmd}{option}") .get("button:first").click().then -> expect(mouseDownEvent.metaKey).to.be.false expect(mouseDownEvent.altKey).to.be.false expect(mouseUpEvent.metaKey).to.be.false expect(mouseUpEvent.altKey).to.be.false expect(clickEvent.metaKey).to.be.false expect(clickEvent.altKey).to.be.false $button.off "mousedown" $button.off "mouseup" $button.off "click" done() it "sends keyup event for activated modifiers when typing is finished", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keyup", (e) -> events.push(e) cy .get("input:text:first") .type("{alt}{ctrl}{meta}{shift}ok") .then -> # first keyups should be for the chars typed, "ok" expect(events[0].which).to.equal(79) expect(events[1].which).to.equal(75) expect(events[2].which).to.equal(18) expect(events[3].which).to.equal(17) expect(events[4].which).to.equal(91) expect(events[5].which).to.equal(16) $input.off("keyup") done() describe "release: false", -> it "maintains modifiers for subsequent type commands", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy .get("input:text:first") .type("{command}{control}", { release: false }) .type("ok") .then -> expect(events[2].metaKey).to.be.true expect(events[2].ctrlKey).to.be.true expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.true expect(events[3].ctrlKey).to.be.true expect(events[3].which).to.equal(75) done() it "maintains modifiers for subsequent click commands", (done) -> $button = cy.$$("button:first") mouseDownEvent = null mouseUpEvent = null clickEvent = null $button.on "mousedown", (e) -> mouseDownEvent = e $button.on "mouseup", (e) -> mouseUpEvent = e $button.on "click", (e) -> clickEvent = e cy .get("input:text:first") .type("{meta}{alt}", { release: false }) .get("button:first").click().then -> expect(mouseDownEvent.metaKey).to.be.true expect(mouseDownEvent.altKey).to.be.true expect(mouseUpEvent.metaKey).to.be.true expect(mouseUpEvent.altKey).to.be.true expect(clickEvent.metaKey).to.be.true expect(clickEvent.altKey).to.be.true done() it "resets modifiers before next test", -> ## this test will fail if you comment out ## $Keyboard.resetModifiers $input = cy.$$("input:text:first") events = [] $input.on "keyup", (e) -> events.push(e) cy .get("input:text:first") .type("a", { release: false }) .then -> expect(events[0].metaKey).to.be.false expect(events[0].ctrlKey).to.be.false expect(events[0].altKey).to.be.false describe "changing modifiers", -> beforeEach -> @$input = cy.$$("input:text:first") cy.get("input:text:first").type("{command}{option}", { release: false }) afterEach -> @$input.off("keydown") it "sends keydown event for new modifiers", (done) -> event = null @$input.on "keydown", (e)-> event = e cy.get("input:text:first").type("{shift}").then -> expect(event.shiftKey).to.be.true expect(event.which).to.equal(16) done() it "does not send keydown event for already activated modifiers", (done) -> triggered = false @$input.on "keydown", (e)-> triggered = true if e.which is 18 or e.which is 17 cy.get("input:text:first").type("{cmd}{alt}").then -> expect(triggered).to.be.false done() describe "case-insensitivity", -> it "special chars are case-insensitive", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{DeL}").then ($input) -> expect($input).to.have.value("ba") it "modifiers are case-insensitive", (done) -> $input = cy.$$("input:text:first") alt = false $input.on "keydown", (e) -> alt = true if e.altKey cy.get("input:text:first").type("{aLt}").then -> expect(alt).to.be.true $input.off("keydown") done() it "letters are case-sensitive", -> cy.get("input:text:first").type("FoO").then ($input) -> expect($input).to.have.value("FoO") describe "click events", -> it "passes timeout and interval down to click", (done) -> input = $("<input />").attr("id", "input-covered-in-span").prependTo(cy.$$("body")) span = $("<span>span on input</span>") .css { position: "absolute" left: input.offset().left top: input.offset().top padding: 5 display: "inline-block" backgroundColor: "yellow" } .prependTo cy.$$("body") cy.on "command:retry", (options) -> expect(options.timeout).to.eq 1000 expect(options.interval).to.eq 60 done() cy.get("#input-covered-in-span").type("foobar", {timeout: 1000, interval: 60}) it "does not issue another click event between type/type", -> clicked = 0 cy.$$(":text:first").click -> clicked += 1 cy.get(":text:first").type("f").type("o").then -> expect(clicked).to.eq 1 it "does not issue another click event if element is already in focus from click", -> clicked = 0 cy.$$(":text:first").click -> clicked += 1 cy.get(":text:first").click().type("o").then -> expect(clicked).to.eq 1 describe "change events", -> it "fires when enter is pressed and value has changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("bar{enter}").then -> expect(changed).to.eq 1 it "fires twice when enter is pressed and then again after losing focus", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("bar{enter}baz").blur().then -> expect(changed).to.eq 2 it "fires when element loses focus due to another action (click)", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 .get("button:first").click().then -> expect(changed).to.eq 1 it "fires when element loses focus due to another action (type)", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 .get("textarea:first").type("bar").then -> expect(changed).to.eq 1 it "fires when element is directly blurred", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").blur().then -> expect(changed).to.eq 1 it "fires when element is tabbed away from"#, -> # changed = 0 # cy.$$(":text:first").change -> # changed += 1 # cy.get(":text:first").invoke("val", "foo").type("b{tab}").then -> # expect(changed).to.eq 1 it "does not fire twice if element is already in focus between type/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("f").type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between clear/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").clear().type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between click/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").click().type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between type/click", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("d{enter}").click().then -> expect(changed).to.eq 1 it "does not fire at all between clear/type/click", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").clear().type("o").click().then ($el) -> expect(changed).to.eq 0 $el .blur() .then -> expect(changed).to.eq 1 it "does not fire if {enter} is preventedDefault", -> changed = 0 cy.$$(":text:first").keypress (e) -> e.preventDefault() if e.which is 13 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("b{enter}").then -> expect(changed).to.eq 0 it "does not fire when enter is pressed and value hasnt changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("b{backspace}{enter}").then -> expect(changed).to.eq 0 it "does not fire at the end of the type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 it "does not fire change event if value hasnt actually changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").invoke("val", "foo").type("{backspace}{backspace}oo{enter}").blur().then -> expect(changed).to.eq 0 it "does not fire if mousedown is preventedDefault which prevents element from losing focus", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.$$("textarea:first").mousedown -> return false cy .get(":text:first").invoke("val", "foo").type("bar") .get("textarea:first").click().then -> expect(changed).to.eq 0 it "does not fire hitting {enter} inside of a textarea", -> changed = 0 cy.$$("textarea:first").change -> changed += 1 cy .get("textarea:first").type("foo{enter}bar").then -> expect(changed).to.eq 0 it "does not fire hitting {enter} inside of [contenteditable]", -> changed = 0 cy.$$("[contenteditable]:first").change -> changed += 1 cy .get("[contenteditable]:first").type("foo{enter}bar").then -> expect(changed).to.eq 0 ## [contenteditable] does not fire ANY change events ever. it "does not fire at ALL for [contenteditable]", -> changed = 0 cy.$$("[contenteditable]:first").change -> changed += 1 cy .get("[contenteditable]:first").type("foo") .get("button:first").click().then -> expect(changed).to.eq 0 it "does not fire on .clear() without blur", -> changed = 0 cy.$$("input:first").change -> changed += 1 cy.get("input:first").invoke('val', 'foo') .clear() .then ($el) -> expect(changed).to.eq 0 $el .type('foo') .blur() .then -> expect(changed).to.eq 0 it "fires change for single value change inputs", -> changed = 0 cy.$$('input[type="date"]:first').change -> changed++ cy.get('input[type="date"]:first') .type("1959-09-13") .blur() .then -> expect(changed).to.eql 1 it "does not fire change for non-change single value input", -> changed = 0 cy.$$('input[type="date"]:first').change -> changed++ cy.get('input[type="date"]:first') .invoke('val', "1959-09-13") .type("1959-09-13") .blur() .then -> expect(changed).to.eql(0) it "does not fire change for type'd change that restores value", -> changed = 0 cy.$$('input:first').change -> changed++ cy.get('input:first') .invoke('val', 'foo') .type('{backspace}o') .invoke('val', 'bar') .type('{backspace}r') .blur() .then -> expect(changed).to.eql 0 describe "caret position", -> it "respects being formatted by input event handlers" it "can arrow from maxlength", -> cy.get('input:first').invoke('attr', 'maxlength', "5").type('foobar{leftarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:4, end:4}) it "won't arrowright past length", -> cy.get('input:first').type('foo{rightarrow}{rightarrow}{rightarrow}bar{rightarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:6, end:6}) it "won't arrowleft before word", -> cy.get('input:first').type('oo' + '{leftarrow}{leftarrow}{leftarrow}' + 'f' + '{leftarrow}'.repeat(5)) cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:0, end:0}) it "leaves caret at the end of contenteditable", -> cy.get('[contenteditable]:first').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:6, end:6}) it "leaves caret at the end of contenteditable when prefilled", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'foo' cy.get('[contenteditable]:first').type('bar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:6, end:6}) it "can move the caret left on contenteditable", -> cy.get('[contenteditable]:first').type('foo{leftarrow}{leftarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:1, end:1}) ##make sure caret is correct ## type left left ## make sure caret correct ## text is fboo ## fix input-mask issue it "leaves caret at the end of input", -> cy.get(':text:first').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$(':text:first').get(0) .to.deep.eq({start:6, end:6}) it "leaves caret at the end of textarea", -> cy.get('#comments').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('#comments').get(0) .to.deep.eq({start:6, end:6}) it "can wrap cursor to next line in [contenteditable] with {rightarrow}", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'start'+ '<div>middle</div>'+ '<div>end</div>' cy.get('[contenteditable]:first') ## move cursor to beginning of div .type('{selectall}{leftarrow}') .type('{rightarrow}'.repeat(14)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('start\nmiddle\ne[_I_]nd\n') it "can wrap cursor to prev line in [contenteditable] with {leftarrow}", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'start'+ '<div>middle</div>'+ '<div>end</div>' cy.get('[contenteditable]:first').type('{leftarrow}'.repeat(12)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('star[_I_]t\nmiddle\nend\n') it "can wrap cursor to next line in [contenteditable] with {rightarrow} and empty lines", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = '<div><br></div>'.repeat(4)+ '<div>end</div>' cy.get('[contenteditable]:first') .type('{selectall}{leftarrow}') # .type('foobar'+'{rightarrow}'.repeat(6)+'[_I_]').then -> # expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('foobar\n\n\n\nen[_I_]d\n') it "can use {rightarrow} and nested elements", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = '<div><b>s</b>ta<b>rt</b></div>' cy.get('[contenteditable]:first') .type('{selectall}{leftarrow}') .type('{rightarrow}'.repeat(3)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('sta[_I_]rt\n') it "enter and \\n should act the same for [contenteditable]", -> cleanseText = (text) -> text.replace(/ /g, ' ') expectMatchInnerText = ($el , innerText) -> expect(cleanseText($el.get(0).innerText)).to.eql(innerText) ## NOTE: this may only pass in Chrome since the whitespace may be different in other browsers ## even if actual and expected appear the same. expected = "{\n foo: 1\n bar: 2\n baz: 3\n}\n" cy.get('[contenteditable]:first') .invoke('html', '<div><br></div>') .type('{{}{enter} foo: 1{enter} bar: 2{enter} baz: 3{enter}}') .should ($el) -> expectMatchInnerText($el, expected) .clear() .type('{{}\n foo: 1\n bar: 2\n baz: 3\n}') .should ($el) -> expectMatchInnerText($el, expected) it "enter and \\n should act the same for textarea", -> expected = "{\n foo: 1\n bar: 2\n baz: 3\n}" cy.get('textarea:first') .clear() .type('{{}{enter} foo: 1{enter} bar: 2{enter} baz: 3{enter}}') .should('have.prop', 'value', expected) .clear() .type('{{}\n foo: 1\n bar: 2\n baz: 3\n}') .should('have.prop', 'value', expected) describe "{enter}", -> beforeEach -> @$forms = cy.$$("#form-submits") context "1 input, no 'submit' elements", -> it "triggers form submit", (done) -> @foo = {} @$forms.find("#single-input").submit (e) -> e.preventDefault() done() cy.get("#single-input input").type("foo{enter}") it "triggers form submit synchronously before type logs or resolves", -> events = [] cy.on "command:start", (cmd) -> events.push "#{cmd.get('name')}:start" @$forms.find("#single-input").submit (e) -> e.preventDefault() events.push "submit" cy.on "log:added", (attrs, log) -> state = log.get("state") if state is "pending" log.on "state:changed", (state) -> events.push "#{log.get('name')}:log:#{state}" events.push "#{log.get('name')}:log:#{state}" cy.on "command:end", (cmd) -> events.push "#{cmd.get('name')}:end" cy.get("#single-input input").type("f{enter}").then -> expect(events).to.deep.eq [ "get:start", "get:log:pending", "get:end", "type:start", "type:log:pending", "submit", "type:end", "then:start" ] it "triggers 2 form submit event", -> submits = 0 @$forms.find("#single-input").submit (e) -> e.preventDefault() submits += 1 cy.get("#single-input input").type("f{enter}{enter}").then -> expect(submits).to.eq 2 it "does not submit when keydown is defaultPrevented on input", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("input").keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keydown is defaultPrevented on wrapper", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("div").keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keydown is defaultPrevented on form", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on input", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on wrapper", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("div").keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on form", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() context "2 inputs, no 'submit' elements", -> it "does not trigger submit event", (done) -> form = @$forms.find("#no-buttons").submit -> done("err: should not have submitted") cy.get("#no-buttons input:first").type("f").type("{enter}").then -> done() context "2 inputs, no 'submit' elements but 1 button[type=button]", -> it "does not trigger submit event", (done) -> form = @$forms.find("#one-button-type-button").submit -> done("err: should not have submitted") cy.get("#one-button-type-button input:first").type("f").type("{enter}").then -> done() context "2 inputs, 1 'submit' element input[type=submit]", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-input-submit").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-input-submit input:first").type("foo{enter}") it "causes click event on the input[type=submit]", (done) -> @$forms.find("#multiple-inputs-and-input-submit input[type=submit]").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-input-submit input:first").type("foo{enter}") it "does not cause click event on the input[type=submit] if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-input-submit").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-input-submit input:first").type("f{enter}").then -> done() context "2 inputs, 1 'submit' element button[type=submit]", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-button-submit").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-submit input:first").type("foo{enter}") it "causes click event on the button[type=submit]", (done) -> @$forms.find("#multiple-inputs-and-button-submit button[type=submit]").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-submit input:first").type("foo{enter}") it "does not cause click event on the button[type=submit] if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-button-submit").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-button-submit input:first").type("f{enter}").then -> done() context "2 inputs, 1 'submit' element button", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-button-with-no-type").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("foo{enter}") it "causes click event on the button", (done) -> @$forms.find("#multiple-inputs-and-button-with-no-type button").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("foo{enter}") it "does not cause click event on the button if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-button-with-no-type").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("f{enter}").then -> done() context "2 inputs, 2 'submit' elements", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}") it "causes click event on the button", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits button").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}") it "does not cause click event on the button if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-multiple-submits").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-multiple-submits input:first").type("f{enter}").then -> done() context "disabled default button", -> beforeEach -> @$forms.find("#multiple-inputs-and-multiple-submits").find("button").prop("disabled", true) it "will not receive click event", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits button").click -> done("err: should not receive click event") cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}").then -> done() it "will not submit the form", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits").submit -> done("err: should not receive submit event") cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}").then -> done() describe "assertion verification", -> beforeEach -> cy.on "log:added", (attrs, log) => if log.get("name") is "assert" @lastLog = log return null it "eventually passes the assertion", -> cy.$$("input:first").keyup -> _.delay => $(@).addClass("typed") , 100 cy.get("input:first").type("f").should("have.class", "typed").then -> lastLog = @lastLog expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("passed") expect(lastLog.get("ended")).to.be.true describe ".log", -> beforeEach -> cy.on "log:added", (attrs, log) => @lastLog = log return null it "passes in $el", -> cy.get("input:first").type("foobar").then ($input) -> lastLog = @lastLog expect(lastLog.get("$el")).to.eq $input it "logs message", -> cy.get(":text:first").type("foobar").then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foobar" it "logs delay arguments", -> cy.get(":text:first").type("foo", {delay: 20}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foo, {delay: 20}" it "clones textarea value after the type happens", -> expectToHaveValueAndCoords = => cmd = cy.queue.find({name: "type"}) log = cmd.get("logs")[0] txt = log.get("snapshots")[1].body.find("#comments") expect(txt).to.have.value("foobarbaz") expect(log.get("coords")).to.be.ok cy .get("#comments").type("foobarbaz").then ($txt) -> expectToHaveValueAndCoords() .get("#comments").clear().type("onetwothree").then -> expectToHaveValueAndCoords() it "clones textarea value when textarea is focused first", -> expectToHaveValueAndNoCoords = => cmd = cy.queue.find({name: "type"}) log = cmd.get("logs")[0] txt = log.get("snapshots")[1].body.find("#comments") expect(txt).to.have.value("foobarbaz") expect(log.get("coords")).not.to.be.ok cy .get("#comments").focus().type("foobarbaz").then ($txt) -> expectToHaveValueAndNoCoords() .get("#comments").clear().type("onetwothree").then -> expectToHaveValueAndNoCoords() it "logs only one type event", -> logs = [] types = [] cy.on "log:added", (attrs, log) -> logs.push(log) if log.get("name") is "type" types.push(log) cy.get(":text:first").type("foo").then -> expect(logs.length).to.eq(2) expect(types.length).to.eq(1) it "logs immediately before resolving", -> $txt = cy.$$(":text:first") expected = false cy.on "log:added", (attrs, log) -> if log.get("name") is "type" expect(log.get("state")).to.eq("pending") expect(log.get("$el").get(0)).to.eq $txt.get(0) expected = true cy.get(":text:first").type("foo").then -> cy.get(":text:first").type("foo") it "snapshots before typing", -> expected = false cy.$$(":text:first").one "keydown", => lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(1) expect(lastLog.get("snapshots")[0].name).to.eq("before") expect(lastLog.get("snapshots")[0].body).to.be.an("object") expected = true cy.get(":text:first").type("foo").then -> expect(expected).to.be.true it "snapshots after typing", -> cy.get(":text:first").type("foo").then -> lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(2) expect(lastLog.get("snapshots")[1].name).to.eq("after") expect(lastLog.get("snapshots")[1].body).to.be.an("object") it "logs deltaOptions", -> cy.get(":text:first").type("foo", {force: true, timeout: 1000}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foo, {force: true, timeout: 1000}" expect(lastLog.invoke("consoleProps").Options).to.deep.eq {force: true, timeout: 1000} context "#consoleProps", -> it "has all of the regular options", -> cy.get("input:first").type("foobar").then ($input) -> { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($input) console = @lastLog.invoke("consoleProps") expect(console.Command).to.eq("type") expect(console.Typed).to.eq("foobar") expect(console["Applied To"]).to.eq $input.get(0) expect(console.Coords.x).to.be.closeTo(fromWindow.x, 1) expect(console.Coords.y).to.be.closeTo(fromWindow.y, 1) it "has a table of keys", -> cy.get(":text:first").type("{cmd}{option}foo{enter}b{leftarrow}{del}{enter}").then -> table = @lastLog.invoke("consoleProps").table() console.table(table.data, table.columns) expect(table.columns).to.deep.eq [ "typed", "which", "keydown", "keypress", "textInput", "input", "keyup", "change", "modifiers" ] expect(table.name).to.eq "Key Events Table" expectedTable = { 1: {typed: "<meta>", which: 91, keydown: true, modifiers: "meta"} 2: {typed: "<alt>", which: 18, keydown: true, modifiers: "alt, meta"} 3: {typed: "f", which: 70, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 4: {typed: "o", which: 79, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 5: {typed: "o", which: 79, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 6: {typed: "{enter}", which: 13, keydown: true, keypress: true, keyup: true, change: true, modifiers: "alt, meta"} 7: {typed: "b", which: 66, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 8: {typed: "{leftarrow}", which: 37, keydown: true, keyup: true, modifiers: "alt, meta"} 9: {typed: "{del}", which: 46, keydown: true, input: true, keyup: true, modifiers: "alt, meta"} 10: {typed: "{enter}", which: 13, keydown: true, keypress: true, keyup: true, modifiers: "alt, meta"} } for i in [1..10] expect(table.data[i]).to.deep.eq(expectedTable[i]) # table.data.forEach (item, i) -> # expect(item).to.deep.eq(expectedTable[i]) # expect(table.data).to.deep.eq(expectedTable) it "has no modifiers when there are none activated", -> cy.get(":text:first").type("f").then -> table = @lastLog.invoke("consoleProps").table() expect(table.data).to.deep.eq { 1: {typed: "f", which: 70, keydown: true, keypress: true, textInput: true, input: true, keyup: true} } it "has a table of keys with preventedDefault", -> cy.$$(":text:first").keydown -> return false cy.get(":text:first").type("f").then -> table = @lastLog.invoke("consoleProps").table() console.table(table.data, table.columns) expect(table.data).to.deep.eq { 1: {typed: "f", which: 70, keydown: "preventedDefault", keyup: true} } describe "errors", -> beforeEach -> Cypress.config("defaultCommandTimeout", 100) @logs = [] cy.on "log:added", (attrs, log) => @lastLog = log @logs.push(log) return null it "throws when not a dom subject", (done) -> cy.on "fail", -> done() cy.noop({}).type("foo") it "throws when subject is not in the document", (done) -> typed = 0 input = cy.$$("input:first").keypress (e) -> typed += 1 input.remove() cy.on "fail", (err) -> expect(typed).to.eq 1 expect(err.message).to.include "cy.type() failed because this element" done() cy.get("input:first").type("a").type("b") it "throws when not textarea or text-like", (done) -> cy.get("form").type("foo") cy.on "fail", (err) -> expect(err.message).to.include "cy.type() failed because it requires a valid typeable element." expect(err.message).to.include "The element typed into was:" expect(err.message).to.include "<form id=\"by-id\">...</form>" expect(err.message).to.include "Cypress considers the 'body', 'textarea', any 'element' with a 'tabindex' or 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid typeable elements." done() it "throws when subject is a collection of elements", (done) -> cy.get("textarea,:text").then ($inputs) -> @num = $inputs.length return $inputs .type("foo") cy.on "fail", (err) => expect(err.message).to.include "cy.type() can only be called on a single element. Your subject contained #{@num} elements." done() it "throws when the subject isnt visible", (done) -> input = cy.$$("input:text:first").show().hide() cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(2) expect(lastLog.get("error")).to.eq(err) expect(err.message).to.include "cy.type() failed because this element is not visible" done() cy.get("input:text:first").type("foo") it "throws when subject is disabled", (done) -> cy.$$("input:text:first").prop("disabled", true) cy.on "fail", (err) => ## get + type logs expect(@logs.length).eq(2) expect(err.message).to.include("cy.type() failed because this element is disabled:\n") done() cy.get("input:text:first").type("foo") it "throws when submitting within nested forms" it "logs once when not dom subject", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(1) expect(lastLog.get("error")).to.eq(err) done() cy.type("foobar") it "throws when input cannot be clicked", (done) -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on button</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.include "cy.type() failed because this element" expect(err.message).to.include "is being covered by another element" done() cy.get("#input-covered-in-span").type("foo") it "throws when special characters dont exist", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 allChars = _.keys(Keyboard.specialChars).concat(_.keys(Keyboard.modifierChars)).join(", ") expect(err.message).to.eq "Special character sequence: '{bar}' is not recognized. Available sequences are: #{allChars}" done() cy.get(":text:first").type("foo{bar}") it "throws when attemping to type tab", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "{tab} isn't a supported character sequence. You'll want to use the command cy.tab(), which is not ready yet, but when it is done that's what you'll use." done() cy.get(":text:first").type("foo{tab}") it "throws on an empty string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "cy.type() cannot accept an empty String. You need to actually type something." done() cy.get(":text:first").type("") it "allows typing spaces", -> cy .get(":text:first").type(" ") .should("have.value", " ") it "can type into input with invalid type attribute", -> cy.get(':text:first') .invoke('attr', 'type', 'asdf') .type('foobar') .should('have.value', 'foobar') _.each [NaN, Infinity, [], {}, null, undefined], (val) => it "throws when trying to type: #{val}", (done) -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "cy.type() can only accept a String or Number. You passed in: '#{val}'" done() cy.get(":text:first").type(val) it "throws when type is cancelled by preventingDefault mousedown" it "throws when element animation exceeds timeout", (done) -> ## force the animation calculation to think we moving at a huge distance ;-) cy.stub(Cypress.utils, "getDistanceBetween").returns(100000) keydowns = 0 cy.$$(":text:first").on "keydown", -> keydowns += 1 cy.on "fail", (err) -> expect(keydowns).to.eq(0) expect(err.message).to.include("cy.type() could not be issued because this element is currently animating:\n") done() cy.get(":text:first").type("foo") it "eventually fails the assertion", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(err.message).to.include(lastLog.get("error").message) expect(err.message).not.to.include("undefined") expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("failed") expect(lastLog.get("error")).to.be.an.instanceof(chai.AssertionError) done() cy.get("input:first").type("f").should("have.class", "typed") it "does not log an additional log on failure", (done) -> cy.on "fail", => expect(@logs.length).to.eq(3) done() cy.get("input:first").type("f").should("have.class", "typed") context "[type=date]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 1989") done() cy.get("#date-without-value").type(1989) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 01-01-1989") done() cy.get("#date-without-value").type("01-01-1989") it "throws when chars is invalid date", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 1989-04-31") done() cy.get("#date-without-value").type("1989-04-31") context "[type=month]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 6") done() cy.get("#month-without-value").type(6) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 01/2000") done() cy.get("#month-without-value").type("01/2000") it "throws when chars is invalid month", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 1989-13") done() cy.get("#month-without-value").type("1989-13") context "[type=tel]", -> it "can edit tel", -> cy.get('#by-name > input[type="tel"]') .type('1234567890') .should('have.prop', 'value', '1234567890') # it "throws when chars is invalid format", (done) -> # cy.on "fail", (err) => # expect(@logs.length).to.eq(2) # expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 2005/W18") # done() context "[type=week]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 23") done() cy.get("#week-without-value").type(23) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 2005/W18") done() cy.get("#week-without-value").type("2005/W18") it "throws when chars is invalid week", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 1995-W60") done() cy.get("#week-without-value").type("1995-W60") context "[type=time]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 9999") done() cy.get("#time-without-value").type(9999) it "throws when chars is invalid format (1:30)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 1:30") done() cy.get("#time-without-value").type("1:30") it "throws when chars is invalid format (01:30pm)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:30pm") done() cy.get("#time-without-value").type("01:30pm") it "throws when chars is invalid format (01:30:30.3333)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:30:30.3333") done() cy.get("#time-without-value").type("01:30:30.3333") it "throws when chars is invalid time", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:60") done() cy.get("#time-without-value").type("01:60") context "#clear", -> it "does not change the subject", -> textarea = cy.$$("textarea") cy.get("textarea").clear().then ($textarea) -> expect($textarea).to.match textarea it "removes the current value", -> textarea = cy.$$("#comments") textarea.val("foo bar") ## make sure it really has that value first expect(textarea).to.have.value("foo bar") cy.get("#comments").clear().then ($textarea) -> expect($textarea).to.have.value("") it "waits until element is no longer disabled", -> textarea = cy.$$("#comments").val("foo bar").prop("disabled", true) retried = false clicks = 0 textarea.on "click", -> clicks += 1 cy.on "command:retry", _.after 3, -> textarea.prop("disabled", false) retried = true cy.get("#comments").clear().then -> expect(clicks).to.eq(1) expect(retried).to.be.true it "can forcibly click even when being covered by another element", -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) clicked = false $input.on "click", -> clicked = true cy.get("#input-covered-in-span").clear({force: true}).then -> expect(clicked).to.be.true it "passes timeout and interval down to click", (done) -> input = $("<input />").attr("id", "input-covered-in-span").prependTo(cy.$$("body")) span = $("<span>span on input</span>").css(position: "absolute", left: input.offset().left, top: input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow").prependTo(cy.$$("body")) cy.on "command:retry", (options) -> expect(options.timeout).to.eq 1000 expect(options.interval).to.eq 60 done() cy.get("#input-covered-in-span").clear({timeout: 1000, interval: 60}) context "works on input type", -> inputTypes = [ "date", "datetime", "datetime-local", "email", "month", "number", "password", "search", "tel", "text", "time", "url", "week" ] inputTypes.forEach (type) -> it type, -> cy.get("##{type}-with-value").clear().then ($input) -> expect($input.val()).to.equal("") describe "assertion verification", -> beforeEach -> cy.on "log:added", (attrs, log) => if log.get("name") is "assert" @lastLog = log return null it "eventually passes the assertion", -> cy.$$("input:first").keyup -> _.delay => $(@).addClass("cleared") , 100 cy.get("input:first").clear().should("have.class", "cleared").then -> lastLog = @lastLog expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("passed") expect(lastLog.get("ended")).to.be.true it "eventually passes the assertion on multiple inputs", -> cy.$$("input").keyup -> _.delay => $(@).addClass("cleared") , 100 cy.get("input").invoke("slice", 0, 2).clear().should("have.class", "cleared") describe "errors", -> beforeEach -> Cypress.config("defaultCommandTimeout", 100) @logs = [] cy.on "log:added", (attrs, log) => @lastLog = log @logs.push(log) return null it "throws when not a dom subject", (done) -> cy.on "fail", (err) -> done() cy.noop({}).clear() it "throws when subject is not in the document", (done) -> cleared = 0 input = cy.$$("input:first").val("123").keydown (e) -> cleared += 1 input.remove() cy.on "fail", (err) -> expect(cleared).to.eq 1 expect(err.message).to.include "cy.clear() failed because this element" done() cy.get("input:first").clear().clear() it "throws if any subject isnt a textarea or text-like", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(3) expect(lastLog.get("error")).to.eq(err) expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<form id=\"checkboxes\">...</form>" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get("textarea:first,form#checkboxes").clear() it "throws if any subject isnt a :text", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<div id=\"dom\">...</div>" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get("div").clear() it "throws on an input radio", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<input type=\"radio\" name=\"gender\" value=\"male\">" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get(":radio").clear() it "throws on an input checkbox", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<input type=\"checkbox\" name=\"colors\" value=\"blue\">" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get(":checkbox").clear() it "throws when the subject isnt visible", (done) -> input = cy.$$("input:text:first").show().hide() cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because this element is not visible" done() cy.get("input:text:first").clear() it "throws when subject is disabled", (done) -> cy.$$("input:text:first").prop("disabled", true) cy.on "fail", (err) => ## get + type logs expect(@logs.length).eq(2) expect(err.message).to.include("cy.clear() failed because this element is disabled:\n") done() cy.get("input:text:first").clear() it "logs once when not dom subject", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(1) expect(lastLog.get("error")).to.eq(err) done() cy.clear() it "throws when input cannot be cleared", (done) -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.include "cy.clear() failed because this element" expect(err.message).to.include "is being covered by another element" done() cy.get("#input-covered-in-span").clear() it "eventually fails the assertion", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(err.message).to.include(lastLog.get("error").message) expect(err.message).not.to.include("undefined") expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("failed") expect(lastLog.get("error")).to.be.an.instanceof(chai.AssertionError) done() cy.get("input:first").clear().should("have.class", "cleared") it "does not log an additional log on failure", (done) -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) cy.on "fail", => expect(@logs.length).to.eq(3) done() cy.get("input:first").clear().should("have.class", "cleared") describe ".log", -> beforeEach -> cy.on "log:added", (attrs, log) => @lastLog = log return null it "logs immediately before resolving", -> $input = cy.$$("input:first") expected = false cy.on "log:added", (attrs, log) -> if log.get("name") is "clear" expect(log.get("state")).to.eq("pending") expect(log.get("$el").get(0)).to.eq $input.get(0) expected = true cy.get("input:first").clear().then -> expect(expected).to.be.true it "ends", -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) if log.get("name") is "clear" cy.get("input").invoke("slice", 0, 2).clear().then -> _.each logs, (log) -> expect(log.get("state")).to.eq("passed") expect(log.get("ended")).to.be.true it "snapshots after clicking", -> cy.get("input:first").clear().then ($input) -> lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(1) expect(lastLog.get("snapshots")[0]).to.be.an("object") it "logs deltaOptions", -> cy.get("input:first").clear({force: true, timeout: 1000}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "{force: true, timeout: 1000}" expect(lastLog.invoke("consoleProps").Options).to.deep.eq {force: true, timeout: 1000}
141101
$ = Cypress.$.bind(Cypress) _ = Cypress._ Keyboard = Cypress.Keyboard Promise = Cypress.Promise $selection = require("../../../../../src/dom/selection") describe "src/cy/commands/actions/type", -> before -> cy .visit("/fixtures/dom.html") .then (win) -> @body = win.document.body.outerHTML beforeEach -> doc = cy.state("document") $(doc.body).empty().html(@body) context "#type", -> it "does not change the subject", -> input = cy.$$("input:first") cy.get("input:first").type("foo").then ($input) -> expect($input).to.match input it "changes the value", -> input = cy.$$("input:text:first") input.val("") ## make sure we are starting from a ## clean state expect(input).to.have.value("") cy.get("input:text:first").type("foo").then ($input) -> expect($input).to.have.value("foo") it "appends subsequent type commands", -> cy .get("input:first").type("123").type("456") .should("have.value", "123456") it "appends subsequent commands when value is changed in between", -> cy .get("input:first") .type("123") .then ($input) -> $input[0].value += '-' return $input .type("456") .should("have.value", "123-456") it "can type numbers", -> cy.get(":text:first").type(123).then ($text) -> expect($text).to.have.value("123") it "triggers focus event on the input", (done) -> cy.$$("input:text:first").focus -> done() cy.get("input:text:first").type("bar") it "lists the input as the focused element", -> $input = cy.$$("input:text:first") cy.get("input:text:first").type("bar").focused().then ($focused) -> expect($focused.get(0)).to.eq $input.get(0) it "causes previous input to receive blur", -> blurred = false cy.$$("input:text:first").blur -> blurred = true cy .get("input:text:first").type("foo") .get("input:text:last").type("bar") .then -> expect(blurred).to.be.true it "can type into contenteditable", -> oldText = cy.$$("#contenteditable").get(0).innerText cy.get("#contenteditable") .type(" foo") .then ($div) -> expect($div.get(0).innerText).to.eq (oldText + " foo") it "delays 50ms before resolving", -> cy.$$(":text:first").on "change", (e) => cy.spy(Promise, "delay") cy.get(":text:first").type("foo{enter}").then -> expect(Promise.delay).to.be.calledWith(50, "type") it "increases the timeout delta", -> cy.spy(cy, "timeout") cy.get(":text:first").type("foo{enter}").then -> expect(cy.timeout).to.be.calledWith(40, true, "type") expect(cy.timeout).to.be.calledWith(50, true, "type") it "accepts body as subject", -> cy.get("body").type("foo") it "does not click when body is subject", -> bodyClicked = false cy.$$("body").on "click", -> bodyClicked = true cy.get("body").type("foo").then -> expect(bodyClicked).to.be.false describe "actionability", -> it "can forcibly click even when element is invisible", -> $txt = cy.$$(":text:first").hide() expect($txt).not.to.have.value("foo") clicked = false $txt.on "click", -> clicked = true cy.get(":text:first").type("foo", {force: true}).then ($input) -> expect(clicked).to.be.true expect($input).to.have.value("foo") it "can forcibly click even when being covered by another element", -> $input = $("<input />") .attr("id", "input-covered-in-span") .css({ width: 50 }) .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) clicked = false $input.on "click", -> clicked = true cy.get("#input-covered-in-span").type("foo", {force: true}).then ($input) -> expect(clicked).to.be.true expect($input).to.have.value("foo") it "waits until element becomes visible", -> $txt = cy.$$(":text:first").hide() retried = false cy.on "command:retry", _.after 3, -> $txt.show() retried = true cy.get(":text:first").type("foo").then -> expect(retried).to.be.true it "waits until element is no longer disabled", -> $txt = cy.$$(":text:first").prop("disabled", true) retried = false clicks = 0 $txt.on "click", -> clicks += 1 cy.on "command:retry", _.after 3, -> $txt.prop("disabled", false) retried = true cy.get(":text:first").type("foo").then -> expect(clicks).to.eq(1) expect(retried).to.be.true it "waits until element stops animating", -> retries = 0 cy.on "command:retry", (obj) -> retries += 1 cy.stub(cy, "ensureElementIsNotAnimating") .throws(new Error("animating!")) .onThirdCall().returns() cy.get(":text:first").type("foo").then -> ## - retry animation coords ## - retry animation ## - retry animation expect(retries).to.eq(3) expect(cy.ensureElementIsNotAnimating).to.be.calledThrice it "does not throw when waiting for animations is disabled", -> cy.stub(cy, "ensureElementIsNotAnimating").throws(new Error("animating!")) Cypress.config("waitForAnimations", false) cy.get(":text:first").type("foo").then -> expect(cy.ensureElementIsNotAnimating).not.to.be.called it "does not throw when turning off waitForAnimations in options", -> cy.stub(cy, "ensureElementIsNotAnimating").throws(new Error("animating!")) cy.get(":text:first").type("foo", {waitForAnimations: false}).then -> expect(cy.ensureElementIsNotAnimating).not.to.be.called it "passes options.animationDistanceThreshold to cy.ensureElementIsNotAnimating", -> $txt = cy.$$(":text:first") { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($txt) cy.spy(cy, "ensureElementIsNotAnimating") cy.get(":text:first").type("foo", {animationDistanceThreshold: 1000}).then -> args = cy.ensureElementIsNotAnimating.firstCall.args expect(args[1]).to.deep.eq([fromWindow, fromWindow]) expect(args[2]).to.eq(1000) it "passes config.animationDistanceThreshold to cy.ensureElementIsNotAnimating", -> animationDistanceThreshold = Cypress.config("animationDistanceThreshold") $txt = cy.$$(":text:first") { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($txt) cy.spy(cy, "ensureElementIsNotAnimating") cy.get(":text:first").type("foo").then -> args = cy.ensureElementIsNotAnimating.firstCall.args expect(args[1]).to.deep.eq([fromWindow, fromWindow]) expect(args[2]).to.eq(animationDistanceThreshold) describe "input types where no extra formatting required", -> _.each [ "<PASSWORD>" "email" "number" "search" "url" "tel" ], (type) -> it "accepts input [type=#{type}]", -> input = cy.$$("<input type='#{type}' id='input-type-#{type}' />") cy.$$("body").append(input) cy.get("#input-type-#{type}").type("1234").then ($input) -> expect($input).to.have.value "1234" expect($input.get(0)).to.eq $input.get(0) it "accepts type [type=#{type}], regardless of capitalization", -> input = cy.$$("<input type='#{type.toUpperCase()}' id='input-type-#{type}' />") cy.$$("body").append(input) cy.get("#input-type-#{type}").type("1234") describe "tabindex", -> beforeEach -> @$div = cy.$$("#tabindex") it "receives keydown, keyup, keypress", -> keydown = false keypress = false keyup = false @$div.keydown -> keydown = true @$div.keypress -> keypress = true @$div.keyup -> keyup = true cy.get("#tabindex").type("a").then -> expect(keydown).to.be.true expect(keypress).to.be.true expect(keyup).to.be.true it "does not receive textInput", -> textInput = false @$div.on "textInput", -> textInput = true cy.get("#tabindex").type("f").then -> expect(textInput).to.be.false it "does not receive input", -> input = false @$div.on "input", -> input = true cy.get("#tabindex").type("f").then -> expect(input).to.be.false it "does not receive change event", -> innerText = @$div.text() change = false @$div.on "change", -> change = true cy.get("#tabindex").type("foo{enter}").then ($el) -> expect(change).to.be.false expect($el.text()).to.eq(innerText) it "does not change inner text", -> innerText = @$div.text() cy.get("#tabindex").type("foo{leftarrow}{del}{rightarrow}{enter}").should("have.text", innerText) it "receives focus", -> focus = false @$div.focus -> focus = true cy.get("#tabindex").type("f").then -> expect(focus).to.be.true it "receives blur", -> blur = false @$div.blur -> blur = true cy .get("#tabindex").type("f") .get("input:first").focus().then -> expect(blur).to.be.true it "receives keydown and keyup for other special characters and keypress for enter and regular characters", -> keydowns = [] keyups = [] keypresses = [] @$div.keydown (e) -> keydowns.push(e) @$div.keypress (e) -> keypresses.push(e) @$div.keyup (e) -> keyups.push(e) cy .get("#tabindex").type("f{leftarrow}{rightarrow}{enter}") .then -> expect(keydowns).to.have.length(4) expect(keypresses).to.have.length(2) expect(keyups).to.have.length(4) describe "delay", -> it "adds delay to delta for each key sequence", -> cy.spy(cy, "timeout") cy .get(":text:first") .type("foo{enter}bar{leftarrow}", { delay: 5 }) .then -> expect(cy.timeout).to.be.calledWith(5 * 8, true, "type") it "can cancel additional keystrokes", (done) -> cy.stub(Cypress.runner, "stop") text = cy.$$(":text:first").keydown _.after 3, -> Cypress.stop() cy.on "stop", -> _.delay -> expect(text).to.have.value("foo") done() , 50 cy.get(":text:first").type("foo{enter}bar{leftarrow}") describe "events", -> it "receives keydown event", (done) -> $txt = cy.$$(":text:first") $txt.on "keydown", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 0 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 65 ## deprecated but fired by chrome always uppercase in the ASCII table layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keydown" view: cy.state("window") which: 65 ## deprecated but fired by chrome } done() cy.get(":text:first").type("a") it "receives keypress event", (done) -> $txt = cy.$$(":text:first") $txt.on "keypress", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 97 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 97 ## deprecated layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keypress" view: cy.state("window") which: 97 ## deprecated } done() cy.get(":text:first").type("a") it "receives keyup event", (done) -> $txt = cy.$$(":text:first") $txt.on "keyup", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 0 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 65 ## deprecated but fired by chrome always uppercase in the ASCII table layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keyup" view: cy.state("window") which: 65 ## deprecated but fired by chrome } done() cy.get(":text:first").type("a") it "receives textInput event", (done) -> $txt = cy.$$(":text:first") $txt.on "textInput", (e) => obj = _.pick e.originalEvent, "bubbles", "cancelable", "charCode", "data", "detail", "keyCode", "layerX", "layerY", "pageX", "pageY", "type", "view", "which" expect(obj).to.deep.eq { bubbles: true cancelable: true charCode: 0 data: "a" detail: 0 keyCode: 0 layerX: 0 layerY: 0 pageX: 0 pageY: 0 type: "textInput" view: cy.state("window") which: 0 } done() cy.get(":text:first").type("a") it "receives input event", (done) -> $txt = cy.$$(":text:first") $txt.on "input", (e) => obj = _.pick e.originalEvent, "bubbles", "cancelable", "type" expect(obj).to.deep.eq { bubbles: true cancelable: false type: "input" } done() cy.get(":text:first").type("a") it "fires events in the correct order" it "fires events for each key stroke" it "does fire input event when value changes", -> fired = false cy.$$(":text:first").on "input", -> fired = true fired = false cy.get(":text:first") .invoke("val", "bar") .type("{selectAll}{rightarrow}{backspace}") .then -> expect(fired).to.eq true fired = false cy.get(":text:first") .invoke("val", "bar") .type("{selectAll}{leftarrow}{del}") .then -> expect(fired).to.eq true cy.$$('[contenteditable]:first').on "input", () -> fired = true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{rightarrow}{backspace}') .then -> expect(fired).to.eq true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{leftarrow}{del}') .then -> expect(fired).to.eq true it "does not fire input event when value does not change", -> fired = false cy.$$(":text:first").on "input", (e) -> fired = true fired = false cy.get(":text:first") .invoke("val", "bar") .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get(":text:first") .invoke("val", "bar") .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false cy.$$("textarea:first").on "input", (e) -> fired = true fired = false cy.get("textarea:first") .invoke("val", "bar") .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get("textarea:first") .invoke("val", "bar") .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false cy.$$('[contenteditable]:first').on "input", () -> fired = true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false describe "maxlength", -> it "limits text entered to the maxlength attribute of a text input", -> $input = cy.$$(":text:first") $input.attr("maxlength", 5) cy.get(":text:first") .type("1234567890") .then (input) -> expect(input).to.have.value("12345") it "ignores an invalid maxlength attribute", -> $input = cy.$$(":text:first") $input.attr("maxlength", "five") cy.get(":text:first") .type("1234567890") .then (input) -> expect(input).to.have.value("1234567890") it "handles special characters", -> $input = cy.$$(":text:first") $input.attr("maxlength", 5) cy.get(":text:first") .type("12{selectall}") .then (input) -> expect(input).to.have.value("12") it "maxlength=0 events", -> events = [] push = (evt) -> return -> events.push(evt) cy .$$(":text:first") .attr("maxlength", 0) .on("keydown", push("keydown")) .on("keypress", push("keypress")) .on("textInput", push("textInput")) .on("input", push("input")) .on("keyup", push("keyup")) cy.get(":text:first") .type("1") .then -> expect(events).to.deep.eq([ "keydown", "keypress", "textInput", "keyup" ]) it "maxlength=1 events", -> events = [] push = (evt) -> return -> events.push(evt) cy .$$(":text:first") .attr("maxlength", 1) .on("keydown", push("keydown")) .on("keypress", push("keypress")) .on("textInput", push("textInput")) .on("input", push("input")) .on("keyup", push("keyup")) cy.get(":text:first") .type("12") .then -> expect(events).to.deep.eq([ "keydown", "keypress", "textInput", "input", "keyup" "keydown", "keypress", "textInput", "keyup" ]) describe "value changing", -> it "changes the elements value", -> cy.get("#input-without-value").type("a").then ($text) -> expect($text).to.have.value("a") it "changes the elements value for multiple keys", -> cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("foo") it "inserts text after existing text", -> cy.get("#input-with-value").type(" bar").then ($text) -> expect($text).to.have.value("foo bar") it "inserts text after existing text input by invoking val", -> cy.get("#input-without-value").invoke("val", "foo").type(" bar").then ($text) -> expect($text).to.have.value("foo bar") it "overwrites text when currently has selection", -> cy.get("#input-without-value").invoke('val', '0').then (el) -> el.select() cy.get("#input-without-value").type("50").then ($input) -> expect($input).to.have.value("50") it "overwrites text when selectAll in click handler", -> cy.$$("#input-without-value").val("0").click -> $(@).select() it "overwrites text when selectAll in mouseup handler", -> cy.$$("#input-without-value").val("0").mouseup -> $(@).select() it "overwrites text when selectAll in mouseup handler", -> cy.$$("#input-without-value").val("0").mouseup -> $(@).select() it "responsive to keydown handler", -> cy.$$("#input-without-value").val("1234").keydown -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("651234") it "responsive to keyup handler", -> cy.$$("#input-without-value").val("1234").keyup -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("612345") it "responsive to input handler", -> cy.$$("#input-without-value").val("1234").keyup -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("612345") it "responsive to change handler", -> cy.$$("#input-without-value").val("1234").change -> $(@).get(0).setSelectionRange(0,0) ## no change event should be fired cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("123456") it "automatically moves the caret to the end if value is changed manually", -> cy.$$("#input-without-value").keypress (e) -> e.preventDefault() key = String.fromCharCode(e.which) $input = $(e.target) val = $input.val() ## setting value updates cursor to the end of input $input.val(val + key + "-") cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("f-o-o-") it "automatically moves the caret to the end if value is changed manually asynchronously", -> cy.$$("#input-without-value").keypress (e) -> key = String.fromCharCode(e.which) $input = $(e.target) _.defer -> val = $input.val() $input.val(val + "-") cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("f-o-o-") it "does not fire keypress when keydown is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> done("should not have received keypress event") cy.$$("#input-without-value").get(0).addEventListener "keydown", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "does not insert key when keydown is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "keydown", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not insert key when keypress is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not fire textInput when keypress is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> done("should not have received textInput event") cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "does not insert key when textInput is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not fire input when textInput is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "input", (e) -> done("should not have received input event") cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "preventing default to input event should not affect anything", -> cy.$$("#input-without-value").get(0).addEventListener "input", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("foo") describe "input[type=number]", -> it "can change values", -> cy.get("#number-without-value").type("42").then ($text) -> expect($text).to.have.value("42") it "can input decimal", -> cy.get("#number-without-value").type("2.0").then ($input) -> expect($input).to.have.value("2.0") it "can utilize {selectall}", -> cy.get("#number-with-value").type("{selectall}99").then ($input) -> expect($input).to.have.value("99") it "can utilize arrows", -> cy.get("#number-with-value").type("{leftarrow}{leftarrow}{rightarrow}9").then ($input) -> expect($input).to.have.value("192") it "inserts text after existing text ", -> cy.get("#number-with-value").type("34").then ($text) -> expect($text).to.have.value("1234") it "inserts text after existing text input by invoking val", -> cy.get("#number-without-value").invoke("val", "12").type("34").then ($text) -> expect($text).to.have.value("1234") it "overwrites text on input[type=number] when input has existing text selected", -> cy.get("#number-without-value").invoke('val', "0").then (el) -> el.get(0).select() cy.get("#number-without-value").type("50").then ($input) -> expect($input).to.have.value("50") it "can type negative numbers", -> cy.get('#number-without-value') .type('-123.12') .should('have.value', '-123.12') it "type=number blurs consistently", -> blurred = 0 cy.$$("#number-without-value").blur -> blurred++ cy.get("#number-without-value") .type('200').blur() .then -> expect(blurred).to.eq 1 describe "input[type=email]", -> it "can change values", -> cy.get("#email-without-value").type("<EMAIL>").then ($text) -> expect($text).to.have.value("<EMAIL>") it "can utilize {selectall}", -> cy.get("#email-with-value").type("{selectall}<EMAIL>").then ($text) -> expect($text).to.have.value("<EMAIL>") it "can utilize arrows", -> cy.get("#email-with-value").type("{leftarrow}{rightarrow}om").then ($text) -> expect($text).to.have.value("<EMAIL>") it "inserts text after existing text", -> cy.get("#email-with-value").type("om").then ($text) -> expect($text).to.have.value("<EMAIL>") it "inserts text after existing text input by invoking val", -> cy.get("#email-without-value").invoke("val", "<EMAIL>").type("om").then ($text) -> expect($text).to.have.value("<EMAIL>") it "overwrites text when input has existing text selected", -> cy.get("#email-without-value").invoke('val', "<EMAIL>").invoke('select') cy.get("#email-without-value").type("<EMAIL>").then ($input) -> expect($input).to.have.value("<EMAIL>") it "type=email blurs consistently", -> blurred = 0 cy.$$("#email-without-value").blur -> blurred++ cy.get("#email-without-value") .type('<EMAIL>').blur() .then -> expect(blurred).to.eq 1 describe "input[type=password]", -> it "can change values", -> cy.get("#password-without-value").type("password").then ($text) -> expect($text).to.have.value("password") it "inserts text after existing text", -> cy.get("#password-with-value").type("word").then ($text) -> expect($text).to.have.value("password") it "inserts text after existing text input by invoking val", -> cy.get("#password-without-value").invoke("val", "secr").type("et").then ($text) -> expect($text).to.have.value("secret") it "overwrites text when input has existing text selected", -> cy.get("#password-without-value").invoke('val', "secret").invoke('select') cy.get("#password-without-value").type("agent").then ($input) -> expect($input).to.have.value("agent") it "overwrites text when input has selected range of text in click handler", -> cy.$$("#input-with-value").mouseup (e) -> # e.preventDefault() e.target.setSelectionRange(1, 1) select = (e) -> e.target.select() cy .$$("#password-without-value") .val("secret") .click(select) .keyup (e) -> switch e.key when "g" select(e) when "n" e.target.setSelectionRange(0, 1) cy.get("#password-without-value").type("agent").then ($input) -> expect($input).to.have.value("tn") describe "input[type=date]", -> it "can change values", -> cy.get("#date-without-value").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") it "overwrites existing value", -> cy.get("#date-with-value").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") it "overwrites existing value input by invoking val", -> cy.get("#date-without-value").invoke("val", "2016-01-01").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") describe "input[type=month]", -> it "can change values", -> cy.get("#month-without-value").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") it "overwrites existing value", -> cy.get("#month-with-value").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") it "overwrites existing value input by invoking val", -> cy.get("#month-without-value").invoke("val", "2016-01").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") describe "input[type=week]", -> it "can change values", -> cy.get("#week-without-value").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") it "overwrites existing value", -> cy.get("#week-with-value").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") it "overwrites existing value input by invoking val", -> cy.get("#week-without-value").invoke("val", "2016-W01").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") describe "input[type=time]", -> it "can change values", -> cy.get("#time-without-value").type("01:23:45").then ($text) -> expect($text).to.have.value("01:23:45") it "overwrites existing value", -> cy.get("#time-with-value").type("12:34:56").then ($text) -> expect($text).to.have.value("12:34:56") it "overwrites existing value input by invoking val", -> cy.get("#time-without-value").invoke("val", "01:23:45").type("12:34:56").then ($text) -> expect($text).to.have.value("12:34:56") it "can be formatted HH:mm", -> cy.get("#time-without-value").type("01:23").then ($text) -> expect($text).to.have.value("01:23") it "can be formatted HH:mm:ss", -> cy.get("#time-without-value").type("01:23:45").then ($text) -> expect($text).to.have.value("01:23:45") it "can be formatted HH:mm:ss.S", -> cy.get("#time-without-value").type("01:23:45.9").then ($text) -> expect($text).to.have.value("01:23:45.9") it "can be formatted HH:mm:ss.SS", -> cy.get("#time-without-value").type("01:23:45.99").then ($text) -> expect($text).to.have.value("01:23:45.99") it "can be formatted HH:mm:ss.SSS", -> cy.get("#time-without-value").type("01:23:45.999").then ($text) -> expect($text).to.have.value("01:23:45.999") describe "[contenteditable]", -> it "can change values", -> cy.get("#input-types [contenteditable]").type("foo").then ($div) -> expect($div).to.have.text("foo") it "inserts text after existing text", -> cy.get("#input-types [contenteditable]").invoke("text", "foo").type(" bar").then ($text) -> expect($text).to.have.text("foo bar") it "can type into [contenteditable] with existing <div>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>foo</div>' cy.get("[contenteditable]:first") .type("bar").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n") expect($div.get(0).textContent).to.eql("foobar") expect($div.get(0).innerHTML).to.eql("<div>foobar</div>") it "can type into [contenteditable] with existing <p>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<p>foo</p>' cy.get("[contenteditable]:first") .type("bar").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n\n") expect($div.get(0).textContent).to.eql("foobar") expect($div.get(0).innerHTML).to.eql("<p>foobar</p>") it "collapses selection to start on {leftarrow}", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>bar</div>' cy.get("[contenteditable]:first") .type("{selectall}{leftarrow}foo").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n") it "collapses selection to end on {rightarrow}", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>bar</div>' cy.get("[contenteditable]:first") .type("{selectall}{leftarrow}foo{selectall}{rightarrow}baz").then ($div) -> expect($div.get(0).innerText).to.eql("foobarbaz\n") it "can remove a placeholder <br>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div><br></div>' cy.get("[contenteditable]:first") .type("foobar").then ($div) -> expect($div.get(0).innerHTML).to.eql("<div>foobar</div>") it "can type into an iframe with designmode = 'on'", -> ## append a new iframe to the body cy.$$('<iframe id="generic-iframe" src="/fixtures/generic.html" style="height: 500px"></iframe>') .appendTo cy.$$('body') ## wait for iframe to load loaded = false cy.get('#generic-iframe') .then ($iframe) -> $iframe.load -> loaded = true .scrollIntoView() .should -> expect(loaded).to.eq true ## type text into iframe cy.get('#generic-iframe') .then ($iframe) -> $iframe[0].contentDocument.designMode = 'on' iframe = $iframe.contents() cy.wrap(iframe.find('html')).first() .type('{selectall}{del} foo bar baz{enter}ac{leftarrow}b') # assert that text was typed cy.get('#generic-iframe') .then ($iframe) -> iframeText = $iframe[0].contentDocument.body.innerText expect(iframeText).to.include('foo bar baz\nabc') ## TODO: fix this with 4.0 updates describe.skip "element reference loss", -> it 'follows the focus of the cursor', -> charCount = 0 cy.$$('input:first').keydown -> if charCount is 3 cy.$$('input').eq(1).focus() charCount++ cy.get('input:first').type('foobar').then -> cy.get('input:first').should('have.value', 'foo') cy.get('input').eq(1).should('have.value', 'bar') describe "specialChars", -> context "{{}", -> it "sets which and keyCode to 219", (done) -> cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 219 expect(e.keyCode).to.eq 219 done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires keypress event with 123 charCode", (done) -> cy.$$(":text:first").on "keypress", (e) -> expect(e.charCode).to.eq 123 expect(e.which).to.eq 123 expect(e.keyCode).to.eq 123 done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires textInput event with e.data", (done) -> cy.$$(":text:first").on "textInput", (e) -> expect(e.originalEvent.data).to.eq "{" done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires input event", (done) -> cy.$$(":text:first").on "input", (e) -> done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "can prevent default character insertion", -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 219 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{{}").then ($input) -> expect($input).to.have.value("foo") context "{esc}", -> it "sets which and keyCode to 27 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 27 expect(e.keyCode).to.eq 27 expect(e.key).to.eq "Escape" done() cy.get(":text:first").invoke("val", "ab").type("{esc}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{esc}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{esc}").then -> done() it "can prevent default esc movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 27 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("d{esc}").then ($input) -> expect($input).to.have.value("food") done() context "{backspace}", -> it "backspaces character to the left", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{backspace}u").then ($input) -> expect($input).to.have.value("bur") it "can backspace a selection range of characters", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'ar' characters $input.get(0).setSelectionRange(1,3) .get(":text:first").type("{backspace}").then ($input) -> expect($input).to.have.value("b") it "sets which and keyCode to 8 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 8 expect(e.keyCode).to.eq 8 expect(e.key).to.eq "Backspace" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}{backspace}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{backspace}").then -> done() it "can prevent default backspace movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 8 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{backspace}").then ($input) -> expect($input).to.have.value("foo") done() context "{del}", -> it "deletes character to the right", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{del}").then ($input) -> expect($input).to.have.value("ba") it "can delete a selection range of characters", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'ar' characters $input.get(0).setSelectionRange(1,3) .get(":text:first").type("{del}").then ($input) -> expect($input).to.have.value("b") it "sets which and keyCode to 46 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 46 expect(e.keyCode).to.eq 46 expect(e.key).to.eq "Delete" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}{del}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{del}").then -> done() it "does fire input event when value changes", (done) -> cy.$$(":text:first").on "input", (e) -> done() cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' characters $input.get(0).setSelectionRange(0,1) .get(":text:first").type("{del}") it "does not fire input event when value does not change", (done) -> cy.$$(":text:first").on "input", (e) -> done("should not have fired input") cy.get(":text:first").invoke("val", "ab").type("{del}").then -> done() it "can prevent default del movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 46 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{del}").then ($input) -> expect($input).to.have.value("foo") done() context "{leftarrow}", -> it "can move the cursor from the end to end - 1", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("banr") it "does not move the cursor if already at bounds 0", -> cy.get(":text:first").invoke("val", "bar").type("{selectall}{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets the cursor to the left bounds", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(1,2) .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("bnar") it "sets the cursor to the very beginning", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(0,1) .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets which and keyCode to 37 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 37 expect(e.keyCode).to.eq 37 expect(e.key).to.eq "ArrowLeft" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then -> done() it "can prevent default left arrow movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 37 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}d").then ($input) -> expect($input).to.have.value("food") done() context "{rightarrow}", -> it "can move the cursor from the beginning to beginning + 1", -> cy.get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the beginning $input.get(0).setSelectionRange(0,0) .get(":text:first").type("{rightarrow}n").then ($input) -> expect($input).to.have.value("bnar") it "does not move the cursor if already at end of bounds", -> cy.get(":text:first").invoke("val", "bar").type("{selectall}{rightarrow}n").then ($input) -> expect($input).to.have.value("barn") it "sets the cursor to the rights bounds", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(1,2) .get(":text:first").type("{rightarrow}n").then ($input) -> expect($input).to.have.value("banr") it "sets the cursor to the very beginning", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> $input.select() .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets which and keyCode to 39 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 39 expect(e.keyCode).to.eq 39 expect(e.key).to.eq "ArrowRight" done() cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then -> done() it "can prevent default right arrow movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 39 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{rightarrow}d").then ($input) -> expect($input).to.have.value("fodo") done() context "{uparrow}", -> beforeEach -> cy.$$("#comments").val("foo\nbar\nbaz") it "sets which and keyCode to 38 and does not fire keypress events", (done) -> cy.$$("#comments").on "keypress", -> done("should not have received keypress") cy.$$("#comments").on "keydown", (e) -> expect(e.which).to.eq 38 expect(e.keyCode).to.eq 38 expect(e.key).to.eq "ArrowUp" done() cy.get("#comments").type("{uparrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$("#comments").on "textInput", (e) -> done("textInput should not have fired") cy.get("#comments").type("{uparrow}").then -> done() it "does not fire input event", (done) -> cy.$$("#comments").on "input", (e) -> done("input should not have fired") cy.get("#comments").type("{uparrow}").then -> done() it "up and down arrow on contenteditable", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' cy.get("[contenteditable]:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33").then ($div) -> expect($div.get(0).innerText).to.eql("foo22\nb11ar\nbaz33\n") it "uparrow ignores current selection", -> ce = cy.$$('[contenteditable]:first').get(0) ce.innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' ## select 'bar' line = cy.$$('[contenteditable]:first div:nth-child(1)').get(0) cy.document().then (doc) -> ce.focus() doc.getSelection().selectAllChildren(line) cy.get("[contenteditable]:first") .type("{uparrow}11").then ($div) -> expect($div.get(0).innerText).to.eql("11foo\nbar\nbaz\n") it "up and down arrow on textarea", -> cy.$$('textarea:first').get(0).value = 'foo\nbar\nbaz' cy.get("textarea:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33").should('have.value', "foo22\nb11ar\nbaz33") it "increments input[type=number]", -> cy.get('input[type="number"]:first') .invoke('val', '12.34') .type('{uparrow}{uparrow}') .should('have.value', '14') context "{downarrow}", -> beforeEach -> cy.$$("#comments").val("foo\nbar\nbaz") it "sets which and keyCode to 40 and does not fire keypress events", (done) -> cy.$$("#comments").on "keypress", -> done("should not have received keypress") cy.$$("#comments").on "keydown", (e) -> expect(e.which).to.eq 40 expect(e.keyCode).to.eq 40 expect(e.key).to.eq "ArrowDown" done() cy.get("#comments").type("{downarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$("#comments").on "textInput", (e) -> done("textInput should not have fired") cy.get("#comments").type("{downarrow}").then -> done() it "does not fire input event", (done) -> cy.$$("#comments").on "input", (e) -> done("input should not have fired") cy.get("#comments").type("{downarrow}").then -> done() it "{downarrow} will move to EOL on textarea", -> cy.$$('textarea:first').get(0).value = 'foo\nbar\nbaz' cy.get("textarea:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33{leftarrow}{downarrow}44").should('have.value', "foo22\nb11ar\nbaz3344") it "decrements input[type='number']", -> cy.get('input[type="number"]:first') .invoke('val', '12.34') .type('{downarrow}{downarrow}') .should('have.value', '11') it "downarrow ignores current selection", -> ce = cy.$$('[contenteditable]:first').get(0) ce.innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' ## select 'foo' line = cy.$$('[contenteditable]:first div:first').get(0) cy.document().then (doc) -> ce.focus() doc.getSelection().selectAllChildren(line) cy.get("[contenteditable]:first") .type("{downarrow}22").then ($div) -> expect($div.get(0).innerText).to.eql("foo\n22bar\nbaz\n") context "{selectall}{del}", -> it "can select all the text and delete", -> cy.get(":text:first").invoke("val", "1234").type("{selectall}{del}").type("foo").then ($text) -> expect($text).to.have.value("foo") it "can select all [contenteditable] and delete", -> cy.get("#input-types [contenteditable]").invoke("text", "1234").type("{selectall}{del}").type("foo").then ($div) -> expect($div).to.have.text("foo") context "{selectall} then type something", -> it "replaces the text", -> cy.get("#input-with-value").type("{selectall}new").then ($text) -> expect($text).to.have.value("new") context "{enter}", -> it "sets which and keyCode to 13 and prevents EOL insertion", (done) -> cy.$$("#input-types textarea").on "keypress", _.after 2, (e) -> done("should not have received keypress event") cy.$$("#input-types textarea").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 13 expect(e.keyCode).to.eq 13 expect(e.key).to.eq "Enter" e.preventDefault() cy.get("#input-types textarea").invoke("val", "foo").type("d{enter}").then ($textarea) -> expect($textarea).to.have.value("food") done() it "sets which and keyCode and charCode to 13 and prevents EOL insertion", (done) -> cy.$$("#input-types textarea").on "keypress", _.after 2, (e) -> expect(e.which).to.eq 13 expect(e.keyCode).to.eq 13 expect(e.charCode).to.eq 13 expect(e.key).to.eq "Enter" e.preventDefault() cy.get("#input-types textarea").invoke("val", "foo").type("d{enter}").then ($textarea) -> expect($textarea).to.have.value("food") done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{enter}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{enter}").then -> done() it "inserts new line into textarea", -> cy.get("#input-types textarea").invoke("val", "foo").type("bar{enter}baz{enter}quux").then ($textarea) -> expect($textarea).to.have.value("foobar\nbaz\nquux") it "inserts new line into [contenteditable] ", -> cy.get("#input-types [contenteditable]:first").invoke("text", "foo") .type("bar{enter}baz{enter}{enter}{enter}quux").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\nbaz\n\n\nquux\n") expect($div.get(0).textContent).to.eql("foobarbazquux") expect($div.get(0).innerHTML).to.eql("foobar<div>baz</div><div><br></div><div><br></div><div>quux</div>") it "inserts new line into [contenteditable] from midline", -> cy.get("#input-types [contenteditable]:first").invoke("text", "foo") .type("bar{leftarrow}{enter}baz{leftarrow}{enter}quux").then ($div) -> expect($div.get(0).innerText).to.eql("fooba\nba\nquuxzr\n") expect($div.get(0).textContent).to.eql("foobabaquuxzr") expect($div.get(0).innerHTML).to.eql("fooba<div>ba</div><div>quuxzr</div>") describe "modifiers", -> describe "activating modifiers", -> it "sends keydown event for modifiers in order", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy.get("input:text:first").type("{shift}{ctrl}").then -> expect(events[0].shiftKey).to.be.true expect(events[0].which).to.equal(16) expect(events[1].ctrlKey).to.be.true expect(events[1].which).to.equal(17) $input.off("keydown") done() it "maintains modifiers for subsequent characters", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy.get("input:text:first").type("{command}{control}ok").then -> expect(events[2].metaKey).to.be.true expect(events[2].ctrlKey).to.be.true expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.true expect(events[3].ctrlKey).to.be.true expect(events[3].which).to.equal(75) $input.off("keydown") done() it "does not maintain modifiers for subsequent type commands", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy .get("input:text:first") .type("{command}{control}") .type("ok") .then -> expect(events[2].metaKey).to.be.false expect(events[2].ctrlKey).to.be.false expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.false expect(events[3].ctrlKey).to.be.false expect(events[3].which).to.equal(75) $input.off("keydown") done() it "does not maintain modifiers for subsequent click commands", (done) -> $button = cy.$$("button:first") mouseDownEvent = null mouseUpEvent = null clickEvent = null $button.on "mousedown", (e)-> mouseDownEvent = e $button.on "mouseup", (e)-> mouseUpEvent = e $button.on "click", (e)-> clickEvent = e cy .get("input:text:first") .type("{cmd}{option}") .get("button:first").click().then -> expect(mouseDownEvent.metaKey).to.be.false expect(mouseDownEvent.altKey).to.be.false expect(mouseUpEvent.metaKey).to.be.false expect(mouseUpEvent.altKey).to.be.false expect(clickEvent.metaKey).to.be.false expect(clickEvent.altKey).to.be.false $button.off "mousedown" $button.off "mouseup" $button.off "click" done() it "sends keyup event for activated modifiers when typing is finished", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keyup", (e) -> events.push(e) cy .get("input:text:first") .type("{alt}{ctrl}{meta}{shift}ok") .then -> # first keyups should be for the chars typed, "ok" expect(events[0].which).to.equal(79) expect(events[1].which).to.equal(75) expect(events[2].which).to.equal(18) expect(events[3].which).to.equal(17) expect(events[4].which).to.equal(91) expect(events[5].which).to.equal(16) $input.off("keyup") done() describe "release: false", -> it "maintains modifiers for subsequent type commands", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy .get("input:text:first") .type("{command}{control}", { release: false }) .type("ok") .then -> expect(events[2].metaKey).to.be.true expect(events[2].ctrlKey).to.be.true expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.true expect(events[3].ctrlKey).to.be.true expect(events[3].which).to.equal(75) done() it "maintains modifiers for subsequent click commands", (done) -> $button = cy.$$("button:first") mouseDownEvent = null mouseUpEvent = null clickEvent = null $button.on "mousedown", (e) -> mouseDownEvent = e $button.on "mouseup", (e) -> mouseUpEvent = e $button.on "click", (e) -> clickEvent = e cy .get("input:text:first") .type("{meta}{alt}", { release: false }) .get("button:first").click().then -> expect(mouseDownEvent.metaKey).to.be.true expect(mouseDownEvent.altKey).to.be.true expect(mouseUpEvent.metaKey).to.be.true expect(mouseUpEvent.altKey).to.be.true expect(clickEvent.metaKey).to.be.true expect(clickEvent.altKey).to.be.true done() it "resets modifiers before next test", -> ## this test will fail if you comment out ## $Keyboard.resetModifiers $input = cy.$$("input:text:first") events = [] $input.on "keyup", (e) -> events.push(e) cy .get("input:text:first") .type("a", { release: false }) .then -> expect(events[0].metaKey).to.be.false expect(events[0].ctrlKey).to.be.false expect(events[0].altKey).to.be.false describe "changing modifiers", -> beforeEach -> @$input = cy.$$("input:text:first") cy.get("input:text:first").type("{command}{option}", { release: false }) afterEach -> @$input.off("keydown") it "sends keydown event for new modifiers", (done) -> event = null @$input.on "keydown", (e)-> event = e cy.get("input:text:first").type("{shift}").then -> expect(event.shiftKey).to.be.true expect(event.which).to.equal(16) done() it "does not send keydown event for already activated modifiers", (done) -> triggered = false @$input.on "keydown", (e)-> triggered = true if e.which is 18 or e.which is 17 cy.get("input:text:first").type("{cmd}{alt}").then -> expect(triggered).to.be.false done() describe "case-insensitivity", -> it "special chars are case-insensitive", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{DeL}").then ($input) -> expect($input).to.have.value("ba") it "modifiers are case-insensitive", (done) -> $input = cy.$$("input:text:first") alt = false $input.on "keydown", (e) -> alt = true if e.altKey cy.get("input:text:first").type("{aLt}").then -> expect(alt).to.be.true $input.off("keydown") done() it "letters are case-sensitive", -> cy.get("input:text:first").type("FoO").then ($input) -> expect($input).to.have.value("FoO") describe "click events", -> it "passes timeout and interval down to click", (done) -> input = $("<input />").attr("id", "input-covered-in-span").prependTo(cy.$$("body")) span = $("<span>span on input</span>") .css { position: "absolute" left: input.offset().left top: input.offset().top padding: 5 display: "inline-block" backgroundColor: "yellow" } .prependTo cy.$$("body") cy.on "command:retry", (options) -> expect(options.timeout).to.eq 1000 expect(options.interval).to.eq 60 done() cy.get("#input-covered-in-span").type("foobar", {timeout: 1000, interval: 60}) it "does not issue another click event between type/type", -> clicked = 0 cy.$$(":text:first").click -> clicked += 1 cy.get(":text:first").type("f").type("o").then -> expect(clicked).to.eq 1 it "does not issue another click event if element is already in focus from click", -> clicked = 0 cy.$$(":text:first").click -> clicked += 1 cy.get(":text:first").click().type("o").then -> expect(clicked).to.eq 1 describe "change events", -> it "fires when enter is pressed and value has changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("bar{enter}").then -> expect(changed).to.eq 1 it "fires twice when enter is pressed and then again after losing focus", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("bar{enter}baz").blur().then -> expect(changed).to.eq 2 it "fires when element loses focus due to another action (click)", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 .get("button:first").click().then -> expect(changed).to.eq 1 it "fires when element loses focus due to another action (type)", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 .get("textarea:first").type("bar").then -> expect(changed).to.eq 1 it "fires when element is directly blurred", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").blur().then -> expect(changed).to.eq 1 it "fires when element is tabbed away from"#, -> # changed = 0 # cy.$$(":text:first").change -> # changed += 1 # cy.get(":text:first").invoke("val", "foo").type("b{tab}").then -> # expect(changed).to.eq 1 it "does not fire twice if element is already in focus between type/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("f").type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between clear/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").clear().type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between click/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").click().type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between type/click", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("d{enter}").click().then -> expect(changed).to.eq 1 it "does not fire at all between clear/type/click", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").clear().type("o").click().then ($el) -> expect(changed).to.eq 0 $el .blur() .then -> expect(changed).to.eq 1 it "does not fire if {enter} is preventedDefault", -> changed = 0 cy.$$(":text:first").keypress (e) -> e.preventDefault() if e.which is 13 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("b{enter}").then -> expect(changed).to.eq 0 it "does not fire when enter is pressed and value hasnt changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("b{backspace}{enter}").then -> expect(changed).to.eq 0 it "does not fire at the end of the type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 it "does not fire change event if value hasnt actually changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").invoke("val", "foo").type("{backspace}{backspace}oo{enter}").blur().then -> expect(changed).to.eq 0 it "does not fire if mousedown is preventedDefault which prevents element from losing focus", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.$$("textarea:first").mousedown -> return false cy .get(":text:first").invoke("val", "foo").type("bar") .get("textarea:first").click().then -> expect(changed).to.eq 0 it "does not fire hitting {enter} inside of a textarea", -> changed = 0 cy.$$("textarea:first").change -> changed += 1 cy .get("textarea:first").type("foo{enter}bar").then -> expect(changed).to.eq 0 it "does not fire hitting {enter} inside of [contenteditable]", -> changed = 0 cy.$$("[contenteditable]:first").change -> changed += 1 cy .get("[contenteditable]:first").type("foo{enter}bar").then -> expect(changed).to.eq 0 ## [contenteditable] does not fire ANY change events ever. it "does not fire at ALL for [contenteditable]", -> changed = 0 cy.$$("[contenteditable]:first").change -> changed += 1 cy .get("[contenteditable]:first").type("foo") .get("button:first").click().then -> expect(changed).to.eq 0 it "does not fire on .clear() without blur", -> changed = 0 cy.$$("input:first").change -> changed += 1 cy.get("input:first").invoke('val', 'foo') .clear() .then ($el) -> expect(changed).to.eq 0 $el .type('foo') .blur() .then -> expect(changed).to.eq 0 it "fires change for single value change inputs", -> changed = 0 cy.$$('input[type="date"]:first').change -> changed++ cy.get('input[type="date"]:first') .type("1959-09-13") .blur() .then -> expect(changed).to.eql 1 it "does not fire change for non-change single value input", -> changed = 0 cy.$$('input[type="date"]:first').change -> changed++ cy.get('input[type="date"]:first') .invoke('val', "1959-09-13") .type("1959-09-13") .blur() .then -> expect(changed).to.eql(0) it "does not fire change for type'd change that restores value", -> changed = 0 cy.$$('input:first').change -> changed++ cy.get('input:first') .invoke('val', 'foo') .type('{backspace}o') .invoke('val', 'bar') .type('{backspace}r') .blur() .then -> expect(changed).to.eql 0 describe "caret position", -> it "respects being formatted by input event handlers" it "can arrow from maxlength", -> cy.get('input:first').invoke('attr', 'maxlength', "5").type('foobar{leftarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:4, end:4}) it "won't arrowright past length", -> cy.get('input:first').type('foo{rightarrow}{rightarrow}{rightarrow}bar{rightarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:6, end:6}) it "won't arrowleft before word", -> cy.get('input:first').type('oo' + '{leftarrow}{leftarrow}{leftarrow}' + 'f' + '{leftarrow}'.repeat(5)) cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:0, end:0}) it "leaves caret at the end of contenteditable", -> cy.get('[contenteditable]:first').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:6, end:6}) it "leaves caret at the end of contenteditable when prefilled", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'foo' cy.get('[contenteditable]:first').type('bar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:6, end:6}) it "can move the caret left on contenteditable", -> cy.get('[contenteditable]:first').type('foo{leftarrow}{leftarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:1, end:1}) ##make sure caret is correct ## type left left ## make sure caret correct ## text is fboo ## fix input-mask issue it "leaves caret at the end of input", -> cy.get(':text:first').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$(':text:first').get(0) .to.deep.eq({start:6, end:6}) it "leaves caret at the end of textarea", -> cy.get('#comments').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('#comments').get(0) .to.deep.eq({start:6, end:6}) it "can wrap cursor to next line in [contenteditable] with {rightarrow}", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'start'+ '<div>middle</div>'+ '<div>end</div>' cy.get('[contenteditable]:first') ## move cursor to beginning of div .type('{selectall}{leftarrow}') .type('{rightarrow}'.repeat(14)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('start\nmiddle\ne[_I_]nd\n') it "can wrap cursor to prev line in [contenteditable] with {leftarrow}", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'start'+ '<div>middle</div>'+ '<div>end</div>' cy.get('[contenteditable]:first').type('{leftarrow}'.repeat(12)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('star[_I_]t\nmiddle\nend\n') it "can wrap cursor to next line in [contenteditable] with {rightarrow} and empty lines", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = '<div><br></div>'.repeat(4)+ '<div>end</div>' cy.get('[contenteditable]:first') .type('{selectall}{leftarrow}') # .type('foobar'+'{rightarrow}'.repeat(6)+'[_I_]').then -> # expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('foobar\n\n\n\nen[_I_]d\n') it "can use {rightarrow} and nested elements", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = '<div><b>s</b>ta<b>rt</b></div>' cy.get('[contenteditable]:first') .type('{selectall}{leftarrow}') .type('{rightarrow}'.repeat(3)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('sta[_I_]rt\n') it "enter and \\n should act the same for [contenteditable]", -> cleanseText = (text) -> text.replace(/ /g, ' ') expectMatchInnerText = ($el , innerText) -> expect(cleanseText($el.get(0).innerText)).to.eql(innerText) ## NOTE: this may only pass in Chrome since the whitespace may be different in other browsers ## even if actual and expected appear the same. expected = "{\n foo: 1\n bar: 2\n baz: 3\n}\n" cy.get('[contenteditable]:first') .invoke('html', '<div><br></div>') .type('{{}{enter} foo: 1{enter} bar: 2{enter} baz: 3{enter}}') .should ($el) -> expectMatchInnerText($el, expected) .clear() .type('{{}\n foo: 1\n bar: 2\n baz: 3\n}') .should ($el) -> expectMatchInnerText($el, expected) it "enter and \\n should act the same for textarea", -> expected = "{\n foo: 1\n bar: 2\n baz: 3\n}" cy.get('textarea:first') .clear() .type('{{}{enter} foo: 1{enter} bar: 2{enter} baz: 3{enter}}') .should('have.prop', 'value', expected) .clear() .type('{{}\n foo: 1\n bar: 2\n baz: 3\n}') .should('have.prop', 'value', expected) describe "{enter}", -> beforeEach -> @$forms = cy.$$("#form-submits") context "1 input, no 'submit' elements", -> it "triggers form submit", (done) -> @foo = {} @$forms.find("#single-input").submit (e) -> e.preventDefault() done() cy.get("#single-input input").type("foo{enter}") it "triggers form submit synchronously before type logs or resolves", -> events = [] cy.on "command:start", (cmd) -> events.push "#{cmd.get('name')}:start" @$forms.find("#single-input").submit (e) -> e.preventDefault() events.push "submit" cy.on "log:added", (attrs, log) -> state = log.get("state") if state is "pending" log.on "state:changed", (state) -> events.push "#{log.get('name')}:log:#{state}" events.push "#{log.get('name')}:log:#{state}" cy.on "command:end", (cmd) -> events.push "#{cmd.get('name')}:end" cy.get("#single-input input").type("f{enter}").then -> expect(events).to.deep.eq [ "get:start", "get:log:pending", "get:end", "type:start", "type:log:pending", "submit", "type:end", "then:start" ] it "triggers 2 form submit event", -> submits = 0 @$forms.find("#single-input").submit (e) -> e.preventDefault() submits += 1 cy.get("#single-input input").type("f{enter}{enter}").then -> expect(submits).to.eq 2 it "does not submit when keydown is defaultPrevented on input", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("input").keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keydown is defaultPrevented on wrapper", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("div").keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keydown is defaultPrevented on form", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on input", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on wrapper", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("div").keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on form", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() context "2 inputs, no 'submit' elements", -> it "does not trigger submit event", (done) -> form = @$forms.find("#no-buttons").submit -> done("err: should not have submitted") cy.get("#no-buttons input:first").type("f").type("{enter}").then -> done() context "2 inputs, no 'submit' elements but 1 button[type=button]", -> it "does not trigger submit event", (done) -> form = @$forms.find("#one-button-type-button").submit -> done("err: should not have submitted") cy.get("#one-button-type-button input:first").type("f").type("{enter}").then -> done() context "2 inputs, 1 'submit' element input[type=submit]", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-input-submit").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-input-submit input:first").type("foo{enter}") it "causes click event on the input[type=submit]", (done) -> @$forms.find("#multiple-inputs-and-input-submit input[type=submit]").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-input-submit input:first").type("foo{enter}") it "does not cause click event on the input[type=submit] if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-input-submit").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-input-submit input:first").type("f{enter}").then -> done() context "2 inputs, 1 'submit' element button[type=submit]", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-button-submit").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-submit input:first").type("foo{enter}") it "causes click event on the button[type=submit]", (done) -> @$forms.find("#multiple-inputs-and-button-submit button[type=submit]").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-submit input:first").type("foo{enter}") it "does not cause click event on the button[type=submit] if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-button-submit").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-button-submit input:first").type("f{enter}").then -> done() context "2 inputs, 1 'submit' element button", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-button-with-no-type").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("foo{enter}") it "causes click event on the button", (done) -> @$forms.find("#multiple-inputs-and-button-with-no-type button").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("foo{enter}") it "does not cause click event on the button if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-button-with-no-type").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("f{enter}").then -> done() context "2 inputs, 2 'submit' elements", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}") it "causes click event on the button", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits button").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}") it "does not cause click event on the button if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-multiple-submits").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-multiple-submits input:first").type("f{enter}").then -> done() context "disabled default button", -> beforeEach -> @$forms.find("#multiple-inputs-and-multiple-submits").find("button").prop("disabled", true) it "will not receive click event", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits button").click -> done("err: should not receive click event") cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}").then -> done() it "will not submit the form", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits").submit -> done("err: should not receive submit event") cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}").then -> done() describe "assertion verification", -> beforeEach -> cy.on "log:added", (attrs, log) => if log.get("name") is "assert" @lastLog = log return null it "eventually passes the assertion", -> cy.$$("input:first").keyup -> _.delay => $(@).addClass("typed") , 100 cy.get("input:first").type("f").should("have.class", "typed").then -> lastLog = @lastLog expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("passed") expect(lastLog.get("ended")).to.be.true describe ".log", -> beforeEach -> cy.on "log:added", (attrs, log) => @lastLog = log return null it "passes in $el", -> cy.get("input:first").type("foobar").then ($input) -> lastLog = @lastLog expect(lastLog.get("$el")).to.eq $input it "logs message", -> cy.get(":text:first").type("foobar").then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foobar" it "logs delay arguments", -> cy.get(":text:first").type("foo", {delay: 20}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foo, {delay: 20}" it "clones textarea value after the type happens", -> expectToHaveValueAndCoords = => cmd = cy.queue.find({name: "type"}) log = cmd.get("logs")[0] txt = log.get("snapshots")[1].body.find("#comments") expect(txt).to.have.value("foobarbaz") expect(log.get("coords")).to.be.ok cy .get("#comments").type("foobarbaz").then ($txt) -> expectToHaveValueAndCoords() .get("#comments").clear().type("onetwothree").then -> expectToHaveValueAndCoords() it "clones textarea value when textarea is focused first", -> expectToHaveValueAndNoCoords = => cmd = cy.queue.find({name: "type"}) log = cmd.get("logs")[0] txt = log.get("snapshots")[1].body.find("#comments") expect(txt).to.have.value("foobarbaz") expect(log.get("coords")).not.to.be.ok cy .get("#comments").focus().type("foobarbaz").then ($txt) -> expectToHaveValueAndNoCoords() .get("#comments").clear().type("onetwothree").then -> expectToHaveValueAndNoCoords() it "logs only one type event", -> logs = [] types = [] cy.on "log:added", (attrs, log) -> logs.push(log) if log.get("name") is "type" types.push(log) cy.get(":text:first").type("foo").then -> expect(logs.length).to.eq(2) expect(types.length).to.eq(1) it "logs immediately before resolving", -> $txt = cy.$$(":text:first") expected = false cy.on "log:added", (attrs, log) -> if log.get("name") is "type" expect(log.get("state")).to.eq("pending") expect(log.get("$el").get(0)).to.eq $txt.get(0) expected = true cy.get(":text:first").type("foo").then -> cy.get(":text:first").type("foo") it "snapshots before typing", -> expected = false cy.$$(":text:first").one "keydown", => lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(1) expect(lastLog.get("snapshots")[0].name).to.eq("before") expect(lastLog.get("snapshots")[0].body).to.be.an("object") expected = true cy.get(":text:first").type("foo").then -> expect(expected).to.be.true it "snapshots after typing", -> cy.get(":text:first").type("foo").then -> lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(2) expect(lastLog.get("snapshots")[1].name).to.eq("after") expect(lastLog.get("snapshots")[1].body).to.be.an("object") it "logs deltaOptions", -> cy.get(":text:first").type("foo", {force: true, timeout: 1000}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foo, {force: true, timeout: 1000}" expect(lastLog.invoke("consoleProps").Options).to.deep.eq {force: true, timeout: 1000} context "#consoleProps", -> it "has all of the regular options", -> cy.get("input:first").type("foobar").then ($input) -> { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($input) console = @lastLog.invoke("consoleProps") expect(console.Command).to.eq("type") expect(console.Typed).to.eq("foobar") expect(console["Applied To"]).to.eq $input.get(0) expect(console.Coords.x).to.be.closeTo(fromWindow.x, 1) expect(console.Coords.y).to.be.closeTo(fromWindow.y, 1) it "has a table of keys", -> cy.get(":text:first").type("{cmd}{option}foo{enter}b{leftarrow}{del}{enter}").then -> table = @lastLog.invoke("consoleProps").table() console.table(table.data, table.columns) expect(table.columns).to.deep.eq [ "typed", "which", "keydown", "keypress", "textInput", "input", "keyup", "change", "modifiers" ] expect(table.name).to.eq "Key Events Table" expectedTable = { 1: {typed: "<meta>", which: 91, keydown: true, modifiers: "meta"} 2: {typed: "<alt>", which: 18, keydown: true, modifiers: "alt, meta"} 3: {typed: "f", which: 70, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 4: {typed: "o", which: 79, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 5: {typed: "o", which: 79, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 6: {typed: "{enter}", which: 13, keydown: true, keypress: true, keyup: true, change: true, modifiers: "alt, meta"} 7: {typed: "b", which: 66, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 8: {typed: "{leftarrow}", which: 37, keydown: true, keyup: true, modifiers: "alt, meta"} 9: {typed: "{del}", which: 46, keydown: true, input: true, keyup: true, modifiers: "alt, meta"} 10: {typed: "{enter}", which: 13, keydown: true, keypress: true, keyup: true, modifiers: "alt, meta"} } for i in [1..10] expect(table.data[i]).to.deep.eq(expectedTable[i]) # table.data.forEach (item, i) -> # expect(item).to.deep.eq(expectedTable[i]) # expect(table.data).to.deep.eq(expectedTable) it "has no modifiers when there are none activated", -> cy.get(":text:first").type("f").then -> table = @lastLog.invoke("consoleProps").table() expect(table.data).to.deep.eq { 1: {typed: "f", which: 70, keydown: true, keypress: true, textInput: true, input: true, keyup: true} } it "has a table of keys with preventedDefault", -> cy.$$(":text:first").keydown -> return false cy.get(":text:first").type("f").then -> table = @lastLog.invoke("consoleProps").table() console.table(table.data, table.columns) expect(table.data).to.deep.eq { 1: {typed: "f", which: 70, keydown: "preventedDefault", keyup: true} } describe "errors", -> beforeEach -> Cypress.config("defaultCommandTimeout", 100) @logs = [] cy.on "log:added", (attrs, log) => @lastLog = log @logs.push(log) return null it "throws when not a dom subject", (done) -> cy.on "fail", -> done() cy.noop({}).type("foo") it "throws when subject is not in the document", (done) -> typed = 0 input = cy.$$("input:first").keypress (e) -> typed += 1 input.remove() cy.on "fail", (err) -> expect(typed).to.eq 1 expect(err.message).to.include "cy.type() failed because this element" done() cy.get("input:first").type("a").type("b") it "throws when not textarea or text-like", (done) -> cy.get("form").type("foo") cy.on "fail", (err) -> expect(err.message).to.include "cy.type() failed because it requires a valid typeable element." expect(err.message).to.include "The element typed into was:" expect(err.message).to.include "<form id=\"by-id\">...</form>" expect(err.message).to.include "Cypress considers the 'body', 'textarea', any 'element' with a 'tabindex' or 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid typeable elements." done() it "throws when subject is a collection of elements", (done) -> cy.get("textarea,:text").then ($inputs) -> @num = $inputs.length return $inputs .type("foo") cy.on "fail", (err) => expect(err.message).to.include "cy.type() can only be called on a single element. Your subject contained #{@num} elements." done() it "throws when the subject isnt visible", (done) -> input = cy.$$("input:text:first").show().hide() cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(2) expect(lastLog.get("error")).to.eq(err) expect(err.message).to.include "cy.type() failed because this element is not visible" done() cy.get("input:text:first").type("foo") it "throws when subject is disabled", (done) -> cy.$$("input:text:first").prop("disabled", true) cy.on "fail", (err) => ## get + type logs expect(@logs.length).eq(2) expect(err.message).to.include("cy.type() failed because this element is disabled:\n") done() cy.get("input:text:first").type("foo") it "throws when submitting within nested forms" it "logs once when not dom subject", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(1) expect(lastLog.get("error")).to.eq(err) done() cy.type("foobar") it "throws when input cannot be clicked", (done) -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on button</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.include "cy.type() failed because this element" expect(err.message).to.include "is being covered by another element" done() cy.get("#input-covered-in-span").type("foo") it "throws when special characters dont exist", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 allChars = _.keys(Keyboard.specialChars).concat(_.keys(Keyboard.modifierChars)).join(", ") expect(err.message).to.eq "Special character sequence: '{bar}' is not recognized. Available sequences are: #{allChars}" done() cy.get(":text:first").type("foo{bar}") it "throws when attemping to type tab", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "{tab} isn't a supported character sequence. You'll want to use the command cy.tab(), which is not ready yet, but when it is done that's what you'll use." done() cy.get(":text:first").type("foo{tab}") it "throws on an empty string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "cy.type() cannot accept an empty String. You need to actually type something." done() cy.get(":text:first").type("") it "allows typing spaces", -> cy .get(":text:first").type(" ") .should("have.value", " ") it "can type into input with invalid type attribute", -> cy.get(':text:first') .invoke('attr', 'type', 'asdf') .type('foobar') .should('have.value', 'foobar') _.each [NaN, Infinity, [], {}, null, undefined], (val) => it "throws when trying to type: #{val}", (done) -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "cy.type() can only accept a String or Number. You passed in: '#{val}'" done() cy.get(":text:first").type(val) it "throws when type is cancelled by preventingDefault mousedown" it "throws when element animation exceeds timeout", (done) -> ## force the animation calculation to think we moving at a huge distance ;-) cy.stub(Cypress.utils, "getDistanceBetween").returns(100000) keydowns = 0 cy.$$(":text:first").on "keydown", -> keydowns += 1 cy.on "fail", (err) -> expect(keydowns).to.eq(0) expect(err.message).to.include("cy.type() could not be issued because this element is currently animating:\n") done() cy.get(":text:first").type("foo") it "eventually fails the assertion", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(err.message).to.include(lastLog.get("error").message) expect(err.message).not.to.include("undefined") expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("failed") expect(lastLog.get("error")).to.be.an.instanceof(chai.AssertionError) done() cy.get("input:first").type("f").should("have.class", "typed") it "does not log an additional log on failure", (done) -> cy.on "fail", => expect(@logs.length).to.eq(3) done() cy.get("input:first").type("f").should("have.class", "typed") context "[type=date]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 1989") done() cy.get("#date-without-value").type(1989) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 01-01-1989") done() cy.get("#date-without-value").type("01-01-1989") it "throws when chars is invalid date", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 1989-04-31") done() cy.get("#date-without-value").type("1989-04-31") context "[type=month]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 6") done() cy.get("#month-without-value").type(6) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 01/2000") done() cy.get("#month-without-value").type("01/2000") it "throws when chars is invalid month", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 1989-13") done() cy.get("#month-without-value").type("1989-13") context "[type=tel]", -> it "can edit tel", -> cy.get('#by-name > input[type="tel"]') .type('1234567890') .should('have.prop', 'value', '1234567890') # it "throws when chars is invalid format", (done) -> # cy.on "fail", (err) => # expect(@logs.length).to.eq(2) # expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 2005/W18") # done() context "[type=week]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 23") done() cy.get("#week-without-value").type(23) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 2005/W18") done() cy.get("#week-without-value").type("2005/W18") it "throws when chars is invalid week", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 1995-W60") done() cy.get("#week-without-value").type("1995-W60") context "[type=time]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 9999") done() cy.get("#time-without-value").type(9999) it "throws when chars is invalid format (1:30)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 1:30") done() cy.get("#time-without-value").type("1:30") it "throws when chars is invalid format (01:30pm)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:30pm") done() cy.get("#time-without-value").type("01:30pm") it "throws when chars is invalid format (01:30:30.3333)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:30:30.3333") done() cy.get("#time-without-value").type("01:30:30.3333") it "throws when chars is invalid time", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:60") done() cy.get("#time-without-value").type("01:60") context "#clear", -> it "does not change the subject", -> textarea = cy.$$("textarea") cy.get("textarea").clear().then ($textarea) -> expect($textarea).to.match textarea it "removes the current value", -> textarea = cy.$$("#comments") textarea.val("foo bar") ## make sure it really has that value first expect(textarea).to.have.value("foo bar") cy.get("#comments").clear().then ($textarea) -> expect($textarea).to.have.value("") it "waits until element is no longer disabled", -> textarea = cy.$$("#comments").val("foo bar").prop("disabled", true) retried = false clicks = 0 textarea.on "click", -> clicks += 1 cy.on "command:retry", _.after 3, -> textarea.prop("disabled", false) retried = true cy.get("#comments").clear().then -> expect(clicks).to.eq(1) expect(retried).to.be.true it "can forcibly click even when being covered by another element", -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) clicked = false $input.on "click", -> clicked = true cy.get("#input-covered-in-span").clear({force: true}).then -> expect(clicked).to.be.true it "passes timeout and interval down to click", (done) -> input = $("<input />").attr("id", "input-covered-in-span").prependTo(cy.$$("body")) span = $("<span>span on input</span>").css(position: "absolute", left: input.offset().left, top: input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow").prependTo(cy.$$("body")) cy.on "command:retry", (options) -> expect(options.timeout).to.eq 1000 expect(options.interval).to.eq 60 done() cy.get("#input-covered-in-span").clear({timeout: 1000, interval: 60}) context "works on input type", -> inputTypes = [ "date", "datetime", "datetime-local", "email", "month", "number", "password", "search", "tel", "text", "time", "url", "week" ] inputTypes.forEach (type) -> it type, -> cy.get("##{type}-with-value").clear().then ($input) -> expect($input.val()).to.equal("") describe "assertion verification", -> beforeEach -> cy.on "log:added", (attrs, log) => if log.get("name") is "assert" @lastLog = log return null it "eventually passes the assertion", -> cy.$$("input:first").keyup -> _.delay => $(@).addClass("cleared") , 100 cy.get("input:first").clear().should("have.class", "cleared").then -> lastLog = @lastLog expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("passed") expect(lastLog.get("ended")).to.be.true it "eventually passes the assertion on multiple inputs", -> cy.$$("input").keyup -> _.delay => $(@).addClass("cleared") , 100 cy.get("input").invoke("slice", 0, 2).clear().should("have.class", "cleared") describe "errors", -> beforeEach -> Cypress.config("defaultCommandTimeout", 100) @logs = [] cy.on "log:added", (attrs, log) => @lastLog = log @logs.push(log) return null it "throws when not a dom subject", (done) -> cy.on "fail", (err) -> done() cy.noop({}).clear() it "throws when subject is not in the document", (done) -> cleared = 0 input = cy.$$("input:first").val("123").keydown (e) -> cleared += 1 input.remove() cy.on "fail", (err) -> expect(cleared).to.eq 1 expect(err.message).to.include "cy.clear() failed because this element" done() cy.get("input:first").clear().clear() it "throws if any subject isnt a textarea or text-like", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(3) expect(lastLog.get("error")).to.eq(err) expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<form id=\"checkboxes\">...</form>" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get("textarea:first,form#checkboxes").clear() it "throws if any subject isnt a :text", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<div id=\"dom\">...</div>" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get("div").clear() it "throws on an input radio", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<input type=\"radio\" name=\"gender\" value=\"male\">" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get(":radio").clear() it "throws on an input checkbox", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<input type=\"checkbox\" name=\"colors\" value=\"blue\">" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get(":checkbox").clear() it "throws when the subject isnt visible", (done) -> input = cy.$$("input:text:first").show().hide() cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because this element is not visible" done() cy.get("input:text:first").clear() it "throws when subject is disabled", (done) -> cy.$$("input:text:first").prop("disabled", true) cy.on "fail", (err) => ## get + type logs expect(@logs.length).eq(2) expect(err.message).to.include("cy.clear() failed because this element is disabled:\n") done() cy.get("input:text:first").clear() it "logs once when not dom subject", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(1) expect(lastLog.get("error")).to.eq(err) done() cy.clear() it "throws when input cannot be cleared", (done) -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.include "cy.clear() failed because this element" expect(err.message).to.include "is being covered by another element" done() cy.get("#input-covered-in-span").clear() it "eventually fails the assertion", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(err.message).to.include(lastLog.get("error").message) expect(err.message).not.to.include("undefined") expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("failed") expect(lastLog.get("error")).to.be.an.instanceof(chai.AssertionError) done() cy.get("input:first").clear().should("have.class", "cleared") it "does not log an additional log on failure", (done) -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) cy.on "fail", => expect(@logs.length).to.eq(3) done() cy.get("input:first").clear().should("have.class", "cleared") describe ".log", -> beforeEach -> cy.on "log:added", (attrs, log) => @lastLog = log return null it "logs immediately before resolving", -> $input = cy.$$("input:first") expected = false cy.on "log:added", (attrs, log) -> if log.get("name") is "clear" expect(log.get("state")).to.eq("pending") expect(log.get("$el").get(0)).to.eq $input.get(0) expected = true cy.get("input:first").clear().then -> expect(expected).to.be.true it "ends", -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) if log.get("name") is "clear" cy.get("input").invoke("slice", 0, 2).clear().then -> _.each logs, (log) -> expect(log.get("state")).to.eq("passed") expect(log.get("ended")).to.be.true it "snapshots after clicking", -> cy.get("input:first").clear().then ($input) -> lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(1) expect(lastLog.get("snapshots")[0]).to.be.an("object") it "logs deltaOptions", -> cy.get("input:first").clear({force: true, timeout: 1000}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "{force: true, timeout: 1000}" expect(lastLog.invoke("consoleProps").Options).to.deep.eq {force: true, timeout: 1000}
true
$ = Cypress.$.bind(Cypress) _ = Cypress._ Keyboard = Cypress.Keyboard Promise = Cypress.Promise $selection = require("../../../../../src/dom/selection") describe "src/cy/commands/actions/type", -> before -> cy .visit("/fixtures/dom.html") .then (win) -> @body = win.document.body.outerHTML beforeEach -> doc = cy.state("document") $(doc.body).empty().html(@body) context "#type", -> it "does not change the subject", -> input = cy.$$("input:first") cy.get("input:first").type("foo").then ($input) -> expect($input).to.match input it "changes the value", -> input = cy.$$("input:text:first") input.val("") ## make sure we are starting from a ## clean state expect(input).to.have.value("") cy.get("input:text:first").type("foo").then ($input) -> expect($input).to.have.value("foo") it "appends subsequent type commands", -> cy .get("input:first").type("123").type("456") .should("have.value", "123456") it "appends subsequent commands when value is changed in between", -> cy .get("input:first") .type("123") .then ($input) -> $input[0].value += '-' return $input .type("456") .should("have.value", "123-456") it "can type numbers", -> cy.get(":text:first").type(123).then ($text) -> expect($text).to.have.value("123") it "triggers focus event on the input", (done) -> cy.$$("input:text:first").focus -> done() cy.get("input:text:first").type("bar") it "lists the input as the focused element", -> $input = cy.$$("input:text:first") cy.get("input:text:first").type("bar").focused().then ($focused) -> expect($focused.get(0)).to.eq $input.get(0) it "causes previous input to receive blur", -> blurred = false cy.$$("input:text:first").blur -> blurred = true cy .get("input:text:first").type("foo") .get("input:text:last").type("bar") .then -> expect(blurred).to.be.true it "can type into contenteditable", -> oldText = cy.$$("#contenteditable").get(0).innerText cy.get("#contenteditable") .type(" foo") .then ($div) -> expect($div.get(0).innerText).to.eq (oldText + " foo") it "delays 50ms before resolving", -> cy.$$(":text:first").on "change", (e) => cy.spy(Promise, "delay") cy.get(":text:first").type("foo{enter}").then -> expect(Promise.delay).to.be.calledWith(50, "type") it "increases the timeout delta", -> cy.spy(cy, "timeout") cy.get(":text:first").type("foo{enter}").then -> expect(cy.timeout).to.be.calledWith(40, true, "type") expect(cy.timeout).to.be.calledWith(50, true, "type") it "accepts body as subject", -> cy.get("body").type("foo") it "does not click when body is subject", -> bodyClicked = false cy.$$("body").on "click", -> bodyClicked = true cy.get("body").type("foo").then -> expect(bodyClicked).to.be.false describe "actionability", -> it "can forcibly click even when element is invisible", -> $txt = cy.$$(":text:first").hide() expect($txt).not.to.have.value("foo") clicked = false $txt.on "click", -> clicked = true cy.get(":text:first").type("foo", {force: true}).then ($input) -> expect(clicked).to.be.true expect($input).to.have.value("foo") it "can forcibly click even when being covered by another element", -> $input = $("<input />") .attr("id", "input-covered-in-span") .css({ width: 50 }) .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) clicked = false $input.on "click", -> clicked = true cy.get("#input-covered-in-span").type("foo", {force: true}).then ($input) -> expect(clicked).to.be.true expect($input).to.have.value("foo") it "waits until element becomes visible", -> $txt = cy.$$(":text:first").hide() retried = false cy.on "command:retry", _.after 3, -> $txt.show() retried = true cy.get(":text:first").type("foo").then -> expect(retried).to.be.true it "waits until element is no longer disabled", -> $txt = cy.$$(":text:first").prop("disabled", true) retried = false clicks = 0 $txt.on "click", -> clicks += 1 cy.on "command:retry", _.after 3, -> $txt.prop("disabled", false) retried = true cy.get(":text:first").type("foo").then -> expect(clicks).to.eq(1) expect(retried).to.be.true it "waits until element stops animating", -> retries = 0 cy.on "command:retry", (obj) -> retries += 1 cy.stub(cy, "ensureElementIsNotAnimating") .throws(new Error("animating!")) .onThirdCall().returns() cy.get(":text:first").type("foo").then -> ## - retry animation coords ## - retry animation ## - retry animation expect(retries).to.eq(3) expect(cy.ensureElementIsNotAnimating).to.be.calledThrice it "does not throw when waiting for animations is disabled", -> cy.stub(cy, "ensureElementIsNotAnimating").throws(new Error("animating!")) Cypress.config("waitForAnimations", false) cy.get(":text:first").type("foo").then -> expect(cy.ensureElementIsNotAnimating).not.to.be.called it "does not throw when turning off waitForAnimations in options", -> cy.stub(cy, "ensureElementIsNotAnimating").throws(new Error("animating!")) cy.get(":text:first").type("foo", {waitForAnimations: false}).then -> expect(cy.ensureElementIsNotAnimating).not.to.be.called it "passes options.animationDistanceThreshold to cy.ensureElementIsNotAnimating", -> $txt = cy.$$(":text:first") { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($txt) cy.spy(cy, "ensureElementIsNotAnimating") cy.get(":text:first").type("foo", {animationDistanceThreshold: 1000}).then -> args = cy.ensureElementIsNotAnimating.firstCall.args expect(args[1]).to.deep.eq([fromWindow, fromWindow]) expect(args[2]).to.eq(1000) it "passes config.animationDistanceThreshold to cy.ensureElementIsNotAnimating", -> animationDistanceThreshold = Cypress.config("animationDistanceThreshold") $txt = cy.$$(":text:first") { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($txt) cy.spy(cy, "ensureElementIsNotAnimating") cy.get(":text:first").type("foo").then -> args = cy.ensureElementIsNotAnimating.firstCall.args expect(args[1]).to.deep.eq([fromWindow, fromWindow]) expect(args[2]).to.eq(animationDistanceThreshold) describe "input types where no extra formatting required", -> _.each [ "PI:PASSWORD:<PASSWORD>END_PI" "email" "number" "search" "url" "tel" ], (type) -> it "accepts input [type=#{type}]", -> input = cy.$$("<input type='#{type}' id='input-type-#{type}' />") cy.$$("body").append(input) cy.get("#input-type-#{type}").type("1234").then ($input) -> expect($input).to.have.value "1234" expect($input.get(0)).to.eq $input.get(0) it "accepts type [type=#{type}], regardless of capitalization", -> input = cy.$$("<input type='#{type.toUpperCase()}' id='input-type-#{type}' />") cy.$$("body").append(input) cy.get("#input-type-#{type}").type("1234") describe "tabindex", -> beforeEach -> @$div = cy.$$("#tabindex") it "receives keydown, keyup, keypress", -> keydown = false keypress = false keyup = false @$div.keydown -> keydown = true @$div.keypress -> keypress = true @$div.keyup -> keyup = true cy.get("#tabindex").type("a").then -> expect(keydown).to.be.true expect(keypress).to.be.true expect(keyup).to.be.true it "does not receive textInput", -> textInput = false @$div.on "textInput", -> textInput = true cy.get("#tabindex").type("f").then -> expect(textInput).to.be.false it "does not receive input", -> input = false @$div.on "input", -> input = true cy.get("#tabindex").type("f").then -> expect(input).to.be.false it "does not receive change event", -> innerText = @$div.text() change = false @$div.on "change", -> change = true cy.get("#tabindex").type("foo{enter}").then ($el) -> expect(change).to.be.false expect($el.text()).to.eq(innerText) it "does not change inner text", -> innerText = @$div.text() cy.get("#tabindex").type("foo{leftarrow}{del}{rightarrow}{enter}").should("have.text", innerText) it "receives focus", -> focus = false @$div.focus -> focus = true cy.get("#tabindex").type("f").then -> expect(focus).to.be.true it "receives blur", -> blur = false @$div.blur -> blur = true cy .get("#tabindex").type("f") .get("input:first").focus().then -> expect(blur).to.be.true it "receives keydown and keyup for other special characters and keypress for enter and regular characters", -> keydowns = [] keyups = [] keypresses = [] @$div.keydown (e) -> keydowns.push(e) @$div.keypress (e) -> keypresses.push(e) @$div.keyup (e) -> keyups.push(e) cy .get("#tabindex").type("f{leftarrow}{rightarrow}{enter}") .then -> expect(keydowns).to.have.length(4) expect(keypresses).to.have.length(2) expect(keyups).to.have.length(4) describe "delay", -> it "adds delay to delta for each key sequence", -> cy.spy(cy, "timeout") cy .get(":text:first") .type("foo{enter}bar{leftarrow}", { delay: 5 }) .then -> expect(cy.timeout).to.be.calledWith(5 * 8, true, "type") it "can cancel additional keystrokes", (done) -> cy.stub(Cypress.runner, "stop") text = cy.$$(":text:first").keydown _.after 3, -> Cypress.stop() cy.on "stop", -> _.delay -> expect(text).to.have.value("foo") done() , 50 cy.get(":text:first").type("foo{enter}bar{leftarrow}") describe "events", -> it "receives keydown event", (done) -> $txt = cy.$$(":text:first") $txt.on "keydown", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 0 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 65 ## deprecated but fired by chrome always uppercase in the ASCII table layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keydown" view: cy.state("window") which: 65 ## deprecated but fired by chrome } done() cy.get(":text:first").type("a") it "receives keypress event", (done) -> $txt = cy.$$(":text:first") $txt.on "keypress", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 97 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 97 ## deprecated layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keypress" view: cy.state("window") which: 97 ## deprecated } done() cy.get(":text:first").type("a") it "receives keyup event", (done) -> $txt = cy.$$(":text:first") $txt.on "keyup", (e) => obj = _.pick(e.originalEvent, "altKey", "bubbles", "cancelable", "charCode", "ctrlKey", "detail", "keyCode", "view", "layerX", "layerY", "location", "metaKey", "pageX", "pageY", "repeat", "shiftKey", "type", "which", "key") expect(obj).to.deep.eq { altKey: false bubbles: true cancelable: true charCode: 0 ## deprecated ctrlKey: false detail: 0 key: "a" keyCode: 65 ## deprecated but fired by chrome always uppercase in the ASCII table layerX: 0 layerY: 0 location: 0 metaKey: false pageX: 0 pageY: 0 repeat: false shiftKey: false type: "keyup" view: cy.state("window") which: 65 ## deprecated but fired by chrome } done() cy.get(":text:first").type("a") it "receives textInput event", (done) -> $txt = cy.$$(":text:first") $txt.on "textInput", (e) => obj = _.pick e.originalEvent, "bubbles", "cancelable", "charCode", "data", "detail", "keyCode", "layerX", "layerY", "pageX", "pageY", "type", "view", "which" expect(obj).to.deep.eq { bubbles: true cancelable: true charCode: 0 data: "a" detail: 0 keyCode: 0 layerX: 0 layerY: 0 pageX: 0 pageY: 0 type: "textInput" view: cy.state("window") which: 0 } done() cy.get(":text:first").type("a") it "receives input event", (done) -> $txt = cy.$$(":text:first") $txt.on "input", (e) => obj = _.pick e.originalEvent, "bubbles", "cancelable", "type" expect(obj).to.deep.eq { bubbles: true cancelable: false type: "input" } done() cy.get(":text:first").type("a") it "fires events in the correct order" it "fires events for each key stroke" it "does fire input event when value changes", -> fired = false cy.$$(":text:first").on "input", -> fired = true fired = false cy.get(":text:first") .invoke("val", "bar") .type("{selectAll}{rightarrow}{backspace}") .then -> expect(fired).to.eq true fired = false cy.get(":text:first") .invoke("val", "bar") .type("{selectAll}{leftarrow}{del}") .then -> expect(fired).to.eq true cy.$$('[contenteditable]:first').on "input", () -> fired = true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{rightarrow}{backspace}') .then -> expect(fired).to.eq true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{leftarrow}{del}') .then -> expect(fired).to.eq true it "does not fire input event when value does not change", -> fired = false cy.$$(":text:first").on "input", (e) -> fired = true fired = false cy.get(":text:first") .invoke("val", "bar") .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get(":text:first") .invoke("val", "bar") .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false cy.$$("textarea:first").on "input", (e) -> fired = true fired = false cy.get("textarea:first") .invoke("val", "bar") .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get("textarea:first") .invoke("val", "bar") .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false cy.$$('[contenteditable]:first').on "input", () -> fired = true fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{rightarrow}{del}') .then -> expect(fired).to.eq false fired = false cy.get('[contenteditable]:first') .invoke('html', 'foobar') .type('{selectAll}{leftarrow}{backspace}') .then -> expect(fired).to.eq false describe "maxlength", -> it "limits text entered to the maxlength attribute of a text input", -> $input = cy.$$(":text:first") $input.attr("maxlength", 5) cy.get(":text:first") .type("1234567890") .then (input) -> expect(input).to.have.value("12345") it "ignores an invalid maxlength attribute", -> $input = cy.$$(":text:first") $input.attr("maxlength", "five") cy.get(":text:first") .type("1234567890") .then (input) -> expect(input).to.have.value("1234567890") it "handles special characters", -> $input = cy.$$(":text:first") $input.attr("maxlength", 5) cy.get(":text:first") .type("12{selectall}") .then (input) -> expect(input).to.have.value("12") it "maxlength=0 events", -> events = [] push = (evt) -> return -> events.push(evt) cy .$$(":text:first") .attr("maxlength", 0) .on("keydown", push("keydown")) .on("keypress", push("keypress")) .on("textInput", push("textInput")) .on("input", push("input")) .on("keyup", push("keyup")) cy.get(":text:first") .type("1") .then -> expect(events).to.deep.eq([ "keydown", "keypress", "textInput", "keyup" ]) it "maxlength=1 events", -> events = [] push = (evt) -> return -> events.push(evt) cy .$$(":text:first") .attr("maxlength", 1) .on("keydown", push("keydown")) .on("keypress", push("keypress")) .on("textInput", push("textInput")) .on("input", push("input")) .on("keyup", push("keyup")) cy.get(":text:first") .type("12") .then -> expect(events).to.deep.eq([ "keydown", "keypress", "textInput", "input", "keyup" "keydown", "keypress", "textInput", "keyup" ]) describe "value changing", -> it "changes the elements value", -> cy.get("#input-without-value").type("a").then ($text) -> expect($text).to.have.value("a") it "changes the elements value for multiple keys", -> cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("foo") it "inserts text after existing text", -> cy.get("#input-with-value").type(" bar").then ($text) -> expect($text).to.have.value("foo bar") it "inserts text after existing text input by invoking val", -> cy.get("#input-without-value").invoke("val", "foo").type(" bar").then ($text) -> expect($text).to.have.value("foo bar") it "overwrites text when currently has selection", -> cy.get("#input-without-value").invoke('val', '0').then (el) -> el.select() cy.get("#input-without-value").type("50").then ($input) -> expect($input).to.have.value("50") it "overwrites text when selectAll in click handler", -> cy.$$("#input-without-value").val("0").click -> $(@).select() it "overwrites text when selectAll in mouseup handler", -> cy.$$("#input-without-value").val("0").mouseup -> $(@).select() it "overwrites text when selectAll in mouseup handler", -> cy.$$("#input-without-value").val("0").mouseup -> $(@).select() it "responsive to keydown handler", -> cy.$$("#input-without-value").val("1234").keydown -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("651234") it "responsive to keyup handler", -> cy.$$("#input-without-value").val("1234").keyup -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("612345") it "responsive to input handler", -> cy.$$("#input-without-value").val("1234").keyup -> $(@).get(0).setSelectionRange(0,0) cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("612345") it "responsive to change handler", -> cy.$$("#input-without-value").val("1234").change -> $(@).get(0).setSelectionRange(0,0) ## no change event should be fired cy.get("#input-without-value").type("56").then ($input) -> expect($input).to.have.value("123456") it "automatically moves the caret to the end if value is changed manually", -> cy.$$("#input-without-value").keypress (e) -> e.preventDefault() key = String.fromCharCode(e.which) $input = $(e.target) val = $input.val() ## setting value updates cursor to the end of input $input.val(val + key + "-") cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("f-o-o-") it "automatically moves the caret to the end if value is changed manually asynchronously", -> cy.$$("#input-without-value").keypress (e) -> key = String.fromCharCode(e.which) $input = $(e.target) _.defer -> val = $input.val() $input.val(val + "-") cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("f-o-o-") it "does not fire keypress when keydown is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> done("should not have received keypress event") cy.$$("#input-without-value").get(0).addEventListener "keydown", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "does not insert key when keydown is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "keydown", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not insert key when keypress is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not fire textInput when keypress is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> done("should not have received textInput event") cy.$$("#input-without-value").get(0).addEventListener "keypress", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "does not insert key when textInput is preventedDefault", -> cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($text) -> expect($text).to.have.value("") it "does not fire input when textInput is preventedDefault", (done) -> cy.$$("#input-without-value").get(0).addEventListener "input", (e) -> done("should not have received input event") cy.$$("#input-without-value").get(0).addEventListener "textInput", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then -> done() it "preventing default to input event should not affect anything", -> cy.$$("#input-without-value").get(0).addEventListener "input", (e) -> e.preventDefault() cy.get("#input-without-value").type("foo").then ($input) -> expect($input).to.have.value("foo") describe "input[type=number]", -> it "can change values", -> cy.get("#number-without-value").type("42").then ($text) -> expect($text).to.have.value("42") it "can input decimal", -> cy.get("#number-without-value").type("2.0").then ($input) -> expect($input).to.have.value("2.0") it "can utilize {selectall}", -> cy.get("#number-with-value").type("{selectall}99").then ($input) -> expect($input).to.have.value("99") it "can utilize arrows", -> cy.get("#number-with-value").type("{leftarrow}{leftarrow}{rightarrow}9").then ($input) -> expect($input).to.have.value("192") it "inserts text after existing text ", -> cy.get("#number-with-value").type("34").then ($text) -> expect($text).to.have.value("1234") it "inserts text after existing text input by invoking val", -> cy.get("#number-without-value").invoke("val", "12").type("34").then ($text) -> expect($text).to.have.value("1234") it "overwrites text on input[type=number] when input has existing text selected", -> cy.get("#number-without-value").invoke('val', "0").then (el) -> el.get(0).select() cy.get("#number-without-value").type("50").then ($input) -> expect($input).to.have.value("50") it "can type negative numbers", -> cy.get('#number-without-value') .type('-123.12') .should('have.value', '-123.12') it "type=number blurs consistently", -> blurred = 0 cy.$$("#number-without-value").blur -> blurred++ cy.get("#number-without-value") .type('200').blur() .then -> expect(blurred).to.eq 1 describe "input[type=email]", -> it "can change values", -> cy.get("#email-without-value").type("PI:EMAIL:<EMAIL>END_PI").then ($text) -> expect($text).to.have.value("PI:EMAIL:<EMAIL>END_PI") it "can utilize {selectall}", -> cy.get("#email-with-value").type("{selectall}PI:EMAIL:<EMAIL>END_PI").then ($text) -> expect($text).to.have.value("PI:EMAIL:<EMAIL>END_PI") it "can utilize arrows", -> cy.get("#email-with-value").type("{leftarrow}{rightarrow}om").then ($text) -> expect($text).to.have.value("PI:EMAIL:<EMAIL>END_PI") it "inserts text after existing text", -> cy.get("#email-with-value").type("om").then ($text) -> expect($text).to.have.value("PI:EMAIL:<EMAIL>END_PI") it "inserts text after existing text input by invoking val", -> cy.get("#email-without-value").invoke("val", "PI:EMAIL:<EMAIL>END_PI").type("om").then ($text) -> expect($text).to.have.value("PI:EMAIL:<EMAIL>END_PI") it "overwrites text when input has existing text selected", -> cy.get("#email-without-value").invoke('val', "PI:EMAIL:<EMAIL>END_PI").invoke('select') cy.get("#email-without-value").type("PI:EMAIL:<EMAIL>END_PI").then ($input) -> expect($input).to.have.value("PI:EMAIL:<EMAIL>END_PI") it "type=email blurs consistently", -> blurred = 0 cy.$$("#email-without-value").blur -> blurred++ cy.get("#email-without-value") .type('PI:EMAIL:<EMAIL>END_PI').blur() .then -> expect(blurred).to.eq 1 describe "input[type=password]", -> it "can change values", -> cy.get("#password-without-value").type("password").then ($text) -> expect($text).to.have.value("password") it "inserts text after existing text", -> cy.get("#password-with-value").type("word").then ($text) -> expect($text).to.have.value("password") it "inserts text after existing text input by invoking val", -> cy.get("#password-without-value").invoke("val", "secr").type("et").then ($text) -> expect($text).to.have.value("secret") it "overwrites text when input has existing text selected", -> cy.get("#password-without-value").invoke('val', "secret").invoke('select') cy.get("#password-without-value").type("agent").then ($input) -> expect($input).to.have.value("agent") it "overwrites text when input has selected range of text in click handler", -> cy.$$("#input-with-value").mouseup (e) -> # e.preventDefault() e.target.setSelectionRange(1, 1) select = (e) -> e.target.select() cy .$$("#password-without-value") .val("secret") .click(select) .keyup (e) -> switch e.key when "g" select(e) when "n" e.target.setSelectionRange(0, 1) cy.get("#password-without-value").type("agent").then ($input) -> expect($input).to.have.value("tn") describe "input[type=date]", -> it "can change values", -> cy.get("#date-without-value").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") it "overwrites existing value", -> cy.get("#date-with-value").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") it "overwrites existing value input by invoking val", -> cy.get("#date-without-value").invoke("val", "2016-01-01").type("1959-09-13").then ($text) -> expect($text).to.have.value("1959-09-13") describe "input[type=month]", -> it "can change values", -> cy.get("#month-without-value").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") it "overwrites existing value", -> cy.get("#month-with-value").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") it "overwrites existing value input by invoking val", -> cy.get("#month-without-value").invoke("val", "2016-01").type("1959-09").then ($text) -> expect($text).to.have.value("1959-09") describe "input[type=week]", -> it "can change values", -> cy.get("#week-without-value").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") it "overwrites existing value", -> cy.get("#week-with-value").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") it "overwrites existing value input by invoking val", -> cy.get("#week-without-value").invoke("val", "2016-W01").type("1959-W09").then ($text) -> expect($text).to.have.value("1959-W09") describe "input[type=time]", -> it "can change values", -> cy.get("#time-without-value").type("01:23:45").then ($text) -> expect($text).to.have.value("01:23:45") it "overwrites existing value", -> cy.get("#time-with-value").type("12:34:56").then ($text) -> expect($text).to.have.value("12:34:56") it "overwrites existing value input by invoking val", -> cy.get("#time-without-value").invoke("val", "01:23:45").type("12:34:56").then ($text) -> expect($text).to.have.value("12:34:56") it "can be formatted HH:mm", -> cy.get("#time-without-value").type("01:23").then ($text) -> expect($text).to.have.value("01:23") it "can be formatted HH:mm:ss", -> cy.get("#time-without-value").type("01:23:45").then ($text) -> expect($text).to.have.value("01:23:45") it "can be formatted HH:mm:ss.S", -> cy.get("#time-without-value").type("01:23:45.9").then ($text) -> expect($text).to.have.value("01:23:45.9") it "can be formatted HH:mm:ss.SS", -> cy.get("#time-without-value").type("01:23:45.99").then ($text) -> expect($text).to.have.value("01:23:45.99") it "can be formatted HH:mm:ss.SSS", -> cy.get("#time-without-value").type("01:23:45.999").then ($text) -> expect($text).to.have.value("01:23:45.999") describe "[contenteditable]", -> it "can change values", -> cy.get("#input-types [contenteditable]").type("foo").then ($div) -> expect($div).to.have.text("foo") it "inserts text after existing text", -> cy.get("#input-types [contenteditable]").invoke("text", "foo").type(" bar").then ($text) -> expect($text).to.have.text("foo bar") it "can type into [contenteditable] with existing <div>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>foo</div>' cy.get("[contenteditable]:first") .type("bar").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n") expect($div.get(0).textContent).to.eql("foobar") expect($div.get(0).innerHTML).to.eql("<div>foobar</div>") it "can type into [contenteditable] with existing <p>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<p>foo</p>' cy.get("[contenteditable]:first") .type("bar").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n\n") expect($div.get(0).textContent).to.eql("foobar") expect($div.get(0).innerHTML).to.eql("<p>foobar</p>") it "collapses selection to start on {leftarrow}", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>bar</div>' cy.get("[contenteditable]:first") .type("{selectall}{leftarrow}foo").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\n") it "collapses selection to end on {rightarrow}", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>bar</div>' cy.get("[contenteditable]:first") .type("{selectall}{leftarrow}foo{selectall}{rightarrow}baz").then ($div) -> expect($div.get(0).innerText).to.eql("foobarbaz\n") it "can remove a placeholder <br>", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div><br></div>' cy.get("[contenteditable]:first") .type("foobar").then ($div) -> expect($div.get(0).innerHTML).to.eql("<div>foobar</div>") it "can type into an iframe with designmode = 'on'", -> ## append a new iframe to the body cy.$$('<iframe id="generic-iframe" src="/fixtures/generic.html" style="height: 500px"></iframe>') .appendTo cy.$$('body') ## wait for iframe to load loaded = false cy.get('#generic-iframe') .then ($iframe) -> $iframe.load -> loaded = true .scrollIntoView() .should -> expect(loaded).to.eq true ## type text into iframe cy.get('#generic-iframe') .then ($iframe) -> $iframe[0].contentDocument.designMode = 'on' iframe = $iframe.contents() cy.wrap(iframe.find('html')).first() .type('{selectall}{del} foo bar baz{enter}ac{leftarrow}b') # assert that text was typed cy.get('#generic-iframe') .then ($iframe) -> iframeText = $iframe[0].contentDocument.body.innerText expect(iframeText).to.include('foo bar baz\nabc') ## TODO: fix this with 4.0 updates describe.skip "element reference loss", -> it 'follows the focus of the cursor', -> charCount = 0 cy.$$('input:first').keydown -> if charCount is 3 cy.$$('input').eq(1).focus() charCount++ cy.get('input:first').type('foobar').then -> cy.get('input:first').should('have.value', 'foo') cy.get('input').eq(1).should('have.value', 'bar') describe "specialChars", -> context "{{}", -> it "sets which and keyCode to 219", (done) -> cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 219 expect(e.keyCode).to.eq 219 done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires keypress event with 123 charCode", (done) -> cy.$$(":text:first").on "keypress", (e) -> expect(e.charCode).to.eq 123 expect(e.which).to.eq 123 expect(e.keyCode).to.eq 123 done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires textInput event with e.data", (done) -> cy.$$(":text:first").on "textInput", (e) -> expect(e.originalEvent.data).to.eq "{" done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "fires input event", (done) -> cy.$$(":text:first").on "input", (e) -> done() cy.get(":text:first").invoke("val", "ab").type("{{}") it "can prevent default character insertion", -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 219 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{{}").then ($input) -> expect($input).to.have.value("foo") context "{esc}", -> it "sets which and keyCode to 27 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 27 expect(e.keyCode).to.eq 27 expect(e.key).to.eq "Escape" done() cy.get(":text:first").invoke("val", "ab").type("{esc}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{esc}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{esc}").then -> done() it "can prevent default esc movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 27 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("d{esc}").then ($input) -> expect($input).to.have.value("food") done() context "{backspace}", -> it "backspaces character to the left", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{backspace}u").then ($input) -> expect($input).to.have.value("bur") it "can backspace a selection range of characters", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'ar' characters $input.get(0).setSelectionRange(1,3) .get(":text:first").type("{backspace}").then ($input) -> expect($input).to.have.value("b") it "sets which and keyCode to 8 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 8 expect(e.keyCode).to.eq 8 expect(e.key).to.eq "Backspace" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}{backspace}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{backspace}").then -> done() it "can prevent default backspace movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 8 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{backspace}").then ($input) -> expect($input).to.have.value("foo") done() context "{del}", -> it "deletes character to the right", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{del}").then ($input) -> expect($input).to.have.value("ba") it "can delete a selection range of characters", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'ar' characters $input.get(0).setSelectionRange(1,3) .get(":text:first").type("{del}").then ($input) -> expect($input).to.have.value("b") it "sets which and keyCode to 46 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 46 expect(e.keyCode).to.eq 46 expect(e.key).to.eq "Delete" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}{del}") it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{del}").then -> done() it "does fire input event when value changes", (done) -> cy.$$(":text:first").on "input", (e) -> done() cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' characters $input.get(0).setSelectionRange(0,1) .get(":text:first").type("{del}") it "does not fire input event when value does not change", (done) -> cy.$$(":text:first").on "input", (e) -> done("should not have fired input") cy.get(":text:first").invoke("val", "ab").type("{del}").then -> done() it "can prevent default del movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 46 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{del}").then ($input) -> expect($input).to.have.value("foo") done() context "{leftarrow}", -> it "can move the cursor from the end to end - 1", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("banr") it "does not move the cursor if already at bounds 0", -> cy.get(":text:first").invoke("val", "bar").type("{selectall}{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets the cursor to the left bounds", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(1,2) .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("bnar") it "sets the cursor to the very beginning", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(0,1) .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets which and keyCode to 37 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 37 expect(e.keyCode).to.eq 37 expect(e.key).to.eq "ArrowLeft" done() cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{leftarrow}").then -> done() it "can prevent default left arrow movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 37 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}d").then ($input) -> expect($input).to.have.value("food") done() context "{rightarrow}", -> it "can move the cursor from the beginning to beginning + 1", -> cy.get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the beginning $input.get(0).setSelectionRange(0,0) .get(":text:first").type("{rightarrow}n").then ($input) -> expect($input).to.have.value("bnar") it "does not move the cursor if already at end of bounds", -> cy.get(":text:first").invoke("val", "bar").type("{selectall}{rightarrow}n").then ($input) -> expect($input).to.have.value("barn") it "sets the cursor to the rights bounds", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> ## select the 'a' character $input.get(0).setSelectionRange(1,2) .get(":text:first").type("{rightarrow}n").then ($input) -> expect($input).to.have.value("banr") it "sets the cursor to the very beginning", -> cy .get(":text:first").invoke("val", "bar").focus().then ($input) -> $input.select() .get(":text:first").type("{leftarrow}n").then ($input) -> expect($input).to.have.value("nbar") it "sets which and keyCode to 39 and does not fire keypress events", (done) -> cy.$$(":text:first").on "keypress", -> done("should not have received keypress") cy.$$(":text:first").on "keydown", (e) -> expect(e.which).to.eq 39 expect(e.keyCode).to.eq 39 expect(e.key).to.eq "ArrowRight" done() cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{rightarrow}").then -> done() it "can prevent default right arrow movement", (done) -> cy.$$(":text:first").on "keydown", (e) -> if e.keyCode is 39 e.preventDefault() cy.get(":text:first").invoke("val", "foo").type("{leftarrow}{rightarrow}d").then ($input) -> expect($input).to.have.value("fodo") done() context "{uparrow}", -> beforeEach -> cy.$$("#comments").val("foo\nbar\nbaz") it "sets which and keyCode to 38 and does not fire keypress events", (done) -> cy.$$("#comments").on "keypress", -> done("should not have received keypress") cy.$$("#comments").on "keydown", (e) -> expect(e.which).to.eq 38 expect(e.keyCode).to.eq 38 expect(e.key).to.eq "ArrowUp" done() cy.get("#comments").type("{uparrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$("#comments").on "textInput", (e) -> done("textInput should not have fired") cy.get("#comments").type("{uparrow}").then -> done() it "does not fire input event", (done) -> cy.$$("#comments").on "input", (e) -> done("input should not have fired") cy.get("#comments").type("{uparrow}").then -> done() it "up and down arrow on contenteditable", -> cy.$$('[contenteditable]:first').get(0).innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' cy.get("[contenteditable]:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33").then ($div) -> expect($div.get(0).innerText).to.eql("foo22\nb11ar\nbaz33\n") it "uparrow ignores current selection", -> ce = cy.$$('[contenteditable]:first').get(0) ce.innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' ## select 'bar' line = cy.$$('[contenteditable]:first div:nth-child(1)').get(0) cy.document().then (doc) -> ce.focus() doc.getSelection().selectAllChildren(line) cy.get("[contenteditable]:first") .type("{uparrow}11").then ($div) -> expect($div.get(0).innerText).to.eql("11foo\nbar\nbaz\n") it "up and down arrow on textarea", -> cy.$$('textarea:first').get(0).value = 'foo\nbar\nbaz' cy.get("textarea:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33").should('have.value', "foo22\nb11ar\nbaz33") it "increments input[type=number]", -> cy.get('input[type="number"]:first') .invoke('val', '12.34') .type('{uparrow}{uparrow}') .should('have.value', '14') context "{downarrow}", -> beforeEach -> cy.$$("#comments").val("foo\nbar\nbaz") it "sets which and keyCode to 40 and does not fire keypress events", (done) -> cy.$$("#comments").on "keypress", -> done("should not have received keypress") cy.$$("#comments").on "keydown", (e) -> expect(e.which).to.eq 40 expect(e.keyCode).to.eq 40 expect(e.key).to.eq "ArrowDown" done() cy.get("#comments").type("{downarrow}").then ($input) -> done() it "does not fire textInput event", (done) -> cy.$$("#comments").on "textInput", (e) -> done("textInput should not have fired") cy.get("#comments").type("{downarrow}").then -> done() it "does not fire input event", (done) -> cy.$$("#comments").on "input", (e) -> done("input should not have fired") cy.get("#comments").type("{downarrow}").then -> done() it "{downarrow} will move to EOL on textarea", -> cy.$$('textarea:first').get(0).value = 'foo\nbar\nbaz' cy.get("textarea:first") .type("{leftarrow}{leftarrow}{uparrow}11{uparrow}22{downarrow}{downarrow}33{leftarrow}{downarrow}44").should('have.value', "foo22\nb11ar\nbaz3344") it "decrements input[type='number']", -> cy.get('input[type="number"]:first') .invoke('val', '12.34') .type('{downarrow}{downarrow}') .should('have.value', '11') it "downarrow ignores current selection", -> ce = cy.$$('[contenteditable]:first').get(0) ce.innerHTML = '<div>foo</div>' + '<div>bar</div>' + '<div>baz</div>' ## select 'foo' line = cy.$$('[contenteditable]:first div:first').get(0) cy.document().then (doc) -> ce.focus() doc.getSelection().selectAllChildren(line) cy.get("[contenteditable]:first") .type("{downarrow}22").then ($div) -> expect($div.get(0).innerText).to.eql("foo\n22bar\nbaz\n") context "{selectall}{del}", -> it "can select all the text and delete", -> cy.get(":text:first").invoke("val", "1234").type("{selectall}{del}").type("foo").then ($text) -> expect($text).to.have.value("foo") it "can select all [contenteditable] and delete", -> cy.get("#input-types [contenteditable]").invoke("text", "1234").type("{selectall}{del}").type("foo").then ($div) -> expect($div).to.have.text("foo") context "{selectall} then type something", -> it "replaces the text", -> cy.get("#input-with-value").type("{selectall}new").then ($text) -> expect($text).to.have.value("new") context "{enter}", -> it "sets which and keyCode to 13 and prevents EOL insertion", (done) -> cy.$$("#input-types textarea").on "keypress", _.after 2, (e) -> done("should not have received keypress event") cy.$$("#input-types textarea").on "keydown", _.after 2, (e) -> expect(e.which).to.eq 13 expect(e.keyCode).to.eq 13 expect(e.key).to.eq "Enter" e.preventDefault() cy.get("#input-types textarea").invoke("val", "foo").type("d{enter}").then ($textarea) -> expect($textarea).to.have.value("food") done() it "sets which and keyCode and charCode to 13 and prevents EOL insertion", (done) -> cy.$$("#input-types textarea").on "keypress", _.after 2, (e) -> expect(e.which).to.eq 13 expect(e.keyCode).to.eq 13 expect(e.charCode).to.eq 13 expect(e.key).to.eq "Enter" e.preventDefault() cy.get("#input-types textarea").invoke("val", "foo").type("d{enter}").then ($textarea) -> expect($textarea).to.have.value("food") done() it "does not fire textInput event", (done) -> cy.$$(":text:first").on "textInput", (e) -> done("textInput should not have fired") cy.get(":text:first").invoke("val", "ab").type("{enter}").then -> done() it "does not fire input event", (done) -> cy.$$(":text:first").on "input", (e) -> done("input should not have fired") cy.get(":text:first").invoke("val", "ab").type("{enter}").then -> done() it "inserts new line into textarea", -> cy.get("#input-types textarea").invoke("val", "foo").type("bar{enter}baz{enter}quux").then ($textarea) -> expect($textarea).to.have.value("foobar\nbaz\nquux") it "inserts new line into [contenteditable] ", -> cy.get("#input-types [contenteditable]:first").invoke("text", "foo") .type("bar{enter}baz{enter}{enter}{enter}quux").then ($div) -> expect($div.get(0).innerText).to.eql("foobar\nbaz\n\n\nquux\n") expect($div.get(0).textContent).to.eql("foobarbazquux") expect($div.get(0).innerHTML).to.eql("foobar<div>baz</div><div><br></div><div><br></div><div>quux</div>") it "inserts new line into [contenteditable] from midline", -> cy.get("#input-types [contenteditable]:first").invoke("text", "foo") .type("bar{leftarrow}{enter}baz{leftarrow}{enter}quux").then ($div) -> expect($div.get(0).innerText).to.eql("fooba\nba\nquuxzr\n") expect($div.get(0).textContent).to.eql("foobabaquuxzr") expect($div.get(0).innerHTML).to.eql("fooba<div>ba</div><div>quuxzr</div>") describe "modifiers", -> describe "activating modifiers", -> it "sends keydown event for modifiers in order", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy.get("input:text:first").type("{shift}{ctrl}").then -> expect(events[0].shiftKey).to.be.true expect(events[0].which).to.equal(16) expect(events[1].ctrlKey).to.be.true expect(events[1].which).to.equal(17) $input.off("keydown") done() it "maintains modifiers for subsequent characters", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy.get("input:text:first").type("{command}{control}ok").then -> expect(events[2].metaKey).to.be.true expect(events[2].ctrlKey).to.be.true expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.true expect(events[3].ctrlKey).to.be.true expect(events[3].which).to.equal(75) $input.off("keydown") done() it "does not maintain modifiers for subsequent type commands", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy .get("input:text:first") .type("{command}{control}") .type("ok") .then -> expect(events[2].metaKey).to.be.false expect(events[2].ctrlKey).to.be.false expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.false expect(events[3].ctrlKey).to.be.false expect(events[3].which).to.equal(75) $input.off("keydown") done() it "does not maintain modifiers for subsequent click commands", (done) -> $button = cy.$$("button:first") mouseDownEvent = null mouseUpEvent = null clickEvent = null $button.on "mousedown", (e)-> mouseDownEvent = e $button.on "mouseup", (e)-> mouseUpEvent = e $button.on "click", (e)-> clickEvent = e cy .get("input:text:first") .type("{cmd}{option}") .get("button:first").click().then -> expect(mouseDownEvent.metaKey).to.be.false expect(mouseDownEvent.altKey).to.be.false expect(mouseUpEvent.metaKey).to.be.false expect(mouseUpEvent.altKey).to.be.false expect(clickEvent.metaKey).to.be.false expect(clickEvent.altKey).to.be.false $button.off "mousedown" $button.off "mouseup" $button.off "click" done() it "sends keyup event for activated modifiers when typing is finished", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keyup", (e) -> events.push(e) cy .get("input:text:first") .type("{alt}{ctrl}{meta}{shift}ok") .then -> # first keyups should be for the chars typed, "ok" expect(events[0].which).to.equal(79) expect(events[1].which).to.equal(75) expect(events[2].which).to.equal(18) expect(events[3].which).to.equal(17) expect(events[4].which).to.equal(91) expect(events[5].which).to.equal(16) $input.off("keyup") done() describe "release: false", -> it "maintains modifiers for subsequent type commands", (done) -> $input = cy.$$("input:text:first") events = [] $input.on "keydown", (e) -> events.push(e) cy .get("input:text:first") .type("{command}{control}", { release: false }) .type("ok") .then -> expect(events[2].metaKey).to.be.true expect(events[2].ctrlKey).to.be.true expect(events[2].which).to.equal(79) expect(events[3].metaKey).to.be.true expect(events[3].ctrlKey).to.be.true expect(events[3].which).to.equal(75) done() it "maintains modifiers for subsequent click commands", (done) -> $button = cy.$$("button:first") mouseDownEvent = null mouseUpEvent = null clickEvent = null $button.on "mousedown", (e) -> mouseDownEvent = e $button.on "mouseup", (e) -> mouseUpEvent = e $button.on "click", (e) -> clickEvent = e cy .get("input:text:first") .type("{meta}{alt}", { release: false }) .get("button:first").click().then -> expect(mouseDownEvent.metaKey).to.be.true expect(mouseDownEvent.altKey).to.be.true expect(mouseUpEvent.metaKey).to.be.true expect(mouseUpEvent.altKey).to.be.true expect(clickEvent.metaKey).to.be.true expect(clickEvent.altKey).to.be.true done() it "resets modifiers before next test", -> ## this test will fail if you comment out ## $Keyboard.resetModifiers $input = cy.$$("input:text:first") events = [] $input.on "keyup", (e) -> events.push(e) cy .get("input:text:first") .type("a", { release: false }) .then -> expect(events[0].metaKey).to.be.false expect(events[0].ctrlKey).to.be.false expect(events[0].altKey).to.be.false describe "changing modifiers", -> beforeEach -> @$input = cy.$$("input:text:first") cy.get("input:text:first").type("{command}{option}", { release: false }) afterEach -> @$input.off("keydown") it "sends keydown event for new modifiers", (done) -> event = null @$input.on "keydown", (e)-> event = e cy.get("input:text:first").type("{shift}").then -> expect(event.shiftKey).to.be.true expect(event.which).to.equal(16) done() it "does not send keydown event for already activated modifiers", (done) -> triggered = false @$input.on "keydown", (e)-> triggered = true if e.which is 18 or e.which is 17 cy.get("input:text:first").type("{cmd}{alt}").then -> expect(triggered).to.be.false done() describe "case-insensitivity", -> it "special chars are case-insensitive", -> cy.get(":text:first").invoke("val", "bar").type("{leftarrow}{DeL}").then ($input) -> expect($input).to.have.value("ba") it "modifiers are case-insensitive", (done) -> $input = cy.$$("input:text:first") alt = false $input.on "keydown", (e) -> alt = true if e.altKey cy.get("input:text:first").type("{aLt}").then -> expect(alt).to.be.true $input.off("keydown") done() it "letters are case-sensitive", -> cy.get("input:text:first").type("FoO").then ($input) -> expect($input).to.have.value("FoO") describe "click events", -> it "passes timeout and interval down to click", (done) -> input = $("<input />").attr("id", "input-covered-in-span").prependTo(cy.$$("body")) span = $("<span>span on input</span>") .css { position: "absolute" left: input.offset().left top: input.offset().top padding: 5 display: "inline-block" backgroundColor: "yellow" } .prependTo cy.$$("body") cy.on "command:retry", (options) -> expect(options.timeout).to.eq 1000 expect(options.interval).to.eq 60 done() cy.get("#input-covered-in-span").type("foobar", {timeout: 1000, interval: 60}) it "does not issue another click event between type/type", -> clicked = 0 cy.$$(":text:first").click -> clicked += 1 cy.get(":text:first").type("f").type("o").then -> expect(clicked).to.eq 1 it "does not issue another click event if element is already in focus from click", -> clicked = 0 cy.$$(":text:first").click -> clicked += 1 cy.get(":text:first").click().type("o").then -> expect(clicked).to.eq 1 describe "change events", -> it "fires when enter is pressed and value has changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("bar{enter}").then -> expect(changed).to.eq 1 it "fires twice when enter is pressed and then again after losing focus", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("bar{enter}baz").blur().then -> expect(changed).to.eq 2 it "fires when element loses focus due to another action (click)", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 .get("button:first").click().then -> expect(changed).to.eq 1 it "fires when element loses focus due to another action (type)", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 .get("textarea:first").type("bar").then -> expect(changed).to.eq 1 it "fires when element is directly blurred", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").blur().then -> expect(changed).to.eq 1 it "fires when element is tabbed away from"#, -> # changed = 0 # cy.$$(":text:first").change -> # changed += 1 # cy.get(":text:first").invoke("val", "foo").type("b{tab}").then -> # expect(changed).to.eq 1 it "does not fire twice if element is already in focus between type/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("f").type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between clear/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").clear().type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between click/type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").click().type("o{enter}").then -> expect(changed).to.eq 1 it "does not fire twice if element is already in focus between type/click", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("d{enter}").click().then -> expect(changed).to.eq 1 it "does not fire at all between clear/type/click", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").clear().type("o").click().then ($el) -> expect(changed).to.eq 0 $el .blur() .then -> expect(changed).to.eq 1 it "does not fire if {enter} is preventedDefault", -> changed = 0 cy.$$(":text:first").keypress (e) -> e.preventDefault() if e.which is 13 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("b{enter}").then -> expect(changed).to.eq 0 it "does not fire when enter is pressed and value hasnt changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.get(":text:first").invoke("val", "foo").type("b{backspace}{enter}").then -> expect(changed).to.eq 0 it "does not fire at the end of the type", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").type("foo").then -> expect(changed).to.eq 0 it "does not fire change event if value hasnt actually changed", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy .get(":text:first").invoke("val", "foo").type("{backspace}{backspace}oo{enter}").blur().then -> expect(changed).to.eq 0 it "does not fire if mousedown is preventedDefault which prevents element from losing focus", -> changed = 0 cy.$$(":text:first").change -> changed += 1 cy.$$("textarea:first").mousedown -> return false cy .get(":text:first").invoke("val", "foo").type("bar") .get("textarea:first").click().then -> expect(changed).to.eq 0 it "does not fire hitting {enter} inside of a textarea", -> changed = 0 cy.$$("textarea:first").change -> changed += 1 cy .get("textarea:first").type("foo{enter}bar").then -> expect(changed).to.eq 0 it "does not fire hitting {enter} inside of [contenteditable]", -> changed = 0 cy.$$("[contenteditable]:first").change -> changed += 1 cy .get("[contenteditable]:first").type("foo{enter}bar").then -> expect(changed).to.eq 0 ## [contenteditable] does not fire ANY change events ever. it "does not fire at ALL for [contenteditable]", -> changed = 0 cy.$$("[contenteditable]:first").change -> changed += 1 cy .get("[contenteditable]:first").type("foo") .get("button:first").click().then -> expect(changed).to.eq 0 it "does not fire on .clear() without blur", -> changed = 0 cy.$$("input:first").change -> changed += 1 cy.get("input:first").invoke('val', 'foo') .clear() .then ($el) -> expect(changed).to.eq 0 $el .type('foo') .blur() .then -> expect(changed).to.eq 0 it "fires change for single value change inputs", -> changed = 0 cy.$$('input[type="date"]:first').change -> changed++ cy.get('input[type="date"]:first') .type("1959-09-13") .blur() .then -> expect(changed).to.eql 1 it "does not fire change for non-change single value input", -> changed = 0 cy.$$('input[type="date"]:first').change -> changed++ cy.get('input[type="date"]:first') .invoke('val', "1959-09-13") .type("1959-09-13") .blur() .then -> expect(changed).to.eql(0) it "does not fire change for type'd change that restores value", -> changed = 0 cy.$$('input:first').change -> changed++ cy.get('input:first') .invoke('val', 'foo') .type('{backspace}o') .invoke('val', 'bar') .type('{backspace}r') .blur() .then -> expect(changed).to.eql 0 describe "caret position", -> it "respects being formatted by input event handlers" it "can arrow from maxlength", -> cy.get('input:first').invoke('attr', 'maxlength', "5").type('foobar{leftarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:4, end:4}) it "won't arrowright past length", -> cy.get('input:first').type('foo{rightarrow}{rightarrow}{rightarrow}bar{rightarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:6, end:6}) it "won't arrowleft before word", -> cy.get('input:first').type('oo' + '{leftarrow}{leftarrow}{leftarrow}' + 'f' + '{leftarrow}'.repeat(5)) cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('input:first').get(0) .to.deep.eq({start:0, end:0}) it "leaves caret at the end of contenteditable", -> cy.get('[contenteditable]:first').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:6, end:6}) it "leaves caret at the end of contenteditable when prefilled", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'foo' cy.get('[contenteditable]:first').type('bar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:6, end:6}) it "can move the caret left on contenteditable", -> cy.get('[contenteditable]:first').type('foo{leftarrow}{leftarrow}') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('[contenteditable]:first').get(0) .to.deep.eq({start:1, end:1}) ##make sure caret is correct ## type left left ## make sure caret correct ## text is fboo ## fix input-mask issue it "leaves caret at the end of input", -> cy.get(':text:first').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$(':text:first').get(0) .to.deep.eq({start:6, end:6}) it "leaves caret at the end of textarea", -> cy.get('#comments').type('foobar') cy.window().then (win) -> expect $selection.getSelectionBounds Cypress.$('#comments').get(0) .to.deep.eq({start:6, end:6}) it "can wrap cursor to next line in [contenteditable] with {rightarrow}", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'start'+ '<div>middle</div>'+ '<div>end</div>' cy.get('[contenteditable]:first') ## move cursor to beginning of div .type('{selectall}{leftarrow}') .type('{rightarrow}'.repeat(14)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('start\nmiddle\ne[_I_]nd\n') it "can wrap cursor to prev line in [contenteditable] with {leftarrow}", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = 'start'+ '<div>middle</div>'+ '<div>end</div>' cy.get('[contenteditable]:first').type('{leftarrow}'.repeat(12)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('star[_I_]t\nmiddle\nend\n') it "can wrap cursor to next line in [contenteditable] with {rightarrow} and empty lines", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = '<div><br></div>'.repeat(4)+ '<div>end</div>' cy.get('[contenteditable]:first') .type('{selectall}{leftarrow}') # .type('foobar'+'{rightarrow}'.repeat(6)+'[_I_]').then -> # expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('foobar\n\n\n\nen[_I_]d\n') it "can use {rightarrow} and nested elements", -> $el = cy.$$('[contenteditable]:first') el = $el.get(0) el.innerHTML = '<div><b>s</b>ta<b>rt</b></div>' cy.get('[contenteditable]:first') .type('{selectall}{leftarrow}') .type('{rightarrow}'.repeat(3)+'[_I_]').then -> expect(cy.$$('[contenteditable]:first').get(0).innerText).to.eql('sta[_I_]rt\n') it "enter and \\n should act the same for [contenteditable]", -> cleanseText = (text) -> text.replace(/ /g, ' ') expectMatchInnerText = ($el , innerText) -> expect(cleanseText($el.get(0).innerText)).to.eql(innerText) ## NOTE: this may only pass in Chrome since the whitespace may be different in other browsers ## even if actual and expected appear the same. expected = "{\n foo: 1\n bar: 2\n baz: 3\n}\n" cy.get('[contenteditable]:first') .invoke('html', '<div><br></div>') .type('{{}{enter} foo: 1{enter} bar: 2{enter} baz: 3{enter}}') .should ($el) -> expectMatchInnerText($el, expected) .clear() .type('{{}\n foo: 1\n bar: 2\n baz: 3\n}') .should ($el) -> expectMatchInnerText($el, expected) it "enter and \\n should act the same for textarea", -> expected = "{\n foo: 1\n bar: 2\n baz: 3\n}" cy.get('textarea:first') .clear() .type('{{}{enter} foo: 1{enter} bar: 2{enter} baz: 3{enter}}') .should('have.prop', 'value', expected) .clear() .type('{{}\n foo: 1\n bar: 2\n baz: 3\n}') .should('have.prop', 'value', expected) describe "{enter}", -> beforeEach -> @$forms = cy.$$("#form-submits") context "1 input, no 'submit' elements", -> it "triggers form submit", (done) -> @foo = {} @$forms.find("#single-input").submit (e) -> e.preventDefault() done() cy.get("#single-input input").type("foo{enter}") it "triggers form submit synchronously before type logs or resolves", -> events = [] cy.on "command:start", (cmd) -> events.push "#{cmd.get('name')}:start" @$forms.find("#single-input").submit (e) -> e.preventDefault() events.push "submit" cy.on "log:added", (attrs, log) -> state = log.get("state") if state is "pending" log.on "state:changed", (state) -> events.push "#{log.get('name')}:log:#{state}" events.push "#{log.get('name')}:log:#{state}" cy.on "command:end", (cmd) -> events.push "#{cmd.get('name')}:end" cy.get("#single-input input").type("f{enter}").then -> expect(events).to.deep.eq [ "get:start", "get:log:pending", "get:end", "type:start", "type:log:pending", "submit", "type:end", "then:start" ] it "triggers 2 form submit event", -> submits = 0 @$forms.find("#single-input").submit (e) -> e.preventDefault() submits += 1 cy.get("#single-input input").type("f{enter}{enter}").then -> expect(submits).to.eq 2 it "does not submit when keydown is defaultPrevented on input", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("input").keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keydown is defaultPrevented on wrapper", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("div").keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keydown is defaultPrevented on form", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.keydown (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on input", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on wrapper", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.find("div").keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() it "does not submit when keypress is defaultPrevented on form", (done) -> form = @$forms.find("#single-input").submit -> done("err: should not have submitted") form.keypress (e) -> e.preventDefault() cy.get("#single-input input").type("f").type("f{enter}").then -> done() context "2 inputs, no 'submit' elements", -> it "does not trigger submit event", (done) -> form = @$forms.find("#no-buttons").submit -> done("err: should not have submitted") cy.get("#no-buttons input:first").type("f").type("{enter}").then -> done() context "2 inputs, no 'submit' elements but 1 button[type=button]", -> it "does not trigger submit event", (done) -> form = @$forms.find("#one-button-type-button").submit -> done("err: should not have submitted") cy.get("#one-button-type-button input:first").type("f").type("{enter}").then -> done() context "2 inputs, 1 'submit' element input[type=submit]", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-input-submit").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-input-submit input:first").type("foo{enter}") it "causes click event on the input[type=submit]", (done) -> @$forms.find("#multiple-inputs-and-input-submit input[type=submit]").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-input-submit input:first").type("foo{enter}") it "does not cause click event on the input[type=submit] if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-input-submit").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-input-submit input:first").type("f{enter}").then -> done() context "2 inputs, 1 'submit' element button[type=submit]", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-button-submit").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-submit input:first").type("foo{enter}") it "causes click event on the button[type=submit]", (done) -> @$forms.find("#multiple-inputs-and-button-submit button[type=submit]").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-submit input:first").type("foo{enter}") it "does not cause click event on the button[type=submit] if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-button-submit").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-button-submit input:first").type("f{enter}").then -> done() context "2 inputs, 1 'submit' element button", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-button-with-no-type").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("foo{enter}") it "causes click event on the button", (done) -> @$forms.find("#multiple-inputs-and-button-with-no-type button").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("foo{enter}") it "does not cause click event on the button if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-button-with-no-type").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-button-with-no-type input:first").type("f{enter}").then -> done() context "2 inputs, 2 'submit' elements", -> it "triggers form submit", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits").submit (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}") it "causes click event on the button", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits button").click (e) -> e.preventDefault() done() cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}") it "does not cause click event on the button if keydown is defaultPrevented on input", (done) -> form = @$forms.find("#multiple-inputs-and-multiple-submits").submit -> done("err: should not have submitted") form.find("input").keypress (e) -> e.preventDefault() cy.get("#multiple-inputs-and-multiple-submits input:first").type("f{enter}").then -> done() context "disabled default button", -> beforeEach -> @$forms.find("#multiple-inputs-and-multiple-submits").find("button").prop("disabled", true) it "will not receive click event", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits button").click -> done("err: should not receive click event") cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}").then -> done() it "will not submit the form", (done) -> @$forms.find("#multiple-inputs-and-multiple-submits").submit -> done("err: should not receive submit event") cy.get("#multiple-inputs-and-multiple-submits input:first").type("foo{enter}").then -> done() describe "assertion verification", -> beforeEach -> cy.on "log:added", (attrs, log) => if log.get("name") is "assert" @lastLog = log return null it "eventually passes the assertion", -> cy.$$("input:first").keyup -> _.delay => $(@).addClass("typed") , 100 cy.get("input:first").type("f").should("have.class", "typed").then -> lastLog = @lastLog expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("passed") expect(lastLog.get("ended")).to.be.true describe ".log", -> beforeEach -> cy.on "log:added", (attrs, log) => @lastLog = log return null it "passes in $el", -> cy.get("input:first").type("foobar").then ($input) -> lastLog = @lastLog expect(lastLog.get("$el")).to.eq $input it "logs message", -> cy.get(":text:first").type("foobar").then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foobar" it "logs delay arguments", -> cy.get(":text:first").type("foo", {delay: 20}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foo, {delay: 20}" it "clones textarea value after the type happens", -> expectToHaveValueAndCoords = => cmd = cy.queue.find({name: "type"}) log = cmd.get("logs")[0] txt = log.get("snapshots")[1].body.find("#comments") expect(txt).to.have.value("foobarbaz") expect(log.get("coords")).to.be.ok cy .get("#comments").type("foobarbaz").then ($txt) -> expectToHaveValueAndCoords() .get("#comments").clear().type("onetwothree").then -> expectToHaveValueAndCoords() it "clones textarea value when textarea is focused first", -> expectToHaveValueAndNoCoords = => cmd = cy.queue.find({name: "type"}) log = cmd.get("logs")[0] txt = log.get("snapshots")[1].body.find("#comments") expect(txt).to.have.value("foobarbaz") expect(log.get("coords")).not.to.be.ok cy .get("#comments").focus().type("foobarbaz").then ($txt) -> expectToHaveValueAndNoCoords() .get("#comments").clear().type("onetwothree").then -> expectToHaveValueAndNoCoords() it "logs only one type event", -> logs = [] types = [] cy.on "log:added", (attrs, log) -> logs.push(log) if log.get("name") is "type" types.push(log) cy.get(":text:first").type("foo").then -> expect(logs.length).to.eq(2) expect(types.length).to.eq(1) it "logs immediately before resolving", -> $txt = cy.$$(":text:first") expected = false cy.on "log:added", (attrs, log) -> if log.get("name") is "type" expect(log.get("state")).to.eq("pending") expect(log.get("$el").get(0)).to.eq $txt.get(0) expected = true cy.get(":text:first").type("foo").then -> cy.get(":text:first").type("foo") it "snapshots before typing", -> expected = false cy.$$(":text:first").one "keydown", => lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(1) expect(lastLog.get("snapshots")[0].name).to.eq("before") expect(lastLog.get("snapshots")[0].body).to.be.an("object") expected = true cy.get(":text:first").type("foo").then -> expect(expected).to.be.true it "snapshots after typing", -> cy.get(":text:first").type("foo").then -> lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(2) expect(lastLog.get("snapshots")[1].name).to.eq("after") expect(lastLog.get("snapshots")[1].body).to.be.an("object") it "logs deltaOptions", -> cy.get(":text:first").type("foo", {force: true, timeout: 1000}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "foo, {force: true, timeout: 1000}" expect(lastLog.invoke("consoleProps").Options).to.deep.eq {force: true, timeout: 1000} context "#consoleProps", -> it "has all of the regular options", -> cy.get("input:first").type("foobar").then ($input) -> { fromWindow } = Cypress.dom.getElementCoordinatesByPosition($input) console = @lastLog.invoke("consoleProps") expect(console.Command).to.eq("type") expect(console.Typed).to.eq("foobar") expect(console["Applied To"]).to.eq $input.get(0) expect(console.Coords.x).to.be.closeTo(fromWindow.x, 1) expect(console.Coords.y).to.be.closeTo(fromWindow.y, 1) it "has a table of keys", -> cy.get(":text:first").type("{cmd}{option}foo{enter}b{leftarrow}{del}{enter}").then -> table = @lastLog.invoke("consoleProps").table() console.table(table.data, table.columns) expect(table.columns).to.deep.eq [ "typed", "which", "keydown", "keypress", "textInput", "input", "keyup", "change", "modifiers" ] expect(table.name).to.eq "Key Events Table" expectedTable = { 1: {typed: "<meta>", which: 91, keydown: true, modifiers: "meta"} 2: {typed: "<alt>", which: 18, keydown: true, modifiers: "alt, meta"} 3: {typed: "f", which: 70, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 4: {typed: "o", which: 79, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 5: {typed: "o", which: 79, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 6: {typed: "{enter}", which: 13, keydown: true, keypress: true, keyup: true, change: true, modifiers: "alt, meta"} 7: {typed: "b", which: 66, keydown: true, keypress: true, textInput: true, input: true, keyup: true, modifiers: "alt, meta"} 8: {typed: "{leftarrow}", which: 37, keydown: true, keyup: true, modifiers: "alt, meta"} 9: {typed: "{del}", which: 46, keydown: true, input: true, keyup: true, modifiers: "alt, meta"} 10: {typed: "{enter}", which: 13, keydown: true, keypress: true, keyup: true, modifiers: "alt, meta"} } for i in [1..10] expect(table.data[i]).to.deep.eq(expectedTable[i]) # table.data.forEach (item, i) -> # expect(item).to.deep.eq(expectedTable[i]) # expect(table.data).to.deep.eq(expectedTable) it "has no modifiers when there are none activated", -> cy.get(":text:first").type("f").then -> table = @lastLog.invoke("consoleProps").table() expect(table.data).to.deep.eq { 1: {typed: "f", which: 70, keydown: true, keypress: true, textInput: true, input: true, keyup: true} } it "has a table of keys with preventedDefault", -> cy.$$(":text:first").keydown -> return false cy.get(":text:first").type("f").then -> table = @lastLog.invoke("consoleProps").table() console.table(table.data, table.columns) expect(table.data).to.deep.eq { 1: {typed: "f", which: 70, keydown: "preventedDefault", keyup: true} } describe "errors", -> beforeEach -> Cypress.config("defaultCommandTimeout", 100) @logs = [] cy.on "log:added", (attrs, log) => @lastLog = log @logs.push(log) return null it "throws when not a dom subject", (done) -> cy.on "fail", -> done() cy.noop({}).type("foo") it "throws when subject is not in the document", (done) -> typed = 0 input = cy.$$("input:first").keypress (e) -> typed += 1 input.remove() cy.on "fail", (err) -> expect(typed).to.eq 1 expect(err.message).to.include "cy.type() failed because this element" done() cy.get("input:first").type("a").type("b") it "throws when not textarea or text-like", (done) -> cy.get("form").type("foo") cy.on "fail", (err) -> expect(err.message).to.include "cy.type() failed because it requires a valid typeable element." expect(err.message).to.include "The element typed into was:" expect(err.message).to.include "<form id=\"by-id\">...</form>" expect(err.message).to.include "Cypress considers the 'body', 'textarea', any 'element' with a 'tabindex' or 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid typeable elements." done() it "throws when subject is a collection of elements", (done) -> cy.get("textarea,:text").then ($inputs) -> @num = $inputs.length return $inputs .type("foo") cy.on "fail", (err) => expect(err.message).to.include "cy.type() can only be called on a single element. Your subject contained #{@num} elements." done() it "throws when the subject isnt visible", (done) -> input = cy.$$("input:text:first").show().hide() cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(2) expect(lastLog.get("error")).to.eq(err) expect(err.message).to.include "cy.type() failed because this element is not visible" done() cy.get("input:text:first").type("foo") it "throws when subject is disabled", (done) -> cy.$$("input:text:first").prop("disabled", true) cy.on "fail", (err) => ## get + type logs expect(@logs.length).eq(2) expect(err.message).to.include("cy.type() failed because this element is disabled:\n") done() cy.get("input:text:first").type("foo") it "throws when submitting within nested forms" it "logs once when not dom subject", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(1) expect(lastLog.get("error")).to.eq(err) done() cy.type("foobar") it "throws when input cannot be clicked", (done) -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on button</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.include "cy.type() failed because this element" expect(err.message).to.include "is being covered by another element" done() cy.get("#input-covered-in-span").type("foo") it "throws when special characters dont exist", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 allChars = _.keys(Keyboard.specialChars).concat(_.keys(Keyboard.modifierChars)).join(", ") expect(err.message).to.eq "Special character sequence: '{bar}' is not recognized. Available sequences are: #{allChars}" done() cy.get(":text:first").type("foo{bar}") it "throws when attemping to type tab", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "{tab} isn't a supported character sequence. You'll want to use the command cy.tab(), which is not ready yet, but when it is done that's what you'll use." done() cy.get(":text:first").type("foo{tab}") it "throws on an empty string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "cy.type() cannot accept an empty String. You need to actually type something." done() cy.get(":text:first").type("") it "allows typing spaces", -> cy .get(":text:first").type(" ") .should("have.value", " ") it "can type into input with invalid type attribute", -> cy.get(':text:first') .invoke('attr', 'type', 'asdf') .type('foobar') .should('have.value', 'foobar') _.each [NaN, Infinity, [], {}, null, undefined], (val) => it "throws when trying to type: #{val}", (done) -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) cy.on "fail", (err) => expect(@logs.length).to.eq 2 expect(err.message).to.eq "cy.type() can only accept a String or Number. You passed in: '#{val}'" done() cy.get(":text:first").type(val) it "throws when type is cancelled by preventingDefault mousedown" it "throws when element animation exceeds timeout", (done) -> ## force the animation calculation to think we moving at a huge distance ;-) cy.stub(Cypress.utils, "getDistanceBetween").returns(100000) keydowns = 0 cy.$$(":text:first").on "keydown", -> keydowns += 1 cy.on "fail", (err) -> expect(keydowns).to.eq(0) expect(err.message).to.include("cy.type() could not be issued because this element is currently animating:\n") done() cy.get(":text:first").type("foo") it "eventually fails the assertion", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(err.message).to.include(lastLog.get("error").message) expect(err.message).not.to.include("undefined") expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("failed") expect(lastLog.get("error")).to.be.an.instanceof(chai.AssertionError) done() cy.get("input:first").type("f").should("have.class", "typed") it "does not log an additional log on failure", (done) -> cy.on "fail", => expect(@logs.length).to.eq(3) done() cy.get("input:first").type("f").should("have.class", "typed") context "[type=date]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 1989") done() cy.get("#date-without-value").type(1989) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 01-01-1989") done() cy.get("#date-without-value").type("01-01-1989") it "throws when chars is invalid date", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a date input with cy.type() requires a valid date with the format 'yyyy-MM-dd'. You passed: 1989-04-31") done() cy.get("#date-without-value").type("1989-04-31") context "[type=month]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 6") done() cy.get("#month-without-value").type(6) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 01/2000") done() cy.get("#month-without-value").type("01/2000") it "throws when chars is invalid month", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a month input with cy.type() requires a valid month with the format 'yyyy-MM'. You passed: 1989-13") done() cy.get("#month-without-value").type("1989-13") context "[type=tel]", -> it "can edit tel", -> cy.get('#by-name > input[type="tel"]') .type('1234567890') .should('have.prop', 'value', '1234567890') # it "throws when chars is invalid format", (done) -> # cy.on "fail", (err) => # expect(@logs.length).to.eq(2) # expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 2005/W18") # done() context "[type=week]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 23") done() cy.get("#week-without-value").type(23) it "throws when chars is invalid format", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 2005/W18") done() cy.get("#week-without-value").type("2005/W18") it "throws when chars is invalid week", (done) -> cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.eq("Typing into a week input with cy.type() requires a valid week with the format 'yyyy-Www', where W is the literal character 'W' and ww is the week number (00-53). You passed: 1995-W60") done() cy.get("#week-without-value").type("1995-W60") context "[type=time]", -> it "throws when chars is not a string", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 9999") done() cy.get("#time-without-value").type(9999) it "throws when chars is invalid format (1:30)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 1:30") done() cy.get("#time-without-value").type("1:30") it "throws when chars is invalid format (01:30pm)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:30pm") done() cy.get("#time-without-value").type("01:30pm") it "throws when chars is invalid format (01:30:30.3333)", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:30:30.3333") done() cy.get("#time-without-value").type("01:30:30.3333") it "throws when chars is invalid time", (done) -> cy.on "fail", (err) => expect(@logs.length).to.equal(2) expect(err.message).to.equal("Typing into a time input with cy.type() requires a valid time with the format 'HH:mm', 'HH:mm:ss' or 'HH:mm:ss.SSS', where HH is 00-23, mm is 00-59, ss is 00-59, and SSS is 000-999. You passed: 01:60") done() cy.get("#time-without-value").type("01:60") context "#clear", -> it "does not change the subject", -> textarea = cy.$$("textarea") cy.get("textarea").clear().then ($textarea) -> expect($textarea).to.match textarea it "removes the current value", -> textarea = cy.$$("#comments") textarea.val("foo bar") ## make sure it really has that value first expect(textarea).to.have.value("foo bar") cy.get("#comments").clear().then ($textarea) -> expect($textarea).to.have.value("") it "waits until element is no longer disabled", -> textarea = cy.$$("#comments").val("foo bar").prop("disabled", true) retried = false clicks = 0 textarea.on "click", -> clicks += 1 cy.on "command:retry", _.after 3, -> textarea.prop("disabled", false) retried = true cy.get("#comments").clear().then -> expect(clicks).to.eq(1) expect(retried).to.be.true it "can forcibly click even when being covered by another element", -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) clicked = false $input.on "click", -> clicked = true cy.get("#input-covered-in-span").clear({force: true}).then -> expect(clicked).to.be.true it "passes timeout and interval down to click", (done) -> input = $("<input />").attr("id", "input-covered-in-span").prependTo(cy.$$("body")) span = $("<span>span on input</span>").css(position: "absolute", left: input.offset().left, top: input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow").prependTo(cy.$$("body")) cy.on "command:retry", (options) -> expect(options.timeout).to.eq 1000 expect(options.interval).to.eq 60 done() cy.get("#input-covered-in-span").clear({timeout: 1000, interval: 60}) context "works on input type", -> inputTypes = [ "date", "datetime", "datetime-local", "email", "month", "number", "password", "search", "tel", "text", "time", "url", "week" ] inputTypes.forEach (type) -> it type, -> cy.get("##{type}-with-value").clear().then ($input) -> expect($input.val()).to.equal("") describe "assertion verification", -> beforeEach -> cy.on "log:added", (attrs, log) => if log.get("name") is "assert" @lastLog = log return null it "eventually passes the assertion", -> cy.$$("input:first").keyup -> _.delay => $(@).addClass("cleared") , 100 cy.get("input:first").clear().should("have.class", "cleared").then -> lastLog = @lastLog expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("passed") expect(lastLog.get("ended")).to.be.true it "eventually passes the assertion on multiple inputs", -> cy.$$("input").keyup -> _.delay => $(@).addClass("cleared") , 100 cy.get("input").invoke("slice", 0, 2).clear().should("have.class", "cleared") describe "errors", -> beforeEach -> Cypress.config("defaultCommandTimeout", 100) @logs = [] cy.on "log:added", (attrs, log) => @lastLog = log @logs.push(log) return null it "throws when not a dom subject", (done) -> cy.on "fail", (err) -> done() cy.noop({}).clear() it "throws when subject is not in the document", (done) -> cleared = 0 input = cy.$$("input:first").val("123").keydown (e) -> cleared += 1 input.remove() cy.on "fail", (err) -> expect(cleared).to.eq 1 expect(err.message).to.include "cy.clear() failed because this element" done() cy.get("input:first").clear().clear() it "throws if any subject isnt a textarea or text-like", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(3) expect(lastLog.get("error")).to.eq(err) expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<form id=\"checkboxes\">...</form>" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get("textarea:first,form#checkboxes").clear() it "throws if any subject isnt a :text", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<div id=\"dom\">...</div>" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get("div").clear() it "throws on an input radio", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<input type=\"radio\" name=\"gender\" value=\"male\">" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get(":radio").clear() it "throws on an input checkbox", (done) -> cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because it requires a valid clearable element." expect(err.message).to.include "The element cleared was:" expect(err.message).to.include "<input type=\"checkbox\" name=\"colors\" value=\"blue\">" expect(err.message).to.include "Cypress considers a 'textarea', any 'element' with a 'contenteditable' attribute, or any 'input' with a 'type' attribute of 'text', 'password', 'email', 'number', 'date', 'week', 'month', 'time', 'datetime', 'datetime-local', 'search', 'url', or 'tel' to be valid clearable elements." done() cy.get(":checkbox").clear() it "throws when the subject isnt visible", (done) -> input = cy.$$("input:text:first").show().hide() cy.on "fail", (err) -> expect(err.message).to.include "cy.clear() failed because this element is not visible" done() cy.get("input:text:first").clear() it "throws when subject is disabled", (done) -> cy.$$("input:text:first").prop("disabled", true) cy.on "fail", (err) => ## get + type logs expect(@logs.length).eq(2) expect(err.message).to.include("cy.clear() failed because this element is disabled:\n") done() cy.get("input:text:first").clear() it "logs once when not dom subject", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(@logs.length).to.eq(1) expect(lastLog.get("error")).to.eq(err) done() cy.clear() it "throws when input cannot be cleared", (done) -> $input = $("<input />") .attr("id", "input-covered-in-span") .prependTo(cy.$$("body")) $span = $("<span>span on input</span>") .css({ position: "absolute", left: $input.offset().left, top: $input.offset().top, padding: 5, display: "inline-block", backgroundColor: "yellow" }) .prependTo(cy.$$("body")) cy.on "fail", (err) => expect(@logs.length).to.eq(2) expect(err.message).to.include "cy.clear() failed because this element" expect(err.message).to.include "is being covered by another element" done() cy.get("#input-covered-in-span").clear() it "eventually fails the assertion", (done) -> cy.on "fail", (err) => lastLog = @lastLog expect(err.message).to.include(lastLog.get("error").message) expect(err.message).not.to.include("undefined") expect(lastLog.get("name")).to.eq("assert") expect(lastLog.get("state")).to.eq("failed") expect(lastLog.get("error")).to.be.an.instanceof(chai.AssertionError) done() cy.get("input:first").clear().should("have.class", "cleared") it "does not log an additional log on failure", (done) -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) cy.on "fail", => expect(@logs.length).to.eq(3) done() cy.get("input:first").clear().should("have.class", "cleared") describe ".log", -> beforeEach -> cy.on "log:added", (attrs, log) => @lastLog = log return null it "logs immediately before resolving", -> $input = cy.$$("input:first") expected = false cy.on "log:added", (attrs, log) -> if log.get("name") is "clear" expect(log.get("state")).to.eq("pending") expect(log.get("$el").get(0)).to.eq $input.get(0) expected = true cy.get("input:first").clear().then -> expect(expected).to.be.true it "ends", -> logs = [] cy.on "log:added", (attrs, log) -> logs.push(log) if log.get("name") is "clear" cy.get("input").invoke("slice", 0, 2).clear().then -> _.each logs, (log) -> expect(log.get("state")).to.eq("passed") expect(log.get("ended")).to.be.true it "snapshots after clicking", -> cy.get("input:first").clear().then ($input) -> lastLog = @lastLog expect(lastLog.get("snapshots").length).to.eq(1) expect(lastLog.get("snapshots")[0]).to.be.an("object") it "logs deltaOptions", -> cy.get("input:first").clear({force: true, timeout: 1000}).then -> lastLog = @lastLog expect(lastLog.get("message")).to.eq "{force: true, timeout: 1000}" expect(lastLog.invoke("consoleProps").Options).to.deep.eq {force: true, timeout: 1000}
[ { "context": " password) ->\n ephemeralStorage.storePassword = password\n if err?\n logger(\"Unexpected error return", "end": 574, "score": 0.9979674220085144, "start": 566, "tag": "PASSWORD", "value": "password" } ]
src/js/extension/ux/index.coffee
obi1kenobi/jester
2
logger = require('../../lib/util/logging').logger(['ext', 'ux', 'index']) constants = require('../../lib/config/constants') sender = require('../messaging/ui/sender') unauthTimer = require('./tools/unauth_timer') ephemeralStorage = require('./tools/ephemeral_storage') popupAuth = require('./auth') popupProfiles = require('./profiles') popupAddNew = require('./addnew') main = () -> setupAutoUnauth() popupAuth.setup (err, password) -> ephemeralStorage.storePassword = password if err? logger("Unexpected error returned from auth setup", err) return $('#jester-loading').removeClass('hidden') setupTabs() popupAddNew.setup() popupProfiles.setup (err, res) -> if err? logger("Unexpected error returned from profile setup", err) return $('#jester-loading').addClass('hidden') $('#jester-authed').removeClass('hidden') setupTabs = () -> deselectAddNewSelectors = () -> $('#addnew-selector').children().removeClass('active') $('#addnew-creds').addClass('hidden') $('#tabhead-home').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-profiles').removeClass('hidden') deselectAddNewSelectors() $('#tabhead-addnew').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-addnew').removeClass('hidden') $('#tabhead-about').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-about').removeClass('hidden') deselectAddNewSelectors() setupAutoUnauth = () -> chrome.tabs.getCurrent (tab) -> if !tab.id? logger("Unexpectedly got tab with no id") return unauthTimer.setup(tab.id) $(document).ready(main)
65048
logger = require('../../lib/util/logging').logger(['ext', 'ux', 'index']) constants = require('../../lib/config/constants') sender = require('../messaging/ui/sender') unauthTimer = require('./tools/unauth_timer') ephemeralStorage = require('./tools/ephemeral_storage') popupAuth = require('./auth') popupProfiles = require('./profiles') popupAddNew = require('./addnew') main = () -> setupAutoUnauth() popupAuth.setup (err, password) -> ephemeralStorage.storePassword = <PASSWORD> if err? logger("Unexpected error returned from auth setup", err) return $('#jester-loading').removeClass('hidden') setupTabs() popupAddNew.setup() popupProfiles.setup (err, res) -> if err? logger("Unexpected error returned from profile setup", err) return $('#jester-loading').addClass('hidden') $('#jester-authed').removeClass('hidden') setupTabs = () -> deselectAddNewSelectors = () -> $('#addnew-selector').children().removeClass('active') $('#addnew-creds').addClass('hidden') $('#tabhead-home').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-profiles').removeClass('hidden') deselectAddNewSelectors() $('#tabhead-addnew').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-addnew').removeClass('hidden') $('#tabhead-about').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-about').removeClass('hidden') deselectAddNewSelectors() setupAutoUnauth = () -> chrome.tabs.getCurrent (tab) -> if !tab.id? logger("Unexpectedly got tab with no id") return unauthTimer.setup(tab.id) $(document).ready(main)
true
logger = require('../../lib/util/logging').logger(['ext', 'ux', 'index']) constants = require('../../lib/config/constants') sender = require('../messaging/ui/sender') unauthTimer = require('./tools/unauth_timer') ephemeralStorage = require('./tools/ephemeral_storage') popupAuth = require('./auth') popupProfiles = require('./profiles') popupAddNew = require('./addnew') main = () -> setupAutoUnauth() popupAuth.setup (err, password) -> ephemeralStorage.storePassword = PI:PASSWORD:<PASSWORD>END_PI if err? logger("Unexpected error returned from auth setup", err) return $('#jester-loading').removeClass('hidden') setupTabs() popupAddNew.setup() popupProfiles.setup (err, res) -> if err? logger("Unexpected error returned from profile setup", err) return $('#jester-loading').addClass('hidden') $('#jester-authed').removeClass('hidden') setupTabs = () -> deselectAddNewSelectors = () -> $('#addnew-selector').children().removeClass('active') $('#addnew-creds').addClass('hidden') $('#tabhead-home').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-profiles').removeClass('hidden') deselectAddNewSelectors() $('#tabhead-addnew').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-addnew').removeClass('hidden') $('#tabhead-about').click () -> unauthTimer.reset() $(this).siblings().removeClass('active') $(this).addClass('active') $(this).parent().siblings('.tab').addClass('hidden') $('#tab-about').removeClass('hidden') deselectAddNewSelectors() setupAutoUnauth = () -> chrome.tabs.getCurrent (tab) -> if !tab.id? logger("Unexpectedly got tab with no id") return unauthTimer.setup(tab.id) $(document).ready(main)
[ { "context": "oid creating many time the same geometry\n# @author David Ronai / http://makiopolis.com / @makio64\n#\nclass Cache3", "end": 79, "score": 0.9998657703399658, "start": 68, "tag": "NAME", "value": "David Ronai" }, { "context": "ry\n# @author David Ronai / http://makiopoli...
src/coffee/makio/3d/Cache3d.coffee
Makio64/pizzaparty_vj
1
# # Cache3D to avoid creating many time the same geometry # @author David Ronai / http://makiopolis.com / @makio64 # class Cache3D @caches : {} @plane = (w=1,h=1,segment=1,rotationX=0)=> if(!@caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"]) geo = new THREE.PlaneBufferGeometry( w, h, segment, segment ) if(rotationX!=0) m = new THREE.Matrix4 m.makeRotationX(rotationX) geo.applyMatrix(m) @caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"] = geo return @caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"] @cube = (w=1,h=1,d=1)=> if(!@caches["cube_#{w}_#{h}_#{d}"]) @caches["cube_#{w}_#{h}_#{d}"] = new THREE.CubeGeometry( w, h, d ) return @caches["cube_#{w}_#{h}_#{d}"] @sphere = (r=1,ws=8,hs=8,phi=0,phiLength=Math.PI*2,theta=0,thetaLength=Math.PI)=> if(!@caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"]) @caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"] = new THREE.SphereGeometry( r, ws, hs, phi, phiLength, theta, thetaLength ) return @caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"] @cylinder = (radiusTop=1, radiusBottom=1, height=1, radiusSegments=8, heightSegments=1, openEnded=false) => if(!@caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"]) @caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"] = new THREE.CylinderGeometry( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) return @caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"] # TODO Other Geometry disposeAll = ()=> for key of @caches @caches[key].dispose() @caches = {} return module.exports = Cache3D
105218
# # Cache3D to avoid creating many time the same geometry # @author <NAME> / http://makiopolis.com / @makio64 # class Cache3D @caches : {} @plane = (w=1,h=1,segment=1,rotationX=0)=> if(!@caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"]) geo = new THREE.PlaneBufferGeometry( w, h, segment, segment ) if(rotationX!=0) m = new THREE.Matrix4 m.makeRotationX(rotationX) geo.applyMatrix(m) @caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"] = geo return @caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"] @cube = (w=1,h=1,d=1)=> if(!@caches["cube_#{w}_#{h}_#{d}"]) @caches["cube_#{w}_#{h}_#{d}"] = new THREE.CubeGeometry( w, h, d ) return @caches["cube_#{w}_#{h}_#{d}"] @sphere = (r=1,ws=8,hs=8,phi=0,phiLength=Math.PI*2,theta=0,thetaLength=Math.PI)=> if(!@caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"]) @caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"] = new THREE.SphereGeometry( r, ws, hs, phi, phiLength, theta, thetaLength ) return @caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"] @cylinder = (radiusTop=1, radiusBottom=1, height=1, radiusSegments=8, heightSegments=1, openEnded=false) => if(!@caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"]) @caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"] = new THREE.CylinderGeometry( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) return @caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"] # TODO Other Geometry disposeAll = ()=> for key of @caches @caches[key].dispose() @caches = {} return module.exports = Cache3D
true
# # Cache3D to avoid creating many time the same geometry # @author PI:NAME:<NAME>END_PI / http://makiopolis.com / @makio64 # class Cache3D @caches : {} @plane = (w=1,h=1,segment=1,rotationX=0)=> if(!@caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"]) geo = new THREE.PlaneBufferGeometry( w, h, segment, segment ) if(rotationX!=0) m = new THREE.Matrix4 m.makeRotationX(rotationX) geo.applyMatrix(m) @caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"] = geo return @caches["plane_#{w}_#{h}_#{segment}_#{rotationX}"] @cube = (w=1,h=1,d=1)=> if(!@caches["cube_#{w}_#{h}_#{d}"]) @caches["cube_#{w}_#{h}_#{d}"] = new THREE.CubeGeometry( w, h, d ) return @caches["cube_#{w}_#{h}_#{d}"] @sphere = (r=1,ws=8,hs=8,phi=0,phiLength=Math.PI*2,theta=0,thetaLength=Math.PI)=> if(!@caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"]) @caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"] = new THREE.SphereGeometry( r, ws, hs, phi, phiLength, theta, thetaLength ) return @caches["sphere_#{r}_#{ws}_#{hs}_#{phi}_#{phiLength}_#{theta}_#{thetaLength}"] @cylinder = (radiusTop=1, radiusBottom=1, height=1, radiusSegments=8, heightSegments=1, openEnded=false) => if(!@caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"]) @caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"] = new THREE.CylinderGeometry( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) return @caches["cylinder_#{radiusTop}_#{radiusBottom}_#{height}_#{radiusSegments}"] # TODO Other Geometry disposeAll = ()=> for key of @caches @caches[key].dispose() @caches = {} return module.exports = Cache3D
[ { "context": "w `radios buttons` like switch slide\n\n@author Thiago Lagden <lagden [at] gmail.com>\n@copyright Author\n###\n\n", "end": 116, "score": 0.999890148639679, "start": 103, "tag": "NAME", "value": "Thiago Lagden" }, { "context": "s` like switch slide\n\n@author ...
src/switch.coffee
lagden/switchSlide
0
### switch.js - SwitchSlide It is a plugin that show `radios buttons` like switch slide @author Thiago Lagden <lagden [at] gmail.com> @copyright Author ### ((root, factory) -> if typeof define is 'function' and define.amd define [ 'get-style-property/get-style-property' 'classie/classie' 'eventEmitter/EventEmitter' 'hammerjs/hammer' ], factory else root.SwitchSlide = factory root.getStyleProperty, root.classie, root.EventEmitter, root.Hammer return ) @, (getStyleProperty, classie, EventEmitter, Hammer) -> 'use strict' # Body docBody = document.querySelector 'body' # Extend object # https://github.com/desandro/draggabilly/blob/master/draggabilly.js#L17 extend = (a, b) -> a[prop] = b[prop] for prop of b return a # Verify if object is an HTMLElement # http://stackoverflow.com/a/384380/182183 isElement = (obj) -> if typeof HTMLElement is 'object' return obj instanceof HTMLElement else return obj and typeof obj is 'object' and obj.nodeType is 1 and typeof obj.nodeName is 'string' # Remove all children removeAllChildren = (el) -> while el.hasChildNodes() c = el.lastChild if c.hasChildNodes() el.removeChild removeAllChildren(c) else el.removeChild c return el # Transform property cross-browser transformProperty = getStyleProperty 'transform' # Globally unique identifiers GUID = 0 # Internal store of all SwitchSlide intances instances = {} # Exception class SwitchSlideException constructor: (@message, @name='SwitchSlideException') -> # Vars # # @container # @options # @a # @b # @radios # @width # @margin # @shift # @valor # @active # @transformTranslateX # @keyCodes # @aria # @eventToggleParams # @eventChange # @widget # @sMin # @sMax # @knob # @sizes # @tapElement # @dragElement # @events # @hammer # Class class SwitchSlide # Private Methods _SPL = # Template getTemplate: -> return ' <div class="{widget}"> <div class="{opts} {optMin}"> <span>{captionMin}</span> </div> <div class="{knob}"></div> <div class="{opts} {optMax}"> <span>{captionMax}</span> </div> </div>'.trim() # Size of elements getSizes: (container, css) -> clone = container.cloneNode true clone.style.visibility = 'hidden' clone.style.position = 'absolute' docBody.appendChild clone widget = clone.querySelector ".#{css.widget}" sMin = widget.querySelector ".#{css.optMin}" sMax = widget.querySelector ".#{css.optMax}" knob = widget.querySelector ".#{css.knob}" knobComputedStyle = window.getComputedStyle knob knobMarLeft = parseInt knobComputedStyle.marginLeft, 10 knobMarRight = parseInt knobComputedStyle.marginRight, 10 sizes = 'sMin': sMin.clientWidth 'sMax': sMax.clientWidth 'knob': knob.clientWidth 'margin': knobMarLeft + knobMarRight 'max' : Math.max sMin.clientWidth, sMax.clientWidth # Remove docBody.removeChild removeAllChildren(clone) # GC clone = null widget = null sMin = null sMax = null knob = null return sizes # Event handler # onToggle: -> width = if @options.negative then -@width else @width opts = [ @sMin @sMax ] if @shift isnt null @active = true @transformTranslateX = if @shift then width else 0 a = if @shift then @b else @a b = a ^ 1 c = if @options.swapOrder then a else b d = c ^ 1 _SPL.checked @radios[a], opts[c] _SPL.unchecked @radios[b], opts[d] else @active = false @transformTranslateX = width / 2 _SPL.unchecked @radios[num], opts[num] for num in [0..1] _SPL.isActive.call @ @updateAria() @updateValor() @updatePosition() @emitToggle() for radio in @radios when radio.checked radio.dispatchEvent @eventChange radio.dispatchEvent @eventClick width = a = b = null return onStart: (event) -> @dragElement.focus() classie.add @dragElement, 'is-dragging' return onMove: (event) -> width = if @options.negative then -@width else @width v = (width / 2) + event.deltaX if @shift isnt null v = if @shift then width + event.deltaX else event.deltaX if @options.negative @transformTranslateX = Math.min 0, Math.max width, v else @transformTranslateX = Math.min width, Math.max v, 0 @updatePosition() width = v = null return onEnd: (event) -> @shift = Math.abs(@transformTranslateX) > (@width / 2) classie.remove @dragElement, 'is-dragging' _SPL.onToggle.call @ return onTap: (event) -> rect = @tapElement.getBoundingClientRect() data = [ rect.left + (rect.width / 2) event.center.x ] a = if @options.negative then 1 else 0 b = a ^ 1 @shift = data[a] < data[b] _SPL.onToggle.call @ rect = data = a = b = null return onKeydown: (event) -> trigger = true switch event.keyCode when @keyCodes.space @shift = !@shift when @keyCodes.right @shift = !@options.negative when @keyCodes.left @shift = @options.negative else trigger = false _SPL.onToggle.call @ if trigger trigger = null return # Helpers # # Check if widget is active isActive: -> if @active isnt null method = if @active then 'add' else 'remove' classie[method] @knob, 'is-active' classie[method] @widget, 'is-active' classie.remove @widget, @options.errorClass if @active return # Get Elements getElements: -> @widget = @container.querySelector ".#{@css.widget}" @sMin = @widget.querySelector ".#{@css.optMax}" @sMax = @widget.querySelector ".#{@css.optMin}" @knob = @widget.querySelector ".#{@css.knob}" return # Set Widths setSizes: -> @sMin.style.width = "#{@width}px" @sMax.style.width = "#{@width}px" @knob.style.width = "#{@width - @margin}px" @container.style.width = (@width * 2) + 'px' return # Handler Tap getTapElement: -> return @widget # Handler Drag getDragElement: -> return @knob # Radio checked checked: (radio, opt) -> radio.setAttribute 'checked', '' radio.checked = true if opt? classie.add opt, 'selected' return # Radio unchecked unchecked: (radio, opt) -> radio.removeAttribute 'checked' radio.checked = false if opt? classie.remove opt, 'selected' return # Observer observer: (radio) -> has = classie.has radio, @options.observerClass method = if has then 'add' else 'remove' classie[method] @widget, @options.errorClass return # Build build: -> # Caption captionMin = captionMax = '' labels = @container.getElementsByTagName 'label' if labels.length == 2 captionMin = labels[@a].textContent captionMax = labels[@b].textContent else console.warn '✖ No labels' # Template Render r = 'captionMin' : captionMin 'captionMax' : captionMax 'widget' : @options.widget 'opts' : @options.opts 'optMin' : @options.optMin 'optMax' : @options.optMax 'knob' : @options.knob content = @options.template().replace /\{(.*?)\}/g, (a, b) -> return r[b] @container.insertAdjacentHTML 'afterbegin', content labels = captionMin = captionMax = content = null # Elements @options.getElements.call @ # Size @sizes = _SPL.getSizes @container, @css @width = @sizes.max @margin = @sizes.margin @options.setSizes.call @ # WAI-ARIA @widget.setAttribute attrib, value for attrib, value of @aria # Handlers @tapElement = @options.getTapElement.call @ @dragElement = @options.getDragElement.call @ # Events @events = tap : _SPL.onTap.bind @ panstart : _SPL.onStart.bind @ pan : _SPL.onMove.bind @ panend : _SPL.onEnd.bind @ pancancel : _SPL.onEnd.bind @ keydown : _SPL.onKeydown.bind @ # Hammer Management @hammer = [ { manager : new Hammer.Manager @tapElement evento : new Hammer.Tap methods : [ 'tap' ] } { manager : new Hammer.Manager @dragElement, dragLockToAxis: true dragBlockHorizontal: true preventDefault: true evento : new Hammer.Pan direction: Hammer.DIRECTION_HORIZONTAL methods : [ 'panstart' 'pan' 'panend' 'pancancel' ] } ] # Add Event and Handler for o in @hammer o.manager.add o.evento for m in o.methods o.manager.on m, @events[m] @widget.addEventListener 'keydown', @events.keydown, true # Observer hasMutation = `'MutationObserver' in window` if hasMutation and @options.observerClass that = @ observer = new MutationObserver (mutations) -> mutations.forEach (mutation) -> if mutation.attributeName == 'class' _SPL.observer.apply that, [mutation.target] return return configObserver = attributes: true attributeOldValue: true for radio in @radios observer.observe radio, configObserver # Init _SPL.onToggle.call @ return constructor: (container, options) -> # Self instance if false is (@ instanceof SwitchSlide) return new SwitchSlide container, options # Container if typeof container == 'string' @container = document.querySelector container else @container = container # Exception if isElement @container is false throw new SwitchSlideException '✖ Container must be an HTMLElement' else # Check if component was initialized initialized = SwitchSlide.data @container if initialized instanceof SwitchSlide return initialized else id = ++GUID @container.GUID = id instances[id] = @ # Options @options = labeledby : null required : false template : _SPL.getTemplate setSizes : _SPL.setSizes getElements : _SPL.getElements getTapElement : _SPL.getTapElement getDragElement : _SPL.getDragElement negative : false swapOrder : false errorClass : 'widgetSlide_err' observerClass : null initialize : '' widget : '' opts : '' optMin : '' optMax : '' knob : '' extend @options, options @css = initialize : 'switchSlide--initialized' widget : 'widgetSlide' opts : 'widgetSlide__opt' optMin : 'widgetSlide__opt--min' optMax : 'widgetSlide__opt--max' knob : 'widgetSlide__knob' for k, v of @css @options[k] = "#{v} #{@options[k]}".trim() # Order @a = if @options.swapOrder then 1 else 0 @b = @a ^ 1 # Radios @radios = [] radios = @container.getElementsByTagName 'input' for radio, idx in radios when radio.type == 'radio' # if @options.required # radio.setAttribute 'required', '' @radios.push radio # Exception if @radios.length != 2 throw new SwitchSlideException '✖ No radios' else # Initialize for css in @options.initialize.split(' ') classie.add @container, css # Width @width = 0 @margin = 0 # on, off or null @shift = null @shift = off if @radios[@a].checked @shift = on if @radios[@b].checked # Initial value @valor = null @updateValor() # Active - Show elements when a side is selected @active = null # Animation @transformTranslateX = 0 # Keyboard @keyCodes = 'space' : 32 'left' : 37 'right' : 39 # Accessibility @aria = 'tabindex' : 0 'role' : 'slider' 'aria-valuemin' : @radios[@a].value 'aria-valuemax' : @radios[@b].value 'aria-valuetext' : null 'aria-valuenow' : null 'aria-labeledby' : @options.labeledby 'aria-required' : @options.required # Event parameters @eventToggleParams = [ 'instance' : @ 'radios' : @radios 'value' : @valor ] # Events @eventChange = new CustomEvent 'change', bubbles: true @eventClick = new CustomEvent 'click', bubbles: true # Others @widget = @sMin = @sMax = @knob = null _SPL.build.call @ return # Trigger emitToggle: -> @.emitEvent 'toggle', @eventToggleParams return # Swap swap: (v) -> @shift = if v? then v else !@shift _SPL.onToggle.call @ return # Set switch position via value setByValue: (v = false) -> return false if !v @shift = off if @radios[@a].value == v @shift = on if @radios[@b].value == v _SPL.onToggle.call @ return # Reset reset: -> @shift = null _SPL.onToggle.call @ return # Update WAI-ARIA - Accessibility updateAria: -> if @shift isnt null v = if @shift is on then @radios[@b].title else @radios[@a].title @widget.setAttribute 'aria-valuenow', @valor @widget.setAttribute 'aria-valuetext', v v = null return # Update value updateValor: -> @valor = null if @shift isnt null @valor = if @shift is on then @radios[@b].value else @radios[@a].value if @eventToggleParams? @eventToggleParams[0].value = @valor return # Update position updatePosition: -> value = ["translate3d(#{@transformTranslateX}px, 0, 0)"] @dragElement.style[transformProperty] = value.join " " value = null return # Destroy destroy: -> if @container isnt null # Remove Listeners for o in @hammer o.manager.destroy() @widget.removeEventListener 'keydown', @events.keydown # Remove children from @widget removeAllChildren @widget # Remove @widget if @container.contains @widget @container.removeChild @widget # Remove classes and attributes for css in @options.initialize.split(' ') classie.remove @container, css @container.removeAttribute 'style' # Remove reference @container.GUID = null # Nullable @container = @options = @a = @b = @radios = @width = @margin = @shift = @valor = @active = @transformTranslateX = @keyCodes = @aria = @eventToggleParams = @eventChange = @widget = @sMin = @sMax = @knob = @sizes = @tapElement = @dragElement = @events = @hammer = null return # Extends extend SwitchSlide::, EventEmitter:: # https://github.com/metafizzy/outlayer/blob/master/outlayer.js#L887 # # get SwitchSlide instance from element # @param {Element} el # @return {SwitchSlide} # SwitchSlide.data = (el) -> id = el and el.GUID return id and instances[id] return SwitchSlide
120054
### switch.js - SwitchSlide It is a plugin that show `radios buttons` like switch slide @author <NAME> <<EMAIL>den [at] gmail.com> @copyright Author ### ((root, factory) -> if typeof define is 'function' and define.amd define [ 'get-style-property/get-style-property' 'classie/classie' 'eventEmitter/EventEmitter' 'hammerjs/hammer' ], factory else root.SwitchSlide = factory root.getStyleProperty, root.classie, root.EventEmitter, root.Hammer return ) @, (getStyleProperty, classie, EventEmitter, Hammer) -> 'use strict' # Body docBody = document.querySelector 'body' # Extend object # https://github.com/desandro/draggabilly/blob/master/draggabilly.js#L17 extend = (a, b) -> a[prop] = b[prop] for prop of b return a # Verify if object is an HTMLElement # http://stackoverflow.com/a/384380/182183 isElement = (obj) -> if typeof HTMLElement is 'object' return obj instanceof HTMLElement else return obj and typeof obj is 'object' and obj.nodeType is 1 and typeof obj.nodeName is 'string' # Remove all children removeAllChildren = (el) -> while el.hasChildNodes() c = el.lastChild if c.hasChildNodes() el.removeChild removeAllChildren(c) else el.removeChild c return el # Transform property cross-browser transformProperty = getStyleProperty 'transform' # Globally unique identifiers GUID = 0 # Internal store of all SwitchSlide intances instances = {} # Exception class SwitchSlideException constructor: (@message, @name='SwitchSlideException') -> # Vars # # @container # @options # @a # @b # @radios # @width # @margin # @shift # @valor # @active # @transformTranslateX # @keyCodes # @aria # @eventToggleParams # @eventChange # @widget # @sMin # @sMax # @knob # @sizes # @tapElement # @dragElement # @events # @hammer # Class class SwitchSlide # Private Methods _SPL = # Template getTemplate: -> return ' <div class="{widget}"> <div class="{opts} {optMin}"> <span>{captionMin}</span> </div> <div class="{knob}"></div> <div class="{opts} {optMax}"> <span>{captionMax}</span> </div> </div>'.trim() # Size of elements getSizes: (container, css) -> clone = container.cloneNode true clone.style.visibility = 'hidden' clone.style.position = 'absolute' docBody.appendChild clone widget = clone.querySelector ".#{css.widget}" sMin = widget.querySelector ".#{css.optMin}" sMax = widget.querySelector ".#{css.optMax}" knob = widget.querySelector ".#{css.knob}" knobComputedStyle = window.getComputedStyle knob knobMarLeft = parseInt knobComputedStyle.marginLeft, 10 knobMarRight = parseInt knobComputedStyle.marginRight, 10 sizes = 'sMin': sMin.clientWidth 'sMax': sMax.clientWidth 'knob': knob.clientWidth 'margin': knobMarLeft + knobMarRight 'max' : Math.max sMin.clientWidth, sMax.clientWidth # Remove docBody.removeChild removeAllChildren(clone) # GC clone = null widget = null sMin = null sMax = null knob = null return sizes # Event handler # onToggle: -> width = if @options.negative then -@width else @width opts = [ @sMin @sMax ] if @shift isnt null @active = true @transformTranslateX = if @shift then width else 0 a = if @shift then @b else @a b = a ^ 1 c = if @options.swapOrder then a else b d = c ^ 1 _SPL.checked @radios[a], opts[c] _SPL.unchecked @radios[b], opts[d] else @active = false @transformTranslateX = width / 2 _SPL.unchecked @radios[num], opts[num] for num in [0..1] _SPL.isActive.call @ @updateAria() @updateValor() @updatePosition() @emitToggle() for radio in @radios when radio.checked radio.dispatchEvent @eventChange radio.dispatchEvent @eventClick width = a = b = null return onStart: (event) -> @dragElement.focus() classie.add @dragElement, 'is-dragging' return onMove: (event) -> width = if @options.negative then -@width else @width v = (width / 2) + event.deltaX if @shift isnt null v = if @shift then width + event.deltaX else event.deltaX if @options.negative @transformTranslateX = Math.min 0, Math.max width, v else @transformTranslateX = Math.min width, Math.max v, 0 @updatePosition() width = v = null return onEnd: (event) -> @shift = Math.abs(@transformTranslateX) > (@width / 2) classie.remove @dragElement, 'is-dragging' _SPL.onToggle.call @ return onTap: (event) -> rect = @tapElement.getBoundingClientRect() data = [ rect.left + (rect.width / 2) event.center.x ] a = if @options.negative then 1 else 0 b = a ^ 1 @shift = data[a] < data[b] _SPL.onToggle.call @ rect = data = a = b = null return onKeydown: (event) -> trigger = true switch event.keyCode when @keyCodes.space @shift = !@shift when @keyCodes.right @shift = !@options.negative when @keyCodes.left @shift = @options.negative else trigger = false _SPL.onToggle.call @ if trigger trigger = null return # Helpers # # Check if widget is active isActive: -> if @active isnt null method = if @active then 'add' else 'remove' classie[method] @knob, 'is-active' classie[method] @widget, 'is-active' classie.remove @widget, @options.errorClass if @active return # Get Elements getElements: -> @widget = @container.querySelector ".#{@css.widget}" @sMin = @widget.querySelector ".#{@css.optMax}" @sMax = @widget.querySelector ".#{@css.optMin}" @knob = @widget.querySelector ".#{@css.knob}" return # Set Widths setSizes: -> @sMin.style.width = "#{@width}px" @sMax.style.width = "#{@width}px" @knob.style.width = "#{@width - @margin}px" @container.style.width = (@width * 2) + 'px' return # Handler Tap getTapElement: -> return @widget # Handler Drag getDragElement: -> return @knob # Radio checked checked: (radio, opt) -> radio.setAttribute 'checked', '' radio.checked = true if opt? classie.add opt, 'selected' return # Radio unchecked unchecked: (radio, opt) -> radio.removeAttribute 'checked' radio.checked = false if opt? classie.remove opt, 'selected' return # Observer observer: (radio) -> has = classie.has radio, @options.observerClass method = if has then 'add' else 'remove' classie[method] @widget, @options.errorClass return # Build build: -> # Caption captionMin = captionMax = '' labels = @container.getElementsByTagName 'label' if labels.length == 2 captionMin = labels[@a].textContent captionMax = labels[@b].textContent else console.warn '✖ No labels' # Template Render r = 'captionMin' : captionMin 'captionMax' : captionMax 'widget' : @options.widget 'opts' : @options.opts 'optMin' : @options.optMin 'optMax' : @options.optMax 'knob' : @options.knob content = @options.template().replace /\{(.*?)\}/g, (a, b) -> return r[b] @container.insertAdjacentHTML 'afterbegin', content labels = captionMin = captionMax = content = null # Elements @options.getElements.call @ # Size @sizes = _SPL.getSizes @container, @css @width = @sizes.max @margin = @sizes.margin @options.setSizes.call @ # WAI-ARIA @widget.setAttribute attrib, value for attrib, value of @aria # Handlers @tapElement = @options.getTapElement.call @ @dragElement = @options.getDragElement.call @ # Events @events = tap : _SPL.onTap.bind @ panstart : _SPL.onStart.bind @ pan : _SPL.onMove.bind @ panend : _SPL.onEnd.bind @ pancancel : _SPL.onEnd.bind @ keydown : _SPL.onKeydown.bind @ # Hammer Management @hammer = [ { manager : new Hammer.Manager @tapElement evento : new Hammer.Tap methods : [ 'tap' ] } { manager : new Hammer.Manager @dragElement, dragLockToAxis: true dragBlockHorizontal: true preventDefault: true evento : new Hammer.Pan direction: Hammer.DIRECTION_HORIZONTAL methods : [ 'panstart' 'pan' 'panend' 'pancancel' ] } ] # Add Event and Handler for o in @hammer o.manager.add o.evento for m in o.methods o.manager.on m, @events[m] @widget.addEventListener 'keydown', @events.keydown, true # Observer hasMutation = `'MutationObserver' in window` if hasMutation and @options.observerClass that = @ observer = new MutationObserver (mutations) -> mutations.forEach (mutation) -> if mutation.attributeName == 'class' _SPL.observer.apply that, [mutation.target] return return configObserver = attributes: true attributeOldValue: true for radio in @radios observer.observe radio, configObserver # Init _SPL.onToggle.call @ return constructor: (container, options) -> # Self instance if false is (@ instanceof SwitchSlide) return new SwitchSlide container, options # Container if typeof container == 'string' @container = document.querySelector container else @container = container # Exception if isElement @container is false throw new SwitchSlideException '✖ Container must be an HTMLElement' else # Check if component was initialized initialized = SwitchSlide.data @container if initialized instanceof SwitchSlide return initialized else id = ++GUID @container.GUID = id instances[id] = @ # Options @options = labeledby : null required : false template : _SPL.getTemplate setSizes : _SPL.setSizes getElements : _SPL.getElements getTapElement : _SPL.getTapElement getDragElement : _SPL.getDragElement negative : false swapOrder : false errorClass : 'widgetSlide_err' observerClass : null initialize : '' widget : '' opts : '' optMin : '' optMax : '' knob : '' extend @options, options @css = initialize : 'switchSlide--initialized' widget : 'widgetSlide' opts : 'widgetSlide__opt' optMin : 'widgetSlide__opt--min' optMax : 'widgetSlide__opt--max' knob : 'widgetSlide__knob' for k, v of @css @options[k] = "#{v} #{@options[k]}".trim() # Order @a = if @options.swapOrder then 1 else 0 @b = @a ^ 1 # Radios @radios = [] radios = @container.getElementsByTagName 'input' for radio, idx in radios when radio.type == 'radio' # if @options.required # radio.setAttribute 'required', '' @radios.push radio # Exception if @radios.length != 2 throw new SwitchSlideException '✖ No radios' else # Initialize for css in @options.initialize.split(' ') classie.add @container, css # Width @width = 0 @margin = 0 # on, off or null @shift = null @shift = off if @radios[@a].checked @shift = on if @radios[@b].checked # Initial value @valor = null @updateValor() # Active - Show elements when a side is selected @active = null # Animation @transformTranslateX = 0 # Keyboard @keyCodes = 'space' : 32 'left' : 37 'right' : 39 # Accessibility @aria = 'tabindex' : 0 'role' : 'slider' 'aria-valuemin' : @radios[@a].value 'aria-valuemax' : @radios[@b].value 'aria-valuetext' : null 'aria-valuenow' : null 'aria-labeledby' : @options.labeledby 'aria-required' : @options.required # Event parameters @eventToggleParams = [ 'instance' : @ 'radios' : @radios 'value' : @valor ] # Events @eventChange = new CustomEvent 'change', bubbles: true @eventClick = new CustomEvent 'click', bubbles: true # Others @widget = @sMin = @sMax = @knob = null _SPL.build.call @ return # Trigger emitToggle: -> @.emitEvent 'toggle', @eventToggleParams return # Swap swap: (v) -> @shift = if v? then v else !@shift _SPL.onToggle.call @ return # Set switch position via value setByValue: (v = false) -> return false if !v @shift = off if @radios[@a].value == v @shift = on if @radios[@b].value == v _SPL.onToggle.call @ return # Reset reset: -> @shift = null _SPL.onToggle.call @ return # Update WAI-ARIA - Accessibility updateAria: -> if @shift isnt null v = if @shift is on then @radios[@b].title else @radios[@a].title @widget.setAttribute 'aria-valuenow', @valor @widget.setAttribute 'aria-valuetext', v v = null return # Update value updateValor: -> @valor = null if @shift isnt null @valor = if @shift is on then @radios[@b].value else @radios[@a].value if @eventToggleParams? @eventToggleParams[0].value = @valor return # Update position updatePosition: -> value = ["translate3d(#{@transformTranslateX}px, 0, 0)"] @dragElement.style[transformProperty] = value.join " " value = null return # Destroy destroy: -> if @container isnt null # Remove Listeners for o in @hammer o.manager.destroy() @widget.removeEventListener 'keydown', @events.keydown # Remove children from @widget removeAllChildren @widget # Remove @widget if @container.contains @widget @container.removeChild @widget # Remove classes and attributes for css in @options.initialize.split(' ') classie.remove @container, css @container.removeAttribute 'style' # Remove reference @container.GUID = null # Nullable @container = @options = @a = @b = @radios = @width = @margin = @shift = @valor = @active = @transformTranslateX = @keyCodes = @aria = @eventToggleParams = @eventChange = @widget = @sMin = @sMax = @knob = @sizes = @tapElement = @dragElement = @events = @hammer = null return # Extends extend SwitchSlide::, EventEmitter:: # https://github.com/metafizzy/outlayer/blob/master/outlayer.js#L887 # # get SwitchSlide instance from element # @param {Element} el # @return {SwitchSlide} # SwitchSlide.data = (el) -> id = el and el.GUID return id and instances[id] return SwitchSlide
true
### switch.js - SwitchSlide It is a plugin that show `radios buttons` like switch slide @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PIden [at] gmail.com> @copyright Author ### ((root, factory) -> if typeof define is 'function' and define.amd define [ 'get-style-property/get-style-property' 'classie/classie' 'eventEmitter/EventEmitter' 'hammerjs/hammer' ], factory else root.SwitchSlide = factory root.getStyleProperty, root.classie, root.EventEmitter, root.Hammer return ) @, (getStyleProperty, classie, EventEmitter, Hammer) -> 'use strict' # Body docBody = document.querySelector 'body' # Extend object # https://github.com/desandro/draggabilly/blob/master/draggabilly.js#L17 extend = (a, b) -> a[prop] = b[prop] for prop of b return a # Verify if object is an HTMLElement # http://stackoverflow.com/a/384380/182183 isElement = (obj) -> if typeof HTMLElement is 'object' return obj instanceof HTMLElement else return obj and typeof obj is 'object' and obj.nodeType is 1 and typeof obj.nodeName is 'string' # Remove all children removeAllChildren = (el) -> while el.hasChildNodes() c = el.lastChild if c.hasChildNodes() el.removeChild removeAllChildren(c) else el.removeChild c return el # Transform property cross-browser transformProperty = getStyleProperty 'transform' # Globally unique identifiers GUID = 0 # Internal store of all SwitchSlide intances instances = {} # Exception class SwitchSlideException constructor: (@message, @name='SwitchSlideException') -> # Vars # # @container # @options # @a # @b # @radios # @width # @margin # @shift # @valor # @active # @transformTranslateX # @keyCodes # @aria # @eventToggleParams # @eventChange # @widget # @sMin # @sMax # @knob # @sizes # @tapElement # @dragElement # @events # @hammer # Class class SwitchSlide # Private Methods _SPL = # Template getTemplate: -> return ' <div class="{widget}"> <div class="{opts} {optMin}"> <span>{captionMin}</span> </div> <div class="{knob}"></div> <div class="{opts} {optMax}"> <span>{captionMax}</span> </div> </div>'.trim() # Size of elements getSizes: (container, css) -> clone = container.cloneNode true clone.style.visibility = 'hidden' clone.style.position = 'absolute' docBody.appendChild clone widget = clone.querySelector ".#{css.widget}" sMin = widget.querySelector ".#{css.optMin}" sMax = widget.querySelector ".#{css.optMax}" knob = widget.querySelector ".#{css.knob}" knobComputedStyle = window.getComputedStyle knob knobMarLeft = parseInt knobComputedStyle.marginLeft, 10 knobMarRight = parseInt knobComputedStyle.marginRight, 10 sizes = 'sMin': sMin.clientWidth 'sMax': sMax.clientWidth 'knob': knob.clientWidth 'margin': knobMarLeft + knobMarRight 'max' : Math.max sMin.clientWidth, sMax.clientWidth # Remove docBody.removeChild removeAllChildren(clone) # GC clone = null widget = null sMin = null sMax = null knob = null return sizes # Event handler # onToggle: -> width = if @options.negative then -@width else @width opts = [ @sMin @sMax ] if @shift isnt null @active = true @transformTranslateX = if @shift then width else 0 a = if @shift then @b else @a b = a ^ 1 c = if @options.swapOrder then a else b d = c ^ 1 _SPL.checked @radios[a], opts[c] _SPL.unchecked @radios[b], opts[d] else @active = false @transformTranslateX = width / 2 _SPL.unchecked @radios[num], opts[num] for num in [0..1] _SPL.isActive.call @ @updateAria() @updateValor() @updatePosition() @emitToggle() for radio in @radios when radio.checked radio.dispatchEvent @eventChange radio.dispatchEvent @eventClick width = a = b = null return onStart: (event) -> @dragElement.focus() classie.add @dragElement, 'is-dragging' return onMove: (event) -> width = if @options.negative then -@width else @width v = (width / 2) + event.deltaX if @shift isnt null v = if @shift then width + event.deltaX else event.deltaX if @options.negative @transformTranslateX = Math.min 0, Math.max width, v else @transformTranslateX = Math.min width, Math.max v, 0 @updatePosition() width = v = null return onEnd: (event) -> @shift = Math.abs(@transformTranslateX) > (@width / 2) classie.remove @dragElement, 'is-dragging' _SPL.onToggle.call @ return onTap: (event) -> rect = @tapElement.getBoundingClientRect() data = [ rect.left + (rect.width / 2) event.center.x ] a = if @options.negative then 1 else 0 b = a ^ 1 @shift = data[a] < data[b] _SPL.onToggle.call @ rect = data = a = b = null return onKeydown: (event) -> trigger = true switch event.keyCode when @keyCodes.space @shift = !@shift when @keyCodes.right @shift = !@options.negative when @keyCodes.left @shift = @options.negative else trigger = false _SPL.onToggle.call @ if trigger trigger = null return # Helpers # # Check if widget is active isActive: -> if @active isnt null method = if @active then 'add' else 'remove' classie[method] @knob, 'is-active' classie[method] @widget, 'is-active' classie.remove @widget, @options.errorClass if @active return # Get Elements getElements: -> @widget = @container.querySelector ".#{@css.widget}" @sMin = @widget.querySelector ".#{@css.optMax}" @sMax = @widget.querySelector ".#{@css.optMin}" @knob = @widget.querySelector ".#{@css.knob}" return # Set Widths setSizes: -> @sMin.style.width = "#{@width}px" @sMax.style.width = "#{@width}px" @knob.style.width = "#{@width - @margin}px" @container.style.width = (@width * 2) + 'px' return # Handler Tap getTapElement: -> return @widget # Handler Drag getDragElement: -> return @knob # Radio checked checked: (radio, opt) -> radio.setAttribute 'checked', '' radio.checked = true if opt? classie.add opt, 'selected' return # Radio unchecked unchecked: (radio, opt) -> radio.removeAttribute 'checked' radio.checked = false if opt? classie.remove opt, 'selected' return # Observer observer: (radio) -> has = classie.has radio, @options.observerClass method = if has then 'add' else 'remove' classie[method] @widget, @options.errorClass return # Build build: -> # Caption captionMin = captionMax = '' labels = @container.getElementsByTagName 'label' if labels.length == 2 captionMin = labels[@a].textContent captionMax = labels[@b].textContent else console.warn '✖ No labels' # Template Render r = 'captionMin' : captionMin 'captionMax' : captionMax 'widget' : @options.widget 'opts' : @options.opts 'optMin' : @options.optMin 'optMax' : @options.optMax 'knob' : @options.knob content = @options.template().replace /\{(.*?)\}/g, (a, b) -> return r[b] @container.insertAdjacentHTML 'afterbegin', content labels = captionMin = captionMax = content = null # Elements @options.getElements.call @ # Size @sizes = _SPL.getSizes @container, @css @width = @sizes.max @margin = @sizes.margin @options.setSizes.call @ # WAI-ARIA @widget.setAttribute attrib, value for attrib, value of @aria # Handlers @tapElement = @options.getTapElement.call @ @dragElement = @options.getDragElement.call @ # Events @events = tap : _SPL.onTap.bind @ panstart : _SPL.onStart.bind @ pan : _SPL.onMove.bind @ panend : _SPL.onEnd.bind @ pancancel : _SPL.onEnd.bind @ keydown : _SPL.onKeydown.bind @ # Hammer Management @hammer = [ { manager : new Hammer.Manager @tapElement evento : new Hammer.Tap methods : [ 'tap' ] } { manager : new Hammer.Manager @dragElement, dragLockToAxis: true dragBlockHorizontal: true preventDefault: true evento : new Hammer.Pan direction: Hammer.DIRECTION_HORIZONTAL methods : [ 'panstart' 'pan' 'panend' 'pancancel' ] } ] # Add Event and Handler for o in @hammer o.manager.add o.evento for m in o.methods o.manager.on m, @events[m] @widget.addEventListener 'keydown', @events.keydown, true # Observer hasMutation = `'MutationObserver' in window` if hasMutation and @options.observerClass that = @ observer = new MutationObserver (mutations) -> mutations.forEach (mutation) -> if mutation.attributeName == 'class' _SPL.observer.apply that, [mutation.target] return return configObserver = attributes: true attributeOldValue: true for radio in @radios observer.observe radio, configObserver # Init _SPL.onToggle.call @ return constructor: (container, options) -> # Self instance if false is (@ instanceof SwitchSlide) return new SwitchSlide container, options # Container if typeof container == 'string' @container = document.querySelector container else @container = container # Exception if isElement @container is false throw new SwitchSlideException '✖ Container must be an HTMLElement' else # Check if component was initialized initialized = SwitchSlide.data @container if initialized instanceof SwitchSlide return initialized else id = ++GUID @container.GUID = id instances[id] = @ # Options @options = labeledby : null required : false template : _SPL.getTemplate setSizes : _SPL.setSizes getElements : _SPL.getElements getTapElement : _SPL.getTapElement getDragElement : _SPL.getDragElement negative : false swapOrder : false errorClass : 'widgetSlide_err' observerClass : null initialize : '' widget : '' opts : '' optMin : '' optMax : '' knob : '' extend @options, options @css = initialize : 'switchSlide--initialized' widget : 'widgetSlide' opts : 'widgetSlide__opt' optMin : 'widgetSlide__opt--min' optMax : 'widgetSlide__opt--max' knob : 'widgetSlide__knob' for k, v of @css @options[k] = "#{v} #{@options[k]}".trim() # Order @a = if @options.swapOrder then 1 else 0 @b = @a ^ 1 # Radios @radios = [] radios = @container.getElementsByTagName 'input' for radio, idx in radios when radio.type == 'radio' # if @options.required # radio.setAttribute 'required', '' @radios.push radio # Exception if @radios.length != 2 throw new SwitchSlideException '✖ No radios' else # Initialize for css in @options.initialize.split(' ') classie.add @container, css # Width @width = 0 @margin = 0 # on, off or null @shift = null @shift = off if @radios[@a].checked @shift = on if @radios[@b].checked # Initial value @valor = null @updateValor() # Active - Show elements when a side is selected @active = null # Animation @transformTranslateX = 0 # Keyboard @keyCodes = 'space' : 32 'left' : 37 'right' : 39 # Accessibility @aria = 'tabindex' : 0 'role' : 'slider' 'aria-valuemin' : @radios[@a].value 'aria-valuemax' : @radios[@b].value 'aria-valuetext' : null 'aria-valuenow' : null 'aria-labeledby' : @options.labeledby 'aria-required' : @options.required # Event parameters @eventToggleParams = [ 'instance' : @ 'radios' : @radios 'value' : @valor ] # Events @eventChange = new CustomEvent 'change', bubbles: true @eventClick = new CustomEvent 'click', bubbles: true # Others @widget = @sMin = @sMax = @knob = null _SPL.build.call @ return # Trigger emitToggle: -> @.emitEvent 'toggle', @eventToggleParams return # Swap swap: (v) -> @shift = if v? then v else !@shift _SPL.onToggle.call @ return # Set switch position via value setByValue: (v = false) -> return false if !v @shift = off if @radios[@a].value == v @shift = on if @radios[@b].value == v _SPL.onToggle.call @ return # Reset reset: -> @shift = null _SPL.onToggle.call @ return # Update WAI-ARIA - Accessibility updateAria: -> if @shift isnt null v = if @shift is on then @radios[@b].title else @radios[@a].title @widget.setAttribute 'aria-valuenow', @valor @widget.setAttribute 'aria-valuetext', v v = null return # Update value updateValor: -> @valor = null if @shift isnt null @valor = if @shift is on then @radios[@b].value else @radios[@a].value if @eventToggleParams? @eventToggleParams[0].value = @valor return # Update position updatePosition: -> value = ["translate3d(#{@transformTranslateX}px, 0, 0)"] @dragElement.style[transformProperty] = value.join " " value = null return # Destroy destroy: -> if @container isnt null # Remove Listeners for o in @hammer o.manager.destroy() @widget.removeEventListener 'keydown', @events.keydown # Remove children from @widget removeAllChildren @widget # Remove @widget if @container.contains @widget @container.removeChild @widget # Remove classes and attributes for css in @options.initialize.split(' ') classie.remove @container, css @container.removeAttribute 'style' # Remove reference @container.GUID = null # Nullable @container = @options = @a = @b = @radios = @width = @margin = @shift = @valor = @active = @transformTranslateX = @keyCodes = @aria = @eventToggleParams = @eventChange = @widget = @sMin = @sMax = @knob = @sizes = @tapElement = @dragElement = @events = @hammer = null return # Extends extend SwitchSlide::, EventEmitter:: # https://github.com/metafizzy/outlayer/blob/master/outlayer.js#L887 # # get SwitchSlide instance from element # @param {Element} el # @return {SwitchSlide} # SwitchSlide.data = (el) -> id = el and el.GUID return id and instances[id] return SwitchSlide
[ { "context": "nly: true\n }\n }\n }\n data = {\n name: 'Bob',\n numbers: [\n {'number':'401-401-1337', ", "end": 589, "score": 0.9997732639312744, "start": 586, "tag": "NAME", "value": "Bob" } ]
test/readOnly.coffee
lgr7/codecombattreema
66
describe 'readOnly in schema', -> schema = { type: 'object', properties: { name: { type: 'string', readOnly: true }, numbers: { type: 'array', items: { type: 'object' }, readOnly: true }, tags: { type: 'array', items: { type: 'string', readOnly: true } }, tags2: { type: 'array', items: { type: 'string' }, readOnly: true } map: { type: 'object', readOnly: true } } } data = { name: 'Bob', numbers: [ {'number':'401-401-1337', 'type':'Home'}, {'number':'123-456-7890', 'type':'Work'} ], tags: ['Friend'], tags2: ['Friend'], map: { 'string': 'String', 'object': { 'key': 'value' } } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() it 'prevents editing of readOnly non-collection properties', -> expect(treema.childrenTreemas.name.canEdit()).toBe(false) # arrays it 'prevents removing from readOnly arrays', -> treema.childrenTreemas.numbers.remove() expect(treema.data.numbers).not.toBeUndefined() it 'prevents adding items to readOnly arrays', -> expect(treema.childrenTreemas.numbers.canAddChild()).toBe(false) it 'prevents removing readOnly items from arrays which are not readOnly', -> treema.childrenTreemas.tags.open() treema.childrenTreemas.tags.childrenTreemas[0].remove() expect(treema.data.tags.length).toBe(1) it 'prevents editing non-collection items in readOnly arrays', -> treema.childrenTreemas.tags2.open() expect(treema.childrenTreemas.tags2.childrenTreemas[0].canEdit()).toBe(false) # objects it 'prevents removing from readOnly objects', -> treema.childrenTreemas.map.remove() expect(treema.data.map).not.toBeUndefined() it 'prevents adding to readOnly objects', -> expect(treema.childrenTreemas.map.canAddChild()).toBe(false) it 'prevents removing readOnly properties from objects which are not readOnly', -> treema.childrenTreemas.name.remove() treema.childrenTreemas.tags.childrenTreemas[0].remove() expect(treema.data.tags.length).toBe(1) it 'prevents editing non-collection properties in readOnly objects', -> treema.childrenTreemas.map.open() expect(treema.childrenTreemas.map.childrenTreemas.string.canEdit()).toBe(false)
2636
describe 'readOnly in schema', -> schema = { type: 'object', properties: { name: { type: 'string', readOnly: true }, numbers: { type: 'array', items: { type: 'object' }, readOnly: true }, tags: { type: 'array', items: { type: 'string', readOnly: true } }, tags2: { type: 'array', items: { type: 'string' }, readOnly: true } map: { type: 'object', readOnly: true } } } data = { name: '<NAME>', numbers: [ {'number':'401-401-1337', 'type':'Home'}, {'number':'123-456-7890', 'type':'Work'} ], tags: ['Friend'], tags2: ['Friend'], map: { 'string': 'String', 'object': { 'key': 'value' } } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() it 'prevents editing of readOnly non-collection properties', -> expect(treema.childrenTreemas.name.canEdit()).toBe(false) # arrays it 'prevents removing from readOnly arrays', -> treema.childrenTreemas.numbers.remove() expect(treema.data.numbers).not.toBeUndefined() it 'prevents adding items to readOnly arrays', -> expect(treema.childrenTreemas.numbers.canAddChild()).toBe(false) it 'prevents removing readOnly items from arrays which are not readOnly', -> treema.childrenTreemas.tags.open() treema.childrenTreemas.tags.childrenTreemas[0].remove() expect(treema.data.tags.length).toBe(1) it 'prevents editing non-collection items in readOnly arrays', -> treema.childrenTreemas.tags2.open() expect(treema.childrenTreemas.tags2.childrenTreemas[0].canEdit()).toBe(false) # objects it 'prevents removing from readOnly objects', -> treema.childrenTreemas.map.remove() expect(treema.data.map).not.toBeUndefined() it 'prevents adding to readOnly objects', -> expect(treema.childrenTreemas.map.canAddChild()).toBe(false) it 'prevents removing readOnly properties from objects which are not readOnly', -> treema.childrenTreemas.name.remove() treema.childrenTreemas.tags.childrenTreemas[0].remove() expect(treema.data.tags.length).toBe(1) it 'prevents editing non-collection properties in readOnly objects', -> treema.childrenTreemas.map.open() expect(treema.childrenTreemas.map.childrenTreemas.string.canEdit()).toBe(false)
true
describe 'readOnly in schema', -> schema = { type: 'object', properties: { name: { type: 'string', readOnly: true }, numbers: { type: 'array', items: { type: 'object' }, readOnly: true }, tags: { type: 'array', items: { type: 'string', readOnly: true } }, tags2: { type: 'array', items: { type: 'string' }, readOnly: true } map: { type: 'object', readOnly: true } } } data = { name: 'PI:NAME:<NAME>END_PI', numbers: [ {'number':'401-401-1337', 'type':'Home'}, {'number':'123-456-7890', 'type':'Work'} ], tags: ['Friend'], tags2: ['Friend'], map: { 'string': 'String', 'object': { 'key': 'value' } } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() it 'prevents editing of readOnly non-collection properties', -> expect(treema.childrenTreemas.name.canEdit()).toBe(false) # arrays it 'prevents removing from readOnly arrays', -> treema.childrenTreemas.numbers.remove() expect(treema.data.numbers).not.toBeUndefined() it 'prevents adding items to readOnly arrays', -> expect(treema.childrenTreemas.numbers.canAddChild()).toBe(false) it 'prevents removing readOnly items from arrays which are not readOnly', -> treema.childrenTreemas.tags.open() treema.childrenTreemas.tags.childrenTreemas[0].remove() expect(treema.data.tags.length).toBe(1) it 'prevents editing non-collection items in readOnly arrays', -> treema.childrenTreemas.tags2.open() expect(treema.childrenTreemas.tags2.childrenTreemas[0].canEdit()).toBe(false) # objects it 'prevents removing from readOnly objects', -> treema.childrenTreemas.map.remove() expect(treema.data.map).not.toBeUndefined() it 'prevents adding to readOnly objects', -> expect(treema.childrenTreemas.map.canAddChild()).toBe(false) it 'prevents removing readOnly properties from objects which are not readOnly', -> treema.childrenTreemas.name.remove() treema.childrenTreemas.tags.childrenTreemas[0].remove() expect(treema.data.tags.length).toBe(1) it 'prevents editing non-collection properties in readOnly objects', -> treema.childrenTreemas.map.open() expect(treema.childrenTreemas.map.childrenTreemas.string.canEdit()).toBe(false)
[ { "context": " strict'\n\n#!\n# esef-frontend\n# https://github.com/egemsoft/esef-frontend\n# Copyright (c) 2014 Egemsoft\n# Lic", "end": 62, "score": 0.9975907206535339, "start": 54, "tag": "USERNAME", "value": "egemsoft" }, { "context": "pyright (c) 2014 Egemsoft\n# License: MIT\n#...
Gruntfile.coffee
egemsoft/esef-frontend
0
'use strict' #! # esef-frontend # https://github.com/egemsoft/esef-frontend # Copyright (c) 2014 Egemsoft # License: MIT # Author: İsmail Demirbilek # module.exports = (grunt) -> loadGruntTasks = require 'load-grunt-tasks' timeGrunt = require 'time-grunt' loadGruntTasks grunt timeGrunt grunt grunt.initConfig pkg: grunt.file.readJSON 'bower.json' appConfig: app: 'src' name: 'Esef Frontend' dist: 'dist' banner: '/*!\n' + ' * <%= pkg.name %> - v<%= pkg.version %>\n' + ' * <%= pkg.homepage %>\n' + ' * <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> Egemsoft\n' + ' * License: <%= pkg.license %>\n' + ' */\n' coffee: app: options: bare: true expand: true src: ['<%= appConfig.app %>/*.coffee', '<%= appConfig.app %>/*/coffee/{,*/}*.coffee'] ext: '.compiled.js' test: options: bare: true expand: true src: ['test/coffee/**/*.coffee'] ext: '.compiled.js' concat: js: options: banner: '\'use strict\';\n<%= banner %>\n' # remove use strict tags process: (src) -> src.replace /(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1' files: '<%= appConfig.dist %>/bundle/esef-frontend.js': ['<%= appConfig.app %>/{,*/}/{,*/}{,*/}*.js'] css: options: banner: '<%= banner %>\n' files: '<%= appConfig.dist %>/bundle/esef-frontend.css': ['<%= appConfig.app %>/{,*/}styles/{,*/}*.css'] connect: test: options: port: 9001 base: [ '.tmp' 'test' '<%= appConfig.app %>' ] clean: dist: dot: true src: [ '.tmp' '<%= appConfig.dist %>/*' '!<%= appConfig.dist %>/.git*' ] coffee: src: [ '<%= appConfig.app %>/app.compiled.js', '<%= appConfig.app %>/*/coffee/{,*/}*.compiled.js' 'test/coffee/{,*/}{,*/}{,*/}*.compiled.js' ] server: '.tmp' jshint: options: jshintrc: '.jshintrc' all: [ 'Gruntfile.js' '<%= appConfig.app %>/{,*/}{,*/}{,*/}*.js' ] cssmin: dist: files: '<%= appConfig.dist %>/css/esef-frontend.min.css': [ '.tmp/styles/{,*/}*.css' '<%= appConfig.app %>/{,*/}styles/{,*/}*.css' ] karma: unit: configFile: 'karma.conf.js' singleRun: true ngAnnotate: dist: files: [ expand: true, cwd: '<%= appConfig.dist %>/' src: '{,*/}*.js' dest: '.tmp' ] uglify: dist: files: '<%= appConfig.dist %>/bundle/esef-frontend.min.js': ['.tmp/bundle/**.js'] ngdocs: options: dest: 'docs' html5Mode: false title: '<%= appConfig.name %> Documentation' all: ['<%= appConfig.app %>/{,*/}{,*/}{,*/}*.js'] 'folder_list': options: files: false folders: true files: src: ['*'] cwd: 'src/' dest: 'modules.json' # set concat and uglify files configs dynamically grunt.registerTask 'setConfigsForSubmodules', () -> # generate modules.json with directories inside src # read generated modules list modules = grunt.file.readJSON 'modules.json' concatFiles = grunt.config.get 'concat.js.files' uglifyFiles = grunt.config.get 'uglify.dist.files' for module in modules do (module) -> concatFiles["<%= appConfig.dist %>/#{ module.location }/#{ module.location }.js"] = ["<%= appConfig.app %>/#{ module.location }/{,*/}{,*/}*.js"] uglifyFiles["<%= appConfig.dist %>/#{ module.location }/#{ module.location }.min.js"] = [".tmp/#{ module.location }/**.js"] grunt.config.set 'concat.js.files', concatFiles grunt.config.set 'uglify.dist.files', uglifyFiles # Scan directories and explore submodules grunt.registerTask 'prepareBuild', [ 'folder_list' 'setConfigsForSubmodules' ] grunt.registerTask 'test', [ 'coffee:test', 'jshint', 'clean:server', 'connect:test', 'karma' ] grunt.registerTask 'build', [ 'coffee:app' 'prepareBuild' 'clean:dist' 'concat:js' # 'concat:css' 'ngAnnotate' # 'cssmin' 'uglify' 'ngdocs' ] grunt.registerTask 'default', [ 'coffee' 'test' 'build', 'clean:coffee' ]
58424
'use strict' #! # esef-frontend # https://github.com/egemsoft/esef-frontend # Copyright (c) 2014 Egemsoft # License: MIT # Author: <NAME> # module.exports = (grunt) -> loadGruntTasks = require 'load-grunt-tasks' timeGrunt = require 'time-grunt' loadGruntTasks grunt timeGrunt grunt grunt.initConfig pkg: grunt.file.readJSON 'bower.json' appConfig: app: 'src' name: 'Esef Frontend' dist: 'dist' banner: '/*!\n' + ' * <%= pkg.name %> - v<%= pkg.version %>\n' + ' * <%= pkg.homepage %>\n' + ' * <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> Egemsoft\n' + ' * License: <%= pkg.license %>\n' + ' */\n' coffee: app: options: bare: true expand: true src: ['<%= appConfig.app %>/*.coffee', '<%= appConfig.app %>/*/coffee/{,*/}*.coffee'] ext: '.compiled.js' test: options: bare: true expand: true src: ['test/coffee/**/*.coffee'] ext: '.compiled.js' concat: js: options: banner: '\'use strict\';\n<%= banner %>\n' # remove use strict tags process: (src) -> src.replace /(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1' files: '<%= appConfig.dist %>/bundle/esef-frontend.js': ['<%= appConfig.app %>/{,*/}/{,*/}{,*/}*.js'] css: options: banner: '<%= banner %>\n' files: '<%= appConfig.dist %>/bundle/esef-frontend.css': ['<%= appConfig.app %>/{,*/}styles/{,*/}*.css'] connect: test: options: port: 9001 base: [ '.tmp' 'test' '<%= appConfig.app %>' ] clean: dist: dot: true src: [ '.tmp' '<%= appConfig.dist %>/*' '!<%= appConfig.dist %>/.git*' ] coffee: src: [ '<%= appConfig.app %>/app.compiled.js', '<%= appConfig.app %>/*/coffee/{,*/}*.compiled.js' 'test/coffee/{,*/}{,*/}{,*/}*.compiled.js' ] server: '.tmp' jshint: options: jshintrc: '.jshintrc' all: [ 'Gruntfile.js' '<%= appConfig.app %>/{,*/}{,*/}{,*/}*.js' ] cssmin: dist: files: '<%= appConfig.dist %>/css/esef-frontend.min.css': [ '.tmp/styles/{,*/}*.css' '<%= appConfig.app %>/{,*/}styles/{,*/}*.css' ] karma: unit: configFile: 'karma.conf.js' singleRun: true ngAnnotate: dist: files: [ expand: true, cwd: '<%= appConfig.dist %>/' src: '{,*/}*.js' dest: '.tmp' ] uglify: dist: files: '<%= appConfig.dist %>/bundle/esef-frontend.min.js': ['.tmp/bundle/**.js'] ngdocs: options: dest: 'docs' html5Mode: false title: '<%= appConfig.name %> Documentation' all: ['<%= appConfig.app %>/{,*/}{,*/}{,*/}*.js'] 'folder_list': options: files: false folders: true files: src: ['*'] cwd: 'src/' dest: 'modules.json' # set concat and uglify files configs dynamically grunt.registerTask 'setConfigsForSubmodules', () -> # generate modules.json with directories inside src # read generated modules list modules = grunt.file.readJSON 'modules.json' concatFiles = grunt.config.get 'concat.js.files' uglifyFiles = grunt.config.get 'uglify.dist.files' for module in modules do (module) -> concatFiles["<%= appConfig.dist %>/#{ module.location }/#{ module.location }.js"] = ["<%= appConfig.app %>/#{ module.location }/{,*/}{,*/}*.js"] uglifyFiles["<%= appConfig.dist %>/#{ module.location }/#{ module.location }.min.js"] = [".tmp/#{ module.location }/**.js"] grunt.config.set 'concat.js.files', concatFiles grunt.config.set 'uglify.dist.files', uglifyFiles # Scan directories and explore submodules grunt.registerTask 'prepareBuild', [ 'folder_list' 'setConfigsForSubmodules' ] grunt.registerTask 'test', [ 'coffee:test', 'jshint', 'clean:server', 'connect:test', 'karma' ] grunt.registerTask 'build', [ 'coffee:app' 'prepareBuild' 'clean:dist' 'concat:js' # 'concat:css' 'ngAnnotate' # 'cssmin' 'uglify' 'ngdocs' ] grunt.registerTask 'default', [ 'coffee' 'test' 'build', 'clean:coffee' ]
true
'use strict' #! # esef-frontend # https://github.com/egemsoft/esef-frontend # Copyright (c) 2014 Egemsoft # License: MIT # Author: PI:NAME:<NAME>END_PI # module.exports = (grunt) -> loadGruntTasks = require 'load-grunt-tasks' timeGrunt = require 'time-grunt' loadGruntTasks grunt timeGrunt grunt grunt.initConfig pkg: grunt.file.readJSON 'bower.json' appConfig: app: 'src' name: 'Esef Frontend' dist: 'dist' banner: '/*!\n' + ' * <%= pkg.name %> - v<%= pkg.version %>\n' + ' * <%= pkg.homepage %>\n' + ' * <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> Egemsoft\n' + ' * License: <%= pkg.license %>\n' + ' */\n' coffee: app: options: bare: true expand: true src: ['<%= appConfig.app %>/*.coffee', '<%= appConfig.app %>/*/coffee/{,*/}*.coffee'] ext: '.compiled.js' test: options: bare: true expand: true src: ['test/coffee/**/*.coffee'] ext: '.compiled.js' concat: js: options: banner: '\'use strict\';\n<%= banner %>\n' # remove use strict tags process: (src) -> src.replace /(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1' files: '<%= appConfig.dist %>/bundle/esef-frontend.js': ['<%= appConfig.app %>/{,*/}/{,*/}{,*/}*.js'] css: options: banner: '<%= banner %>\n' files: '<%= appConfig.dist %>/bundle/esef-frontend.css': ['<%= appConfig.app %>/{,*/}styles/{,*/}*.css'] connect: test: options: port: 9001 base: [ '.tmp' 'test' '<%= appConfig.app %>' ] clean: dist: dot: true src: [ '.tmp' '<%= appConfig.dist %>/*' '!<%= appConfig.dist %>/.git*' ] coffee: src: [ '<%= appConfig.app %>/app.compiled.js', '<%= appConfig.app %>/*/coffee/{,*/}*.compiled.js' 'test/coffee/{,*/}{,*/}{,*/}*.compiled.js' ] server: '.tmp' jshint: options: jshintrc: '.jshintrc' all: [ 'Gruntfile.js' '<%= appConfig.app %>/{,*/}{,*/}{,*/}*.js' ] cssmin: dist: files: '<%= appConfig.dist %>/css/esef-frontend.min.css': [ '.tmp/styles/{,*/}*.css' '<%= appConfig.app %>/{,*/}styles/{,*/}*.css' ] karma: unit: configFile: 'karma.conf.js' singleRun: true ngAnnotate: dist: files: [ expand: true, cwd: '<%= appConfig.dist %>/' src: '{,*/}*.js' dest: '.tmp' ] uglify: dist: files: '<%= appConfig.dist %>/bundle/esef-frontend.min.js': ['.tmp/bundle/**.js'] ngdocs: options: dest: 'docs' html5Mode: false title: '<%= appConfig.name %> Documentation' all: ['<%= appConfig.app %>/{,*/}{,*/}{,*/}*.js'] 'folder_list': options: files: false folders: true files: src: ['*'] cwd: 'src/' dest: 'modules.json' # set concat and uglify files configs dynamically grunt.registerTask 'setConfigsForSubmodules', () -> # generate modules.json with directories inside src # read generated modules list modules = grunt.file.readJSON 'modules.json' concatFiles = grunt.config.get 'concat.js.files' uglifyFiles = grunt.config.get 'uglify.dist.files' for module in modules do (module) -> concatFiles["<%= appConfig.dist %>/#{ module.location }/#{ module.location }.js"] = ["<%= appConfig.app %>/#{ module.location }/{,*/}{,*/}*.js"] uglifyFiles["<%= appConfig.dist %>/#{ module.location }/#{ module.location }.min.js"] = [".tmp/#{ module.location }/**.js"] grunt.config.set 'concat.js.files', concatFiles grunt.config.set 'uglify.dist.files', uglifyFiles # Scan directories and explore submodules grunt.registerTask 'prepareBuild', [ 'folder_list' 'setConfigsForSubmodules' ] grunt.registerTask 'test', [ 'coffee:test', 'jshint', 'clean:server', 'connect:test', 'karma' ] grunt.registerTask 'build', [ 'coffee:app' 'prepareBuild' 'clean:dist' 'concat:js' # 'concat:css' 'ngAnnotate' # 'cssmin' 'uglify' 'ngdocs' ] grunt.registerTask 'default', [ 'coffee' 'test' 'build', 'clean:coffee' ]
[ { "context": " 'copStart',\n 'A crooked cop'\n '''\n Dentley thumbs the stack of bills to make sure you aren't", "end": 245, "score": 0.9657688140869141, "start": 238, "tag": "NAME", "value": "Dentley" }, { "context": "k of bills to make sure you aren't shorting him. \...
src/coffee/game/cop.coffee
arashikou/exper3-2015
0
angular.module 'gameDefinition.copStories', ['qbn.edsl', 'gameDefinition.enums'] .run (qbnEdsl, enums) -> {storylet, choice, reqs, consq} = qbnEdsl {leads} = enums storylet 'copStart', 'A crooked cop' ''' Dentley thumbs the stack of bills to make sure you aren't shorting him. "Horace Brown, eh? Funny you should mention him. That name just came across my desk this morning." You ask whether this means the police are going to investigate the disappearance after all. "No, no, nothing like that. His _alleged_ disappearance…" Something gives even Dentley pause. "That investigation is being shut down from a very high level. No, he came up as a person of interest in another case. Of course, as no one can find him, that's a request I am putting no effort into fulfilling." "There was a body. Washed up on the south banks near the granary district. It also vanished before we could bring it in. I don't know any more than that, but someone thinks it's tied to Brown, somehow, so it's probably of interest to you." ''' consequences: bluebacks: consq.decrease 10 lead: consq.set leads.cop cop: (quality) -> quality.value++ 'Officer Dentley has given you a tip about a body.' progress: consq.set 0 storylet 'cop1', 'Follow up on Dentley\'s tip' ''' You need to find this body before the police do. ''' choices: [ choice 'cop1Rumor', 'Connect the dots' 'Some of these rumors you\'re hearing must be about the body.' visible: progress: reqs.lt 7 active: rumor: reqs.gte 3 choice 'cop1Bluebacks', 'Pay for info' 'Unlike the police, you\'re willing to pay for good info.' visible: progress: reqs.lt 7 active: bluebacks: reqs.gte 3 choice 'cop1CantripUp', 'Hire a scryer' 'Magic is the modern way, after all.' visible: progress: reqs.lt 7 active: cantripUp: reqs.gte 3 choice 'cop1Solve', 'Somebody has been found' 'You know where the body went. You can only hope there\'s enough left to ID.' active: progress: reqs.gte 7 ] storylet 'cop1Rumor', 'Connect the dots' ''' With your info, you are able to narrow down the locations the body could have gone to. ''' consequences: rumor: consq.decrease 3 progress: consq.increase 1 storylet 'cop1Bluebacks', 'Pay for info' ''' You find a few people who saw the body before it was moved or saw it being moved. Whoever it was has them too scared to name names, but you can feel your net closing. ''' consequences: bluebacks: consq.decrease 3 progress: consq.increase 1 storylet 'cop1CantripUp', 'Hire a scryer' ''' You can't afford a top-rate scryer, but the one you _can_ afford gives your some tantalizing and useful clues about the body's current disposition. ''' consequences: cantripUp: consq.decrease 3 progress: consq.increase 1 storylet 'cop1Solve', 'Not much left' ''' You burst into the warehouse and order everyone on the floor. Like terrified lambs, they all comply. Despite their sick tendencies, these men and women aren't savage or prepared to defend themselves. They're lucky you found them and their crime first; the police might have come in with guns blazing. They're "ghouls," or at least that's how they fancy themselves. People who think this era of casual magic gives them the right to appropriate old cultural traditions and use them as a cover for their twisted desires. You gather what's left of the body in a sack and warn them to get lost before the police arrive. You make haste to the precinct before the body starts to smell, but not before taking a peek for yourself. There's not much left, but what's there is confusing. The body is female, unqestionably. There are bits of clothing from a dress similar to the one Mrs. Brown was wearing the day she walked into your office. Also a broach that's identical to one you've seen at the Brown household. And judging by the time of its discovery and its state at the time, this person probably died within a day before or after Mr. Brown disappearing. There's no hope of identifying this person now, but this is definitely tied to your case somehow. ''' consequences: evidence: consq.increase 2 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' cop: (quality) -> quality.value++ 'You found a body, or at least what\'s left of it.' progress: consq.set 0 return
10265
angular.module 'gameDefinition.copStories', ['qbn.edsl', 'gameDefinition.enums'] .run (qbnEdsl, enums) -> {storylet, choice, reqs, consq} = qbnEdsl {leads} = enums storylet 'copStart', 'A crooked cop' ''' <NAME> thumbs the stack of bills to make sure you aren't shorting him. "<NAME>, eh? Funny you should mention him. That name just came across my desk this morning." You ask whether this means the police are going to investigate the disappearance after all. "No, no, nothing like that. His _alleged_ disappearance…" Something gives even Dentley pause. "That investigation is being shut down from a very high level. No, he came up as a person of interest in another case. Of course, as no one can find him, that's a request I am putting no effort into fulfilling." "There was a body. Washed up on the south banks near the granary district. It also vanished before we could bring it in. I don't know any more than that, but someone thinks it's tied to <NAME>, somehow, so it's probably of interest to you." ''' consequences: bluebacks: consq.decrease 10 lead: consq.set leads.cop cop: (quality) -> quality.value++ 'Officer <NAME> has given you a tip about a body.' progress: consq.set 0 storylet 'cop1', 'Follow up on Dentley\'s tip' ''' You need to find this body before the police do. ''' choices: [ choice 'cop1Rumor', 'Connect the dots' 'Some of these rumors you\'re hearing must be about the body.' visible: progress: reqs.lt 7 active: rumor: reqs.gte 3 choice 'cop1Bluebacks', 'Pay for info' 'Unlike the police, you\'re willing to pay for good info.' visible: progress: reqs.lt 7 active: bluebacks: reqs.gte 3 choice 'cop1CantripUp', 'Hire a scryer' 'Magic is the modern way, after all.' visible: progress: reqs.lt 7 active: cantripUp: reqs.gte 3 choice 'cop1Solve', 'Somebody has been found' 'You know where the body went. You can only hope there\'s enough left to ID.' active: progress: reqs.gte 7 ] storylet 'cop1Rumor', 'Connect the dots' ''' With your info, you are able to narrow down the locations the body could have gone to. ''' consequences: rumor: consq.decrease 3 progress: consq.increase 1 storylet 'cop1Bluebacks', 'Pay for info' ''' You find a few people who saw the body before it was moved or saw it being moved. Whoever it was has them too scared to name names, but you can feel your net closing. ''' consequences: bluebacks: consq.decrease 3 progress: consq.increase 1 storylet 'cop1CantripUp', 'Hire a scryer' ''' You can't afford a top-rate scryer, but the one you _can_ afford gives your some tantalizing and useful clues about the body's current disposition. ''' consequences: cantripUp: consq.decrease 3 progress: consq.increase 1 storylet 'cop1Solve', 'Not much left' ''' You burst into the warehouse and order everyone on the floor. Like terrified lambs, they all comply. Despite their sick tendencies, these men and women aren't savage or prepared to defend themselves. They're lucky you found them and their crime first; the police might have come in with guns blazing. They're "ghouls," or at least that's how they fancy themselves. People who think this era of casual magic gives them the right to appropriate old cultural traditions and use them as a cover for their twisted desires. You gather what's left of the body in a sack and warn them to get lost before the police arrive. You make haste to the precinct before the body starts to smell, but not before taking a peek for yourself. There's not much left, but what's there is confusing. The body is female, unqestionably. There are bits of clothing from a dress similar to the one <NAME>rs<NAME>. <NAME> was wearing the day she walked into your office. Also a broach that's identical to one you've seen at the Brown household. And judging by the time of its discovery and its state at the time, this person probably died within a day before or after Mr. Brown disappearing. There's no hope of identifying this person now, but this is definitely tied to your case somehow. ''' consequences: evidence: consq.increase 2 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' cop: (quality) -> quality.value++ 'You found a body, or at least what\'s left of it.' progress: consq.set 0 return
true
angular.module 'gameDefinition.copStories', ['qbn.edsl', 'gameDefinition.enums'] .run (qbnEdsl, enums) -> {storylet, choice, reqs, consq} = qbnEdsl {leads} = enums storylet 'copStart', 'A crooked cop' ''' PI:NAME:<NAME>END_PI thumbs the stack of bills to make sure you aren't shorting him. "PI:NAME:<NAME>END_PI, eh? Funny you should mention him. That name just came across my desk this morning." You ask whether this means the police are going to investigate the disappearance after all. "No, no, nothing like that. His _alleged_ disappearance…" Something gives even Dentley pause. "That investigation is being shut down from a very high level. No, he came up as a person of interest in another case. Of course, as no one can find him, that's a request I am putting no effort into fulfilling." "There was a body. Washed up on the south banks near the granary district. It also vanished before we could bring it in. I don't know any more than that, but someone thinks it's tied to PI:NAME:<NAME>END_PI, somehow, so it's probably of interest to you." ''' consequences: bluebacks: consq.decrease 10 lead: consq.set leads.cop cop: (quality) -> quality.value++ 'Officer PI:NAME:<NAME>END_PI has given you a tip about a body.' progress: consq.set 0 storylet 'cop1', 'Follow up on Dentley\'s tip' ''' You need to find this body before the police do. ''' choices: [ choice 'cop1Rumor', 'Connect the dots' 'Some of these rumors you\'re hearing must be about the body.' visible: progress: reqs.lt 7 active: rumor: reqs.gte 3 choice 'cop1Bluebacks', 'Pay for info' 'Unlike the police, you\'re willing to pay for good info.' visible: progress: reqs.lt 7 active: bluebacks: reqs.gte 3 choice 'cop1CantripUp', 'Hire a scryer' 'Magic is the modern way, after all.' visible: progress: reqs.lt 7 active: cantripUp: reqs.gte 3 choice 'cop1Solve', 'Somebody has been found' 'You know where the body went. You can only hope there\'s enough left to ID.' active: progress: reqs.gte 7 ] storylet 'cop1Rumor', 'Connect the dots' ''' With your info, you are able to narrow down the locations the body could have gone to. ''' consequences: rumor: consq.decrease 3 progress: consq.increase 1 storylet 'cop1Bluebacks', 'Pay for info' ''' You find a few people who saw the body before it was moved or saw it being moved. Whoever it was has them too scared to name names, but you can feel your net closing. ''' consequences: bluebacks: consq.decrease 3 progress: consq.increase 1 storylet 'cop1CantripUp', 'Hire a scryer' ''' You can't afford a top-rate scryer, but the one you _can_ afford gives your some tantalizing and useful clues about the body's current disposition. ''' consequences: cantripUp: consq.decrease 3 progress: consq.increase 1 storylet 'cop1Solve', 'Not much left' ''' You burst into the warehouse and order everyone on the floor. Like terrified lambs, they all comply. Despite their sick tendencies, these men and women aren't savage or prepared to defend themselves. They're lucky you found them and their crime first; the police might have come in with guns blazing. They're "ghouls," or at least that's how they fancy themselves. People who think this era of casual magic gives them the right to appropriate old cultural traditions and use them as a cover for their twisted desires. You gather what's left of the body in a sack and warn them to get lost before the police arrive. You make haste to the precinct before the body starts to smell, but not before taking a peek for yourself. There's not much left, but what's there is confusing. The body is female, unqestionably. There are bits of clothing from a dress similar to the one PI:NAME:<NAME>END_PIrsPI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI was wearing the day she walked into your office. Also a broach that's identical to one you've seen at the Brown household. And judging by the time of its discovery and its state at the time, this person probably died within a day before or after Mr. Brown disappearing. There's no hope of identifying this person now, but this is definitely tied to your case somehow. ''' consequences: evidence: consq.increase 2 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' cop: (quality) -> quality.value++ 'You found a body, or at least what\'s left of it.' progress: consq.set 0 return
[ { "context": "L5 Canvas.\n#\n# * [in GitHub](https://github.com/curran/canvas-vis)\n# * [Examples](examples.html)\n# *", "end": 146, "score": 0.999121904373169, "start": 140, "tag": "USERNAME", "value": "curran" }, { "context": "../tests/index.html), [Source](https://github.com...
src/AnIntroduction.coffee
curran/canvas-vis
2
# Canvas-Vis # ========== # # A JavaScript library for information visualization using HTML5 Canvas. # # * [in GitHub](https://github.com/curran/canvas-vis) # * [Examples](examples.html) # * Unit Tests: [Run](../tests/index.html), [Source](https://github.com/curran/canvas-vis/tree/master/tests/spec) # # The project was just recently started in April 2013, and is not yet usable. # # Canvas-vis consists of a set of [AMD](http://requirejs.org/) modules written in [CoffeeScript](http://coffeescript.org/) that leverage [Backbone.js](http://backbonejs.org/) and [Underscore.js](http://underscorejs.org/). # # Modules assume Backbone and Underscore are loaded as script tags and expose the globals `Backbone` and `_`. # # --Curran Kelleher, April 2013
414
# Canvas-Vis # ========== # # A JavaScript library for information visualization using HTML5 Canvas. # # * [in GitHub](https://github.com/curran/canvas-vis) # * [Examples](examples.html) # * Unit Tests: [Run](../tests/index.html), [Source](https://github.com/curran/canvas-vis/tree/master/tests/spec) # # The project was just recently started in April 2013, and is not yet usable. # # Canvas-vis consists of a set of [AMD](http://requirejs.org/) modules written in [CoffeeScript](http://coffeescript.org/) that leverage [Backbone.js](http://backbonejs.org/) and [Underscore.js](http://underscorejs.org/). # # Modules assume Backbone and Underscore are loaded as script tags and expose the globals `Backbone` and `_`. # # --<NAME>, April 2013
true
# Canvas-Vis # ========== # # A JavaScript library for information visualization using HTML5 Canvas. # # * [in GitHub](https://github.com/curran/canvas-vis) # * [Examples](examples.html) # * Unit Tests: [Run](../tests/index.html), [Source](https://github.com/curran/canvas-vis/tree/master/tests/spec) # # The project was just recently started in April 2013, and is not yet usable. # # Canvas-vis consists of a set of [AMD](http://requirejs.org/) modules written in [CoffeeScript](http://coffeescript.org/) that leverage [Backbone.js](http://backbonejs.org/) and [Underscore.js](http://underscorejs.org/). # # Modules assume Backbone and Underscore are loaded as script tags and expose the globals `Backbone` and `_`. # # --PI:NAME:<NAME>END_PI, April 2013
[ { "context": "ew Tests for no-extra-boolean-cast rule.\n# @author Brandon Mills\n###\n\n'use strict'\n\n#-----------------------------", "end": 82, "score": 0.9993265867233276, "start": 69, "tag": "NAME", "value": "Brandon Mills" } ]
src/tests/rules/no-extra-boolean-cast.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-extra-boolean-cast rule. # @author Brandon Mills ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-extra-boolean-cast' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-extra-boolean-cast', rule, valid: [ 'foo = !!bar' '-> !!bar' 'foo = if bar() then !!baz else !!bat' 'foo = Boolean(bar)' '-> return Boolean(bar)' 'foo = if bar() then Boolean(baz) else Boolean(bat)' 'if (new Boolean(foo)) then ;' ] invalid: [ code: 'if (!!foo) then ;' # output: 'if (foo) then ;' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'while (!!foo) then ;' # output: 'while (foo) then ;' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'if !!foo then bar else baz' # output: 'if foo then bar else baz' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: '!!!foo' # output: '!foo' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'Boolean(!!foo)' # output: 'Boolean(foo)' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'new Boolean(!!foo)' # output: 'new Boolean(foo)' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'if (Boolean(foo)) then ;' # output: 'if (foo) then ;' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: 'while (Boolean(foo)) then ;' # output: 'while (foo) then ;' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: 'if Boolean foo then bar else baz' # output: 'if foo then bar else baz' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean foo' # output: '!foo' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo and bar)' # output: '!(foo and bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo + bar)' # output: '!(foo + bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(+foo)' # output: '!+foo' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo())' # output: '!foo()' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo = bar)' # output: '!(foo = bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(...foo)' # output: null errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo; bar())' # output: null errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean((foo; bar()))' # output: '!(foo; bar())' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean()' # output: 'true' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!(Boolean())' # output: 'true' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] ]
144935
###* # @fileoverview Tests for no-extra-boolean-cast rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-extra-boolean-cast' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-extra-boolean-cast', rule, valid: [ 'foo = !!bar' '-> !!bar' 'foo = if bar() then !!baz else !!bat' 'foo = Boolean(bar)' '-> return Boolean(bar)' 'foo = if bar() then Boolean(baz) else Boolean(bat)' 'if (new Boolean(foo)) then ;' ] invalid: [ code: 'if (!!foo) then ;' # output: 'if (foo) then ;' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'while (!!foo) then ;' # output: 'while (foo) then ;' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'if !!foo then bar else baz' # output: 'if foo then bar else baz' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: '!!!foo' # output: '!foo' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'Boolean(!!foo)' # output: 'Boolean(foo)' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'new Boolean(!!foo)' # output: 'new Boolean(foo)' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'if (Boolean(foo)) then ;' # output: 'if (foo) then ;' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: 'while (Boolean(foo)) then ;' # output: 'while (foo) then ;' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: 'if Boolean foo then bar else baz' # output: 'if foo then bar else baz' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean foo' # output: '!foo' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo and bar)' # output: '!(foo and bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo + bar)' # output: '!(foo + bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(+foo)' # output: '!+foo' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo())' # output: '!foo()' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo = bar)' # output: '!(foo = bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(...foo)' # output: null errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo; bar())' # output: null errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean((foo; bar()))' # output: '!(foo; bar())' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean()' # output: 'true' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!(Boolean())' # output: 'true' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] ]
true
###* # @fileoverview Tests for no-extra-boolean-cast rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-extra-boolean-cast' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-extra-boolean-cast', rule, valid: [ 'foo = !!bar' '-> !!bar' 'foo = if bar() then !!baz else !!bat' 'foo = Boolean(bar)' '-> return Boolean(bar)' 'foo = if bar() then Boolean(baz) else Boolean(bat)' 'if (new Boolean(foo)) then ;' ] invalid: [ code: 'if (!!foo) then ;' # output: 'if (foo) then ;' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'while (!!foo) then ;' # output: 'while (foo) then ;' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'if !!foo then bar else baz' # output: 'if foo then bar else baz' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: '!!!foo' # output: '!foo' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'Boolean(!!foo)' # output: 'Boolean(foo)' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'new Boolean(!!foo)' # output: 'new Boolean(foo)' errors: [ messageId: 'unexpectedNegation' type: 'UnaryExpression' ] , code: 'if (Boolean(foo)) then ;' # output: 'if (foo) then ;' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: 'while (Boolean(foo)) then ;' # output: 'while (foo) then ;' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: 'if Boolean foo then bar else baz' # output: 'if foo then bar else baz' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean foo' # output: '!foo' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo and bar)' # output: '!(foo and bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo + bar)' # output: '!(foo + bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(+foo)' # output: '!+foo' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo())' # output: '!foo()' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo = bar)' # output: '!(foo = bar)' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(...foo)' # output: null errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean(foo; bar())' # output: null errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean((foo; bar()))' # output: '!(foo; bar())' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!Boolean()' # output: 'true' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] , code: '!(Boolean())' # output: 'true' errors: [ messageId: 'unexpectedCall' type: 'CallExpression' ] ]
[ { "context": "'getName', ->\n equal(Users.first().getName(), \"ben\")\n\n test \"getFriends\", ->\n equal(Users.first(", "end": 278, "score": 0.9417794942855835, "start": 275, "tag": "NAME", "value": "ben" }, { "context": " 0)\n \n u = new User\n u.set { friends : ['j...
test/models/user_test.coffee
bnolan/diaspora-x2
7
runTests -> module('user model'); new UserFixtures # If we were using jasmine or qunit-mock we could stub... :/ window.$c = { getChannel : -> # ... } test 'model exists', -> ok(User) test 'getName', -> equal(Users.first().getName(), "ben") test "getFriends", -> equal(Users.first().getFriends().length, 0) u = new User u.set { friends : ['jim@example.com'] } equal(u.getFriends()[0].getName(), "jim") test "addFriend", -> u = new User equal u.getFriends().length, 0 u.addFriend 'jim@example.com' equal u.getFriends().length, 1 u.addFriend 'jim@example.com' equal u.getFriends().length, 1 u.addFriend 'zigzug@example.com' equal u.getFriends().length, 2
15079
runTests -> module('user model'); new UserFixtures # If we were using jasmine or qunit-mock we could stub... :/ window.$c = { getChannel : -> # ... } test 'model exists', -> ok(User) test 'getName', -> equal(Users.first().getName(), "<NAME>") test "getFriends", -> equal(Users.first().getFriends().length, 0) u = new User u.set { friends : ['<EMAIL>'] } equal(u.getFriends()[0].getName(), "<NAME>") test "addFriend", -> u = new User equal u.getFriends().length, 0 u.addFriend '<EMAIL>' equal u.getFriends().length, 1 u.addFriend '<EMAIL>' equal u.getFriends().length, 1 u.addFriend '<EMAIL>' equal u.getFriends().length, 2
true
runTests -> module('user model'); new UserFixtures # If we were using jasmine or qunit-mock we could stub... :/ window.$c = { getChannel : -> # ... } test 'model exists', -> ok(User) test 'getName', -> equal(Users.first().getName(), "PI:NAME:<NAME>END_PI") test "getFriends", -> equal(Users.first().getFriends().length, 0) u = new User u.set { friends : ['PI:EMAIL:<EMAIL>END_PI'] } equal(u.getFriends()[0].getName(), "PI:NAME:<NAME>END_PI") test "addFriend", -> u = new User equal u.getFriends().length, 0 u.addFriend 'PI:EMAIL:<EMAIL>END_PI' equal u.getFriends().length, 1 u.addFriend 'PI:EMAIL:<EMAIL>END_PI' equal u.getFriends().length, 1 u.addFriend 'PI:EMAIL:<EMAIL>END_PI' equal u.getFriends().length, 2
[ { "context": "3 Flarebyte.com Ltd. All rights reserved.\nCreator: Olivier Huin\nContributors:\n###\n\n'use strict'\n# Controllers\nfla", "end": 151, "score": 0.9998728036880493, "start": 139, "tag": "NAME", "value": "Olivier Huin" } ]
nodejs/flarebyte.net/0.8/node/flaming/browser/js/controllers22.coffee
flarebyte/wonderful-bazar
0
### GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT) Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved. Creator: Olivier Huin Contributors: ### 'use strict' # Controllers flamingAppControllers = angular.module('flamingApp.controllers', []) flamingAppControllers.controller "ProfileCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.profile = ListAllProfileService.query() ] flamingAppControllers.controller "LoginCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.login = ListAllProfileService.query() ] flamingAppControllers.controller "ComposeCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.compose = ListAllProfileService.query() ] flamingAppControllers.controller "ToReadCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.toRead = ListAllProfileService.query() ] flamingAppControllers.controller "ToDoCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.toDo = ListAllProfileService.query() ] flamingAppControllers.controller "ImportantCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.important = ListAllProfileService.query() ] flamingAppControllers.controller "RecentCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.recent = ListAllProfileService.query() ] flamingAppControllers.controller "SharedCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.shared = ListAllProfileService.query() ] flamingAppControllers.controller "AllCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.all = ListAllProfileService.query() ] flamingAppControllers.controller "NewsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.news = ListAllProfileService.query() ] flamingAppControllers.controller "TrashCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.trash = ListAllProfileService.query() ] flamingAppControllers.controller "DashboardCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.dashboard = ListAllProfileService.query() ] flamingAppControllers.controller "ContactsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.contacts = ListAllProfileService.query() ] flamingAppControllers.controller "SettingsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.settings = ListAllProfileService.query() ] flamingAppControllers.controller "HelpCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.help = ListAllProfileService.query() ] flamingAppControllers.controller "FaqCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.faq = ListAllProfileService.query() ] flamingAppControllers.controller "PrivacyCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.privacy = ListAllProfileService.query() ] flamingAppControllers.controller "TermsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.terms = ListAllProfileService.query() ]
156641
### GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT) Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved. Creator: <NAME> Contributors: ### 'use strict' # Controllers flamingAppControllers = angular.module('flamingApp.controllers', []) flamingAppControllers.controller "ProfileCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.profile = ListAllProfileService.query() ] flamingAppControllers.controller "LoginCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.login = ListAllProfileService.query() ] flamingAppControllers.controller "ComposeCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.compose = ListAllProfileService.query() ] flamingAppControllers.controller "ToReadCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.toRead = ListAllProfileService.query() ] flamingAppControllers.controller "ToDoCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.toDo = ListAllProfileService.query() ] flamingAppControllers.controller "ImportantCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.important = ListAllProfileService.query() ] flamingAppControllers.controller "RecentCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.recent = ListAllProfileService.query() ] flamingAppControllers.controller "SharedCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.shared = ListAllProfileService.query() ] flamingAppControllers.controller "AllCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.all = ListAllProfileService.query() ] flamingAppControllers.controller "NewsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.news = ListAllProfileService.query() ] flamingAppControllers.controller "TrashCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.trash = ListAllProfileService.query() ] flamingAppControllers.controller "DashboardCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.dashboard = ListAllProfileService.query() ] flamingAppControllers.controller "ContactsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.contacts = ListAllProfileService.query() ] flamingAppControllers.controller "SettingsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.settings = ListAllProfileService.query() ] flamingAppControllers.controller "HelpCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.help = ListAllProfileService.query() ] flamingAppControllers.controller "FaqCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.faq = ListAllProfileService.query() ] flamingAppControllers.controller "PrivacyCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.privacy = ListAllProfileService.query() ] flamingAppControllers.controller "TermsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.terms = ListAllProfileService.query() ]
true
### GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT) Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved. Creator: PI:NAME:<NAME>END_PI Contributors: ### 'use strict' # Controllers flamingAppControllers = angular.module('flamingApp.controllers', []) flamingAppControllers.controller "ProfileCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.profile = ListAllProfileService.query() ] flamingAppControllers.controller "LoginCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.login = ListAllProfileService.query() ] flamingAppControllers.controller "ComposeCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.compose = ListAllProfileService.query() ] flamingAppControllers.controller "ToReadCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.toRead = ListAllProfileService.query() ] flamingAppControllers.controller "ToDoCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.toDo = ListAllProfileService.query() ] flamingAppControllers.controller "ImportantCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.important = ListAllProfileService.query() ] flamingAppControllers.controller "RecentCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.recent = ListAllProfileService.query() ] flamingAppControllers.controller "SharedCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.shared = ListAllProfileService.query() ] flamingAppControllers.controller "AllCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.all = ListAllProfileService.query() ] flamingAppControllers.controller "NewsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.news = ListAllProfileService.query() ] flamingAppControllers.controller "TrashCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.trash = ListAllProfileService.query() ] flamingAppControllers.controller "DashboardCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.dashboard = ListAllProfileService.query() ] flamingAppControllers.controller "ContactsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.contacts = ListAllProfileService.query() ] flamingAppControllers.controller "SettingsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.settings = ListAllProfileService.query() ] flamingAppControllers.controller "HelpCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.help = ListAllProfileService.query() ] flamingAppControllers.controller "FaqCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.faq = ListAllProfileService.query() ] flamingAppControllers.controller "PrivacyCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.privacy = ListAllProfileService.query() ] flamingAppControllers.controller "TermsCtrl", ["$scope", "ListAllProfileService", ($scope, ListAllProfileService) -> $scope.terms = ListAllProfileService.query() ]
[ { "context": "r node.js or the browser.\n\nCopyright (c) 2011-2012 Caleb Troughton\nLicensed under the MIT license.\nhttps://raw.githu", "end": 210, "score": 0.9998840689659119, "start": 195, "tag": "NAME", "value": "Caleb Troughton" } ]
src/timeline.coffee
imakewebthings/timeline
30
# setInterval rearranged for CoffeeScript goodness every = (ms, callback) -> setInterval callback, ms ### Timeline: A generic event timeline for node.js or the browser. Copyright (c) 2011-2012 Caleb Troughton Licensed under the MIT license. https://raw.github.com/imakewebthings/timeline/master/MIT-license.txt ### class Timeline # Statics! @defaults: frequency: 100 length: 0 # Begin "private" things. Not really private, just using the lazy # underscore naming to denote their undocumented, internal status. _lastPosition: 0 _position: 0 _timer: -1 _previousTick: 0 _createTick: -> clearInterval @_timer @_timer = every @_options.frequency, @_onTick _onTick: => now = (new Date).getTime() @_updatePositions now @_triggerMarkers() @_previousTick = now @trigger 'tick' @_checkForEnd() _updatePositions: (now) -> @_lastPosition = @_position @_position += now - @_previousTick @_position = @_options.length if @_position > @_options.length _triggerMarkers: -> for marker in @markers marker.backward() if @_lastPosition > marker.time >= @_position marker.forward() if @_lastPosition <= marker.time < @_position _checkForEnd: -> if @_position >= @_options.length @_position = @_options.length @pause() @trigger 'end' # Begin "public" things playing: off # Markers are objects with three properties. To add markers, just # put them in this array. # # time: Number in milliseconds where this marker should live on # the timeline # forward: Function that fires when the timeline moves forward # through the marker. # backward: Function that fires when the timeline moves backward # through the marker. markers: [] # Creates a new Timeline object. Extends the defaults with the # values in the options parameter if passed in. constructor: (options) -> @_options = {} @_options[key] = val for key, val of Timeline.defaults @_options[key] = val for key, val of options @_events = {} # If no parameters are given, this returns the total length of # the timeline in milliseconds. If a number is passed in, it # sets the total length and returns the Timeline for chaining. length: (ms) -> if ms? @_options.length = ms this else @_options.length # If no parameters are given, this returns the frequency at # which the timeline emits tick events in milliseconds. If a # number is passed in, it sets the frequency and returns the # Timeline for chaining. frequency: (ms) -> if ms? @_options.frequency = ms this else @_options.frequency # If no parameters are given, this returns the current position # in the timeline. If a number is passed in, the timeline seeks # to the new position and returns the Timeline for chaining. This # jump will always produce a tick, and may emit an end event if # appropriate. If the number passed in is below 0 or above the # total length the method will seek to the closest possible value # (0 and length, respectively). position: (ms) -> if ms? ms = @_options.length if ms > @_options.length ms = 0 if ms < 0 @_lastPosition = @_position @_position = ms @_triggerMarkers() @trigger 'tick' @_checkForEnd() this else @_position # Begins playing the Timeline. Starts emitting ticks every # "frequency" milliseconds and trigger markers as it goes. # Emits a play event. play: -> unless @playing @playing = on @_previousTick = (new Date).getTime() @_createTick() @trigger 'play' this # Pauses the Timeline. Emits a pause event. pause: -> if @playing @playing = off clearInterval @_timer @trigger 'pause' this # Binds the callback to the event, where "event" is a string # and "callback" is a function. on: (event, callback) -> @_events[event] = [] unless @_events[event] @_events[event].push callback this # If callback is passed in, this unbinds that function from # the event. If no callback is given, all callbacks are unbound. off: (event, callback) -> if @_events[event]? and callback? @_events[event] = (cb for cb in @_events[event] when cb isnt callback) else @_events[event] = [] this # Triggers all callbacks on the given event. Any extra arguments # are passed on to the callbacks. trigger: (event, args...) -> if @_events[event]? callback.apply this, args for callback in @_events[event] this if module? then module.exports = Timeline else @Timeline = Timeline
35181
# setInterval rearranged for CoffeeScript goodness every = (ms, callback) -> setInterval callback, ms ### Timeline: A generic event timeline for node.js or the browser. Copyright (c) 2011-2012 <NAME> Licensed under the MIT license. https://raw.github.com/imakewebthings/timeline/master/MIT-license.txt ### class Timeline # Statics! @defaults: frequency: 100 length: 0 # Begin "private" things. Not really private, just using the lazy # underscore naming to denote their undocumented, internal status. _lastPosition: 0 _position: 0 _timer: -1 _previousTick: 0 _createTick: -> clearInterval @_timer @_timer = every @_options.frequency, @_onTick _onTick: => now = (new Date).getTime() @_updatePositions now @_triggerMarkers() @_previousTick = now @trigger 'tick' @_checkForEnd() _updatePositions: (now) -> @_lastPosition = @_position @_position += now - @_previousTick @_position = @_options.length if @_position > @_options.length _triggerMarkers: -> for marker in @markers marker.backward() if @_lastPosition > marker.time >= @_position marker.forward() if @_lastPosition <= marker.time < @_position _checkForEnd: -> if @_position >= @_options.length @_position = @_options.length @pause() @trigger 'end' # Begin "public" things playing: off # Markers are objects with three properties. To add markers, just # put them in this array. # # time: Number in milliseconds where this marker should live on # the timeline # forward: Function that fires when the timeline moves forward # through the marker. # backward: Function that fires when the timeline moves backward # through the marker. markers: [] # Creates a new Timeline object. Extends the defaults with the # values in the options parameter if passed in. constructor: (options) -> @_options = {} @_options[key] = val for key, val of Timeline.defaults @_options[key] = val for key, val of options @_events = {} # If no parameters are given, this returns the total length of # the timeline in milliseconds. If a number is passed in, it # sets the total length and returns the Timeline for chaining. length: (ms) -> if ms? @_options.length = ms this else @_options.length # If no parameters are given, this returns the frequency at # which the timeline emits tick events in milliseconds. If a # number is passed in, it sets the frequency and returns the # Timeline for chaining. frequency: (ms) -> if ms? @_options.frequency = ms this else @_options.frequency # If no parameters are given, this returns the current position # in the timeline. If a number is passed in, the timeline seeks # to the new position and returns the Timeline for chaining. This # jump will always produce a tick, and may emit an end event if # appropriate. If the number passed in is below 0 or above the # total length the method will seek to the closest possible value # (0 and length, respectively). position: (ms) -> if ms? ms = @_options.length if ms > @_options.length ms = 0 if ms < 0 @_lastPosition = @_position @_position = ms @_triggerMarkers() @trigger 'tick' @_checkForEnd() this else @_position # Begins playing the Timeline. Starts emitting ticks every # "frequency" milliseconds and trigger markers as it goes. # Emits a play event. play: -> unless @playing @playing = on @_previousTick = (new Date).getTime() @_createTick() @trigger 'play' this # Pauses the Timeline. Emits a pause event. pause: -> if @playing @playing = off clearInterval @_timer @trigger 'pause' this # Binds the callback to the event, where "event" is a string # and "callback" is a function. on: (event, callback) -> @_events[event] = [] unless @_events[event] @_events[event].push callback this # If callback is passed in, this unbinds that function from # the event. If no callback is given, all callbacks are unbound. off: (event, callback) -> if @_events[event]? and callback? @_events[event] = (cb for cb in @_events[event] when cb isnt callback) else @_events[event] = [] this # Triggers all callbacks on the given event. Any extra arguments # are passed on to the callbacks. trigger: (event, args...) -> if @_events[event]? callback.apply this, args for callback in @_events[event] this if module? then module.exports = Timeline else @Timeline = Timeline
true
# setInterval rearranged for CoffeeScript goodness every = (ms, callback) -> setInterval callback, ms ### Timeline: A generic event timeline for node.js or the browser. Copyright (c) 2011-2012 PI:NAME:<NAME>END_PI Licensed under the MIT license. https://raw.github.com/imakewebthings/timeline/master/MIT-license.txt ### class Timeline # Statics! @defaults: frequency: 100 length: 0 # Begin "private" things. Not really private, just using the lazy # underscore naming to denote their undocumented, internal status. _lastPosition: 0 _position: 0 _timer: -1 _previousTick: 0 _createTick: -> clearInterval @_timer @_timer = every @_options.frequency, @_onTick _onTick: => now = (new Date).getTime() @_updatePositions now @_triggerMarkers() @_previousTick = now @trigger 'tick' @_checkForEnd() _updatePositions: (now) -> @_lastPosition = @_position @_position += now - @_previousTick @_position = @_options.length if @_position > @_options.length _triggerMarkers: -> for marker in @markers marker.backward() if @_lastPosition > marker.time >= @_position marker.forward() if @_lastPosition <= marker.time < @_position _checkForEnd: -> if @_position >= @_options.length @_position = @_options.length @pause() @trigger 'end' # Begin "public" things playing: off # Markers are objects with three properties. To add markers, just # put them in this array. # # time: Number in milliseconds where this marker should live on # the timeline # forward: Function that fires when the timeline moves forward # through the marker. # backward: Function that fires when the timeline moves backward # through the marker. markers: [] # Creates a new Timeline object. Extends the defaults with the # values in the options parameter if passed in. constructor: (options) -> @_options = {} @_options[key] = val for key, val of Timeline.defaults @_options[key] = val for key, val of options @_events = {} # If no parameters are given, this returns the total length of # the timeline in milliseconds. If a number is passed in, it # sets the total length and returns the Timeline for chaining. length: (ms) -> if ms? @_options.length = ms this else @_options.length # If no parameters are given, this returns the frequency at # which the timeline emits tick events in milliseconds. If a # number is passed in, it sets the frequency and returns the # Timeline for chaining. frequency: (ms) -> if ms? @_options.frequency = ms this else @_options.frequency # If no parameters are given, this returns the current position # in the timeline. If a number is passed in, the timeline seeks # to the new position and returns the Timeline for chaining. This # jump will always produce a tick, and may emit an end event if # appropriate. If the number passed in is below 0 or above the # total length the method will seek to the closest possible value # (0 and length, respectively). position: (ms) -> if ms? ms = @_options.length if ms > @_options.length ms = 0 if ms < 0 @_lastPosition = @_position @_position = ms @_triggerMarkers() @trigger 'tick' @_checkForEnd() this else @_position # Begins playing the Timeline. Starts emitting ticks every # "frequency" milliseconds and trigger markers as it goes. # Emits a play event. play: -> unless @playing @playing = on @_previousTick = (new Date).getTime() @_createTick() @trigger 'play' this # Pauses the Timeline. Emits a pause event. pause: -> if @playing @playing = off clearInterval @_timer @trigger 'pause' this # Binds the callback to the event, where "event" is a string # and "callback" is a function. on: (event, callback) -> @_events[event] = [] unless @_events[event] @_events[event].push callback this # If callback is passed in, this unbinds that function from # the event. If no callback is given, all callbacks are unbound. off: (event, callback) -> if @_events[event]? and callback? @_events[event] = (cb for cb in @_events[event] when cb isnt callback) else @_events[event] = [] this # Triggers all callbacks on the given event. Any extra arguments # are passed on to the callbacks. trigger: (event, args...) -> if @_events[event]? callback.apply this, args for callback in @_events[event] this if module? then module.exports = Timeline else @Timeline = Timeline
[ { "context": "playlists at all', () ->\r\n name = 'Rock and Roll'\r\n player = result.getPlayer name\r", "end": 2692, "score": 0.9818549752235413, "start": 2679, "tag": "NAME", "value": "Rock and Roll" }, { "context": "when id is provided', ->\r\n ...
Sample exam/tests/task-1-tests.coffee
madmarks/JavaScript-OOP
0
expect = require('chai').expect result = require('../tasks/task-1')() describe 'Sample exam tests', () -> describe 'Players', () -> describe 'With valid input', () -> it 'expect getPlayer to exist, to be a function and to take a single parameter', () -> expect(result.getPlayer).to.exist expect(result.getPlayer).to.be.a 'function' expect(result.getPlayer).to.have.length 1 it 'expect getPlayer to return a new player instance, with provided name and generated id', () -> name = 'Rock and roll' player = result.getPlayer name expect(player).to.exist expect(player).to.be.an 'object' expect(player.name).to.equal name expect(player.id).to.exist it 'expect player.addPlaylist() to exists, to be a function, to take a single parameter and to enable chaining', () -> name = 'Rock and roll' player = result.getPlayer name playlist = result.getPlaylist name expect(player.addPlaylist).to.exist expect(player.addPlaylist).to.be.a 'function' expect(player.addPlaylist).to.have.length 1 returnedPlayer = player.addPlaylist playlist expect(returnedPlayer).to.equal player it 'expect player.getPlaylistById() to return previously added playlist, when no other playlists', () -> name = 'Rock and Roll' player = result.getPlayer name playlist = result.getPlaylist name returnedPlaylist = player.addPlaylist(playlist) .getPlaylistById(playlist.id) expect(returnedPlaylist).to.equal(playlist) it 'expect player.getPlaylistById() to return previously added playlist, when there are other playlists', () -> name = 'Rock and Roll' player = result.getPlayer name playlist = result.getPlaylist name count = 5 for i in [0..count] player.addPlaylist(result.getPlaylist(name + i)) player.addPlaylist(playlist) for i in [0..count] player.addPlaylist(result.getPlaylist(name + i)) expect(player.getPlaylistById playlist.id).to.equal(playlist) it 'expect player.getPlaylistById() with id, not contianed in the player to return null, when there are other playlists and when there are no playlists at all', () -> name = 'Rock and Roll' player = result.getPlayer name expect(player.getPlaylist(2)).to.be.null count = 5 ids = {} for i in [0..count] playlist = result.getPlaylist(name + i) player.addPlaylist(playlist) ids[playlist.id] = true invalidID = (Math.random() * 100000000) | 0 while ids[invalidID] invalidID = (Math.random() * 100000000) | 0 expect(player.getPlaylist(invalidID)).to.be.null it 'expect player.removePlaylist() to remove the playlist, when id is provided', -> name = 'Rock and Roll' player = result.getPlayer name playlist = result.getPlaylist name player.addPlaylist(playlist) .removePlaylist(playlist.id) expect(player.getPlaylistById(playlist.id)).to.be.null for i in [0..5] player.addPlaylist(name + i)
180128
expect = require('chai').expect result = require('../tasks/task-1')() describe 'Sample exam tests', () -> describe 'Players', () -> describe 'With valid input', () -> it 'expect getPlayer to exist, to be a function and to take a single parameter', () -> expect(result.getPlayer).to.exist expect(result.getPlayer).to.be.a 'function' expect(result.getPlayer).to.have.length 1 it 'expect getPlayer to return a new player instance, with provided name and generated id', () -> name = 'Rock and roll' player = result.getPlayer name expect(player).to.exist expect(player).to.be.an 'object' expect(player.name).to.equal name expect(player.id).to.exist it 'expect player.addPlaylist() to exists, to be a function, to take a single parameter and to enable chaining', () -> name = 'Rock and roll' player = result.getPlayer name playlist = result.getPlaylist name expect(player.addPlaylist).to.exist expect(player.addPlaylist).to.be.a 'function' expect(player.addPlaylist).to.have.length 1 returnedPlayer = player.addPlaylist playlist expect(returnedPlayer).to.equal player it 'expect player.getPlaylistById() to return previously added playlist, when no other playlists', () -> name = 'Rock and Roll' player = result.getPlayer name playlist = result.getPlaylist name returnedPlaylist = player.addPlaylist(playlist) .getPlaylistById(playlist.id) expect(returnedPlaylist).to.equal(playlist) it 'expect player.getPlaylistById() to return previously added playlist, when there are other playlists', () -> name = 'Rock and Roll' player = result.getPlayer name playlist = result.getPlaylist name count = 5 for i in [0..count] player.addPlaylist(result.getPlaylist(name + i)) player.addPlaylist(playlist) for i in [0..count] player.addPlaylist(result.getPlaylist(name + i)) expect(player.getPlaylistById playlist.id).to.equal(playlist) it 'expect player.getPlaylistById() with id, not contianed in the player to return null, when there are other playlists and when there are no playlists at all', () -> name = '<NAME>' player = result.getPlayer name expect(player.getPlaylist(2)).to.be.null count = 5 ids = {} for i in [0..count] playlist = result.getPlaylist(name + i) player.addPlaylist(playlist) ids[playlist.id] = true invalidID = (Math.random() * 100000000) | 0 while ids[invalidID] invalidID = (Math.random() * 100000000) | 0 expect(player.getPlaylist(invalidID)).to.be.null it 'expect player.removePlaylist() to remove the playlist, when id is provided', -> name = '<NAME>' player = result.getPlayer name playlist = result.getPlaylist name player.addPlaylist(playlist) .removePlaylist(playlist.id) expect(player.getPlaylistById(playlist.id)).to.be.null for i in [0..5] player.addPlaylist(name + i)
true
expect = require('chai').expect result = require('../tasks/task-1')() describe 'Sample exam tests', () -> describe 'Players', () -> describe 'With valid input', () -> it 'expect getPlayer to exist, to be a function and to take a single parameter', () -> expect(result.getPlayer).to.exist expect(result.getPlayer).to.be.a 'function' expect(result.getPlayer).to.have.length 1 it 'expect getPlayer to return a new player instance, with provided name and generated id', () -> name = 'Rock and roll' player = result.getPlayer name expect(player).to.exist expect(player).to.be.an 'object' expect(player.name).to.equal name expect(player.id).to.exist it 'expect player.addPlaylist() to exists, to be a function, to take a single parameter and to enable chaining', () -> name = 'Rock and roll' player = result.getPlayer name playlist = result.getPlaylist name expect(player.addPlaylist).to.exist expect(player.addPlaylist).to.be.a 'function' expect(player.addPlaylist).to.have.length 1 returnedPlayer = player.addPlaylist playlist expect(returnedPlayer).to.equal player it 'expect player.getPlaylistById() to return previously added playlist, when no other playlists', () -> name = 'Rock and Roll' player = result.getPlayer name playlist = result.getPlaylist name returnedPlaylist = player.addPlaylist(playlist) .getPlaylistById(playlist.id) expect(returnedPlaylist).to.equal(playlist) it 'expect player.getPlaylistById() to return previously added playlist, when there are other playlists', () -> name = 'Rock and Roll' player = result.getPlayer name playlist = result.getPlaylist name count = 5 for i in [0..count] player.addPlaylist(result.getPlaylist(name + i)) player.addPlaylist(playlist) for i in [0..count] player.addPlaylist(result.getPlaylist(name + i)) expect(player.getPlaylistById playlist.id).to.equal(playlist) it 'expect player.getPlaylistById() with id, not contianed in the player to return null, when there are other playlists and when there are no playlists at all', () -> name = 'PI:NAME:<NAME>END_PI' player = result.getPlayer name expect(player.getPlaylist(2)).to.be.null count = 5 ids = {} for i in [0..count] playlist = result.getPlaylist(name + i) player.addPlaylist(playlist) ids[playlist.id] = true invalidID = (Math.random() * 100000000) | 0 while ids[invalidID] invalidID = (Math.random() * 100000000) | 0 expect(player.getPlaylist(invalidID)).to.be.null it 'expect player.removePlaylist() to remove the playlist, when id is provided', -> name = 'PI:NAME:<NAME>END_PI' player = result.getPlayer name playlist = result.getPlaylist name player.addPlaylist(playlist) .removePlaylist(playlist.id) expect(player.getPlaylistById(playlist.id)).to.be.null for i in [0..5] player.addPlaylist(name + i)
[ { "context": "#author Sergiy Voronov twitter.com/mamezito dribbble.com/mamezito\n#done ", "end": 22, "score": 0.9998847842216492, "start": 8, "tag": "NAME", "value": "Sergiy Voronov" }, { "context": "#author Sergiy Voronov twitter.com/mamezito dribbble.com/mamezito\n#done for Framer ...
23radial.framer/modules/dragOnCircle.coffee
gremjua-forks/100daysofframer
26
#author Sergiy Voronov twitter.com/mamezito dribbble.com/mamezito #done for Framer London framerlondon.com exports.circleDrag=(objectLayer, radius)-> angle=0 centerX=objectLayer.midX centerY=objectLayer.midY+radius proxy=objectLayer.copy() proxy.name="proxy" proxy.opacity=0 proxy.draggable=true proxy.draggable.overdrag=false proxy.draggable.momentum=false proxy.draggable.constraints= x:proxy.midX-radius-proxy.width/2 y:proxy.y width:radius*2+proxy.width height:radius*2+proxy.width proxy.onDrag (event, layer) -> radX=this.x-centerX radY=this.y-centerY angle=Math.atan2(radX,radY)*(180/Math.PI) exports.dragAngle=180-angle placeOnElipse objectLayer, centerX, centerY, angle, radius, radius proxy.onDragEnd -> proxy.x=objectLayer.x proxy.y=objectLayer.y placeOnElipse=(newLayer, centerX, centerY, angle, radiusX, radiusY)-> newLayer.midX=centerX-Math.sin((angle+180) * Math.PI / 180)*radiusX newLayer.midY=centerY-Math.cos((angle+180) * Math.PI / 180)*radiusY
165607
#author <NAME> twitter.com/mamezito dribbble.com/mamezito #done for Framer London framerlondon.com exports.circleDrag=(objectLayer, radius)-> angle=0 centerX=objectLayer.midX centerY=objectLayer.midY+radius proxy=objectLayer.copy() proxy.name="proxy" proxy.opacity=0 proxy.draggable=true proxy.draggable.overdrag=false proxy.draggable.momentum=false proxy.draggable.constraints= x:proxy.midX-radius-proxy.width/2 y:proxy.y width:radius*2+proxy.width height:radius*2+proxy.width proxy.onDrag (event, layer) -> radX=this.x-centerX radY=this.y-centerY angle=Math.atan2(radX,radY)*(180/Math.PI) exports.dragAngle=180-angle placeOnElipse objectLayer, centerX, centerY, angle, radius, radius proxy.onDragEnd -> proxy.x=objectLayer.x proxy.y=objectLayer.y placeOnElipse=(newLayer, centerX, centerY, angle, radiusX, radiusY)-> newLayer.midX=centerX-Math.sin((angle+180) * Math.PI / 180)*radiusX newLayer.midY=centerY-Math.cos((angle+180) * Math.PI / 180)*radiusY
true
#author PI:NAME:<NAME>END_PI twitter.com/mamezito dribbble.com/mamezito #done for Framer London framerlondon.com exports.circleDrag=(objectLayer, radius)-> angle=0 centerX=objectLayer.midX centerY=objectLayer.midY+radius proxy=objectLayer.copy() proxy.name="proxy" proxy.opacity=0 proxy.draggable=true proxy.draggable.overdrag=false proxy.draggable.momentum=false proxy.draggable.constraints= x:proxy.midX-radius-proxy.width/2 y:proxy.y width:radius*2+proxy.width height:radius*2+proxy.width proxy.onDrag (event, layer) -> radX=this.x-centerX radY=this.y-centerY angle=Math.atan2(radX,radY)*(180/Math.PI) exports.dragAngle=180-angle placeOnElipse objectLayer, centerX, centerY, angle, radius, radius proxy.onDragEnd -> proxy.x=objectLayer.x proxy.y=objectLayer.y placeOnElipse=(newLayer, centerX, centerY, angle, radiusX, radiusY)-> newLayer.midX=centerX-Math.sin((angle+180) * Math.PI / 180)*radiusX newLayer.midY=centerY-Math.cos((angle+180) * Math.PI / 180)*radiusY
[ { "context": "\n O/P: Array of Posns\n\n I am a cute sick Kate Whiper Snapper\n i love monodebe and I learn all about the f", "end": 10329, "score": 0.9974217414855957, "start": 10310, "tag": "NAME", "value": "Kate Whiper Snapper" } ]
src/coffee/geometry/cubic-bezier-line-segment.coffee
agiza/mondrian
226
### Internal representation of a cubic bezier line segment p1 p4 o o \\ // \\ // \ \ / / \ \ / / \ _ _ / \ __ __ / ° --_____-- ° p2 p3 I/P: p1: First absolute point, the moveto p2: The first point's curve handle p3: The second point's curve handle p4: The second absolute point In context with syntax: M[p1]C[p2] [p3] [p4] ### class CubicBezier constructor: (@p1, @p2, @p3, @p4, @source = @toCurveTo()) -> ### toString: -> "(Cubic bezier: #{@p1},#{@p2},#{@p3},#{@p4})" ### toString: -> "new CubicBezier(#{@p1}, #{@p2}, #{@p3}, #{@p4})" toCurveTo: -> new CurveTo(@p2.x, @p2.y, @p3.x, @p3.y, @p4.x, @p4.y) toSVGPoint: -> @toCurveTo() length: -> # Not that accurate lol @intoLineSegments(4).reduce((a, b) -> a + b.length) beginning: -> @p1 end: -> @p4 nudge: (x, y) -> @p1.nudge(x, y) @p2.nudge(x, y) @p3.nudge(x, y) @p4.nudge(x, y) @ scale: (x, y, origin) -> @p1.scale(x, y, origin) @p2.scale(x, y, origin) @p3.scale(x, y, origin) @p4.scale(x, y, origin) @ rotate: (angle, origin) -> @p1.rotate(angle, origin) @p2.rotate(angle, origin) @p3.rotate(angle, origin) @p4.rotate(angle, origin) @ reverse: -> # Note: this makes it lose its source new CubicBezier @p4, @p3, @p2, @p1 equal: (cbls) -> return false if cbls instanceof LineSegment (((@p1.equal cbls.p1) && (@p2.equal cbls.p2) && (@p3.equal cbls.p3) && (@p4.equal cbls.p4)) || ((@p1.equal cbls.p4) && (@p2.equal cbls.p3) && (@p3.equal cbls.p2) && (@p4.equal cbls.p1))) intersects: (other) -> inter = @intersection(other) inter instanceof Posn or (inter instanceof Array and inter.length > 0) intersection: (other) -> switch other.constructor when LineSegment return @intersectionWithLineSegment(other) when CubicBezier return @intersectionWithCubicBezier(other) xRange: -> @bounds().xr yRange: -> @bounds().yr ends: -> [@p1, @p4] midPoint: -> @splitAt(0.5)[0].p4 bounds: (useCached = false) -> if @boundsCached? and useCached return @boundsCached minx = miny = Infinity maxx = maxy = -Infinity top2x = @p2.x - @p1.x top2y = @p2.y - @p1.y top3x = @p3.x - @p2.x top3y = @p3.y - @p2.y top4x = @p4.x - @p3.x top4y = @p4.y - @p3.y for i in [0..40] d = i / 40 px = @p1.x + d * top2x py = @p1.y + d * top2y qx = @p2.x + d * top3x qy = @p2.y + d * top3y rx = @p3.x + d * top4x ry = @p3.y + d * top4y toqx = qx - px toqy = qy - py torx = rx - qx tory = ry - qy sx = px + d * toqx sy = py + d * toqy tx = qx + d * torx ty = qy + d * tory totx = tx - sx toty = ty - sy x = sx + d * totx y = sy + d * toty minx = Math.min(minx, x) miny = Math.min(miny, y) maxx = Math.max(maxx, x) maxy = Math.max(maxy, y) width = maxx - minx height = maxy - miny # Cache the bounds and return them at the same time @boundsCached = new Bounds(minx, miny, width, height) boundsCached: undefined intoLineSegments: (n) -> # Given n, split the bezier into n consecutive LineSegments, returned in an Array # # I/P: n, number # O/P: [LineSegment, LineSegment, LineSegment...] array segments = [] for m in [0..n] i = 1 / m x = Math.pow((1-i), 3) * @p1.x + 3 * Math.pow((1-i), 2) * i * @p2.x + 3 * (1 - i) * Math.pow(i, 2) * @p3.x + Math.pow(i, 3) * @p4.x y = Math.pow((1-i), 3) * @p1.y + 3 * Math.pow((1-i), 2) * i * @p2.y + 3 * (1 - i) * Math.pow(i, 2) * @p3.y + Math.pow(i, 3) * @p4.y if m % 2 == 0 last = new Posn(x, y) else segments.push new LineSegment(last, new Posn(x, y)) segments.splice 1 splitAt: (t, force = null) -> # Given a float t between 0 and 1, return two CubicBeziers that result from splitting this one at that percentage in. # # I/P: t, number between 0 and 1 # O/P: [CubicBezier, CubicBezier] array # # Uses de Casteljau's algorithm. Really damn good resources: # http://processingjs.nihongoresources.com/bezierinfo/ # http://en.wikipedia.org/wiki/De_Casteljau's_algorithm # # Example, splitting in half: # t = 0.5 # p1: (10,10), p2: (20, 5), p3: (40, 20), p4: (50, 10) # p5: (15, 7.5), p6: (30, 12.5), p7: (45, 15) # p8: (22.5, 10), p9: (37.5, 13.75) # p10: (30, 11.875) # # The split will happen at exactly p10, so the resulting curves will end and start there, respectively. # The resulting curves will be # [new CubicBezier(p1, p5, p8, p10), new CubicBezier(p10, p9, p7, p4)] if typeof t is "number" p5 = new LineSegment(@p1, @p2).posnAtPercent t p6 = new LineSegment(@p2, @p3).posnAtPercent t p7 = new LineSegment(@p3, @p4).posnAtPercent t p8 = new LineSegment(p5, p6).posnAtPercent t p9 = new LineSegment(p6, p7).posnAtPercent t p10 = if force then force else new LineSegment(p8, p9).posnAtPercent t return [new CubicBezier(@p1, p5, p8, p10), new CubicBezier(p10, p9, p7, @p4)] else if t instanceof Posn # Given a single Posn, find its percentage and then split the line on it. return @splitAt(@findPercentageOfPoint(t), t) else if t instanceof Array # Given a list of Posns, we have a bit more work to do. # We need to sort the Posns by their percentage along on the original line. # Then we recur on the line, splitting it on each posn that occurs from 0.0 to 1.0. # We always recur on the second half of the resulting split with # the next Posn in line. # We're going to use the Posns' percentages as keys # with which we'll sort them and split the line on them # one after the other. sortedPosns = {} # This will be the final array of split segments. segments = [] # Find percentage for each posn, save the posn under that percentage. for posn in t percent = @findPercentageOfPoint posn sortedPosns[percent] = posn # Sort the keys - the list of percentages at which posns are available. percentages = Object.keys(sortedPosns).map(parseFloat).sort(sortNumbers) # Start by splitting the entire bezier. tail = @ # For each posn, going in order of percentages... for perc in percentages # Split the tail on that single posn pair = tail.splitAt sortedPosns[perc] # Keep the first half segments.push pair[0] # And "recur" on the second half by redefining tail to be it tail = pair[1] # Don't abandon that last tail! ;) segments.push tail # Shazam return segments findPercentageOfPoint: (posn, tolerance = 1e-3, accumulated = 0.0, nextstep = 0.5) -> # Recursively find the percentage (float from 0 - 1) of given posn on this bezier, within tolerance given. # This works so well. I am so stoked about it. # Basically, this splits the given bezier in half. If the midpoint is within the tolerance of the posn we're looking for, # return the accumulated float. If not, it will recur on either or both of its halves, # adding (0.5 * n / 2) to the accumulator for the one on the right and keeping it the same for the one on the left # where n is the depth of recursion. # # I/P: posn: the Posn we're looking for # [tolerance]: find the value for within this much of the x and y of the given posn. # # Ignore the accumulated and nextstep values, those should start as they're precoded. # # O/P: A float between 0 and 1. split = @splitAt(0.5) a = split[0] b = split[1] # Base case - we've found it! Return the amt accumulated. if a.p4.within(tolerance, posn) or nextstep < 1e-4 return accumulated # Recursion ab = a.bounds() bb = b.bounds() # Both halves might contain the point, if we have a shape that overlaps itself for example. # For this reason we have to actually recur on both the left and right. # When staying with a, however, we don't add to the accumulator because we're not advancing to the second half of the line. # We're simply not making the jump, so we don't count it. But we might make the next smallest jump when we recur on a. if ab.xr.containsInclusive(posn.x, 0.2) and ab.yr.containsInclusive(posn.y, 0.2) ac = a.findPercentageOfPoint(posn, tolerance, accumulated, nextstep / 2) if bb.xr.containsInclusive(posn.x, 0.2) and bb.yr.containsInclusive(posn.y, 0.2) bc = b.findPercentageOfPoint(posn, tolerance, accumulated + nextstep, nextstep / 2) # This is where the recursion bottoms out. Null means it's not on the bezier line within the tolerance. # ############# # IMPORTANT # ############# # This is a compromise right now. Since the intersection algorithm is imperfect, we get as close as we can and # return accumulated if there are no options. NOT null, which it used to be. # All this means is that if a point is given that's a bit off the line the recursion will stop when it can't # get any closer to it. So it does what it can, basically. # # This means you can't just feed any point into this and expect it to ignore you given a bad point. # This also means there is some tolerance to a point being a little bit off, which can happen when calculating # several intersections on one curve. # # It's very accurate this way. Nothing to worry about. Just a note so I don't forget. <3 if ac? then ac else if bc? then bc else accumulated ### Intersection methods ### intersectionWithLineSegment: (l) -> ### Given a LineSegment, lists intersection point(s). I/P: LineSegment O/P: Array of Posns I am a cute sick Kate Whiper Snapper i love monodebe and I learn all about the flexible scemless data base Disclaimer: I don't really understand this but it passes my tests. ### min = l.a.min(l.b) max = l.a.max(l.b) results = [] a = @p1.multiplyBy -1 b = @p2.multiplyBy 3 c = @p3.multiplyBy -3 d = a.add(b.add(c.add(@p4))) c3 = new Posn(d.x, d.y) a = @p1.multiplyBy 3 b = @p2.multiplyBy -6 c = @p3.multiplyBy 3 d = a.add(b.add(c)) c2 = new Posn(d.x, d.y) a = @p1.multiplyBy -3 b = @p2.multiplyBy 3 c = a.add b c1 = new Posn(c.x, c.y) c0 = new Posn(@p1.x, @p1.y) n = new Posn(l.a.y - l.b.y, l.b.x - l.a.x) cl = l.a.x * l.b.y - l.b.x * l.a.y roots = new Polynomial([n.dot(c3), n.dot(c2), n.dot(c1), n.dot(c0) + cl]).roots() for i,t of roots if 0 <= t and t <= 1 p5 = @p1.lerp(@p2, t) p6 = @p2.lerp(@p3, t) p7 = @p3.lerp(@p4, t) p8 = p5.lerp(p6, t) p9 = p6.lerp(p7, t) p10 = p8.lerp(p9, t) if l.a.x is l.b.x if (min.y <= p10.y) and (p10.y <= max.y) results.push p10 else if l.a.y is l.b.y if min.x <= p10.x and p10.x <= max.x results.push p10 else if p10.gte(min) and p10.lte(max) results.push p10 results intersectionWithCubicBezier: (other) -> # I don't know. # # I/P: Another CubicBezier # O/P: Array of Posns. # # Source: http://www.kevlindev.com/gui/math/intersection/index.htm#Anchor-intersectBezie-45477 results = [] a = @p1.multiplyBy(-1) b = @p2.multiplyBy(3) c = @p3.multiplyBy(-3) d = a.add(b.add(c.add(@p4))) c13 = new Posn(d.x, d.y) a = @p1.multiplyBy(3) b = @p2.multiplyBy(-6) c = @p3.multiplyBy(3) d = a.add(b.add(c)) c12 = new Posn(d.x, d.y) a = @p1.multiplyBy(-3) b = @p2.multiplyBy(3) c = a.add(b) c11 = new Posn(c.x, c.y) c10 = new Posn(@p1.x, @p1.y) a = other.p1.multiplyBy(-1) b = other.p2.multiplyBy(3) c = other.p3.multiplyBy(-3) d = a.add(b.add(c.add(other.p4))) c23 = new Posn(d.x, d.y) a = other.p1.multiplyBy(3) b = other.p2.multiplyBy(-6) c = other.p3.multiplyBy(3) d = a.add(b.add(c)) c22 = new Posn(d.x, d.y) a = other.p1.multiplyBy(-3) b = other.p2.multiplyBy(3) c = a.add(b) c21 = new Posn(c.x, c.y) c20 = new Posn(other.p1.x, other.p1.y) c10x2 = c10.x * c10.x c10x3 = c10.x * c10.x * c10.x c10y2 = c10.y * c10.y c10y3 = c10.y * c10.y * c10.y c11x2 = c11.x * c11.x c11x3 = c11.x * c11.x * c11.x c11y2 = c11.y * c11.y c11y3 = c11.y * c11.y * c11.y c12x2 = c12.x * c12.x c12x3 = c12.x * c12.x * c12.x c12y2 = c12.y * c12.y c12y3 = c12.y * c12.y * c12.y c13x2 = c13.x * c13.x c13x3 = c13.x * c13.x * c13.x c13y2 = c13.y * c13.y c13y3 = c13.y * c13.y * c13.y c20x2 = c20.x * c20.x c20x3 = c20.x * c20.x * c20.x c20y2 = c20.y * c20.y c20y3 = c20.y * c20.y * c20.y c21x2 = c21.x * c21.x c21x3 = c21.x * c21.x * c21.x c21y2 = c21.y * c21.y c22x2 = c22.x * c22.x c22x3 = c22.x * c22.x * c22.x c22y2 = c22.y * c22.y c23x2 = c23.x * c23.x c23x3 = c23.x * c23.x * c23.x c23y2 = c23.y * c23.y c23y3 = c23.y * c23.y * c23.y poly = new Polynomial([ -c13x3*c23y3 + c13y3*c23x3 - 3*c13.x*c13y2*c23x2*c23.y + 3*c13x2*c13.y*c23.x*c23y2, -6*c13.x*c22.x*c13y2*c23.x*c23.y + 6*c13x2*c13.y*c22.y*c23.x*c23.y + 3*c22.x*c13y3*c23x2 - 3*c13x3*c22.y*c23y2 - 3*c13.x*c13y2*c22.y*c23x2 + 3*c13x2*c22.x*c13.y*c23y2, -6*c21.x*c13.x*c13y2*c23.x*c23.y - 6*c13.x*c22.x*c13y2*c22.y*c23.x + 6*c13x2*c22.x*c13.y*c22.y*c23.y + 3*c21.x*c13y3*c23x2 + 3*c22x2*c13y3*c23.x + 3*c21.x*c13x2*c13.y*c23y2 - 3*c13.x*c21.y*c13y2*c23x2 - 3*c13.x*c22x2*c13y2*c23.y + c13x2*c13.y*c23.x*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-c21.y*c23y2 - 2*c22y2*c23.y - c23.y*(2*c21.y*c23.y + c22y2)), c11.x*c12.y*c13.x*c13.y*c23.x*c23.y - c11.y*c12.x*c13.x*c13.y*c23.x*c23.y + 6*c21.x*c22.x*c13y3*c23.x + 3*c11.x*c12.x*c13.x*c13.y*c23y2 + 6*c10.x*c13.x*c13y2*c23.x*c23.y - 3*c11.x*c12.x*c13y2*c23.x*c23.y - 3*c11.y*c12.y*c13.x*c13.y*c23x2 - 6*c10.y*c13x2*c13.y*c23.x*c23.y - 6*c20.x*c13.x*c13y2*c23.x*c23.y + 3*c11.y*c12.y*c13x2*c23.x*c23.y - 2*c12.x*c12y2*c13.x*c23.x*c23.y - 6*c21.x*c13.x*c22.x*c13y2*c23.y - 6*c21.x*c13.x*c13y2*c22.y*c23.x - 6*c13.x*c21.y*c22.x*c13y2*c23.x + 6*c21.x*c13x2*c13.y*c22.y*c23.y + 2*c12x2*c12.y*c13.y*c23.x*c23.y + c22x3*c13y3 - 3*c10.x*c13y3*c23x2 + 3*c10.y*c13x3*c23y2 + 3*c20.x*c13y3*c23x2 + c12y3*c13.x*c23x2 - c12x3*c13.y*c23y2 - 3*c10.x*c13x2*c13.y*c23y2 + 3*c10.y*c13.x*c13y2*c23x2 - 2*c11.x*c12.y*c13x2*c23y2 + c11.x*c12.y*c13y2*c23x2 - c11.y*c12.x*c13x2*c23y2 + 2*c11.y*c12.x*c13y2*c23x2 + 3*c20.x*c13x2*c13.y*c23y2 - c12.x*c12y2*c13.y*c23x2 - 3*c20.y*c13.x*c13y2*c23x2 + c12x2*c12.y*c13.x*c23y2 - 3*c13.x*c22x2*c13y2*c22.y + c13x2*c13.y*c23.x*(6*c20.y*c23.y + 6*c21.y*c22.y) + c13x2*c22.x*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c21.y*c22.y*c23.y - c20.y*c23y2 - c22.y*(2*c21.y*c23.y + c22y2) - c23.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), 6*c11.x*c12.x*c13.x*c13.y*c22.y*c23.y + c11.x*c12.y*c13.x*c22.x*c13.y*c23.y + c11.x*c12.y*c13.x*c13.y*c22.y*c23.x - c11.y*c12.x*c13.x*c22.x*c13.y*c23.y - c11.y*c12.x*c13.x*c13.y*c22.y*c23.x - 6*c11.y*c12.y*c13.x*c22.x*c13.y*c23.x - 6*c10.x*c22.x*c13y3*c23.x + 6*c20.x*c22.x*c13y3*c23.x + 6*c10.y*c13x3*c22.y*c23.y + 2*c12y3*c13.x*c22.x*c23.x - 2*c12x3*c13.y*c22.y*c23.y + 6*c10.x*c13.x*c22.x*c13y2*c23.y + 6*c10.x*c13.x*c13y2*c22.y*c23.x + 6*c10.y*c13.x*c22.x*c13y2*c23.x - 3*c11.x*c12.x*c22.x*c13y2*c23.y - 3*c11.x*c12.x*c13y2*c22.y*c23.x + 2*c11.x*c12.y*c22.x*c13y2*c23.x + 4*c11.y*c12.x*c22.x*c13y2*c23.x - 6*c10.x*c13x2*c13.y*c22.y*c23.y - 6*c10.y*c13x2*c22.x*c13.y*c23.y - 6*c10.y*c13x2*c13.y*c22.y*c23.x - 4*c11.x*c12.y*c13x2*c22.y*c23.y - 6*c20.x*c13.x*c22.x*c13y2*c23.y - 6*c20.x*c13.x*c13y2*c22.y*c23.x - 2*c11.y*c12.x*c13x2*c22.y*c23.y + 3*c11.y*c12.y*c13x2*c22.x*c23.y + 3*c11.y*c12.y*c13x2*c22.y*c23.x - 2*c12.x*c12y2*c13.x*c22.x*c23.y - 2*c12.x*c12y2*c13.x*c22.y*c23.x - 2*c12.x*c12y2*c22.x*c13.y*c23.x - 6*c20.y*c13.x*c22.x*c13y2*c23.x - 6*c21.x*c13.x*c21.y*c13y2*c23.x - 6*c21.x*c13.x*c22.x*c13y2*c22.y + 6*c20.x*c13x2*c13.y*c22.y*c23.y + 2*c12x2*c12.y*c13.x*c22.y*c23.y + 2*c12x2*c12.y*c22.x*c13.y*c23.y + 2*c12x2*c12.y*c13.y*c22.y*c23.x + 3*c21.x*c22x2*c13y3 + 3*c21x2*c13y3*c23.x - 3*c13.x*c21.y*c22x2*c13y2 - 3*c21x2*c13.x*c13y2*c23.y + c13x2*c22.x*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c13x2*c13.y*c23.x*(6*c20.y*c22.y + 3*c21y2) + c21.x*c13x2*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c20.y*c22.y*c23.y - c23.y*(2*c20.y*c22.y + c21y2) - c21.y*(2*c21.y*c23.y + c22y2) - c22.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), c11.x*c21.x*c12.y*c13.x*c13.y*c23.y + c11.x*c12.y*c13.x*c21.y*c13.y*c23.x + c11.x*c12.y*c13.x*c22.x*c13.y*c22.y - c11.y*c12.x*c21.x*c13.x*c13.y*c23.y - c11.y*c12.x*c13.x*c21.y*c13.y*c23.x - c11.y*c12.x*c13.x*c22.x*c13.y*c22.y - 6*c11.y*c21.x*c12.y*c13.x*c13.y*c23.x - 6*c10.x*c21.x*c13y3*c23.x + 6*c20.x*c21.x*c13y3*c23.x + 2*c21.x*c12y3*c13.x*c23.x + 6*c10.x*c21.x*c13.x*c13y2*c23.y + 6*c10.x*c13.x*c21.y*c13y2*c23.x + 6*c10.x*c13.x*c22.x*c13y2*c22.y + 6*c10.y*c21.x*c13.x*c13y2*c23.x - 3*c11.x*c12.x*c21.x*c13y2*c23.y - 3*c11.x*c12.x*c21.y*c13y2*c23.x - 3*c11.x*c12.x*c22.x*c13y2*c22.y + 2*c11.x*c21.x*c12.y*c13y2*c23.x + 4*c11.y*c12.x*c21.x*c13y2*c23.x - 6*c10.y*c21.x*c13x2*c13.y*c23.y - 6*c10.y*c13x2*c21.y*c13.y*c23.x - 6*c10.y*c13x2*c22.x*c13.y*c22.y - 6*c20.x*c21.x*c13.x*c13y2*c23.y - 6*c20.x*c13.x*c21.y*c13y2*c23.x - 6*c20.x*c13.x*c22.x*c13y2*c22.y + 3*c11.y*c21.x*c12.y*c13x2*c23.y - 3*c11.y*c12.y*c13.x*c22x2*c13.y + 3*c11.y*c12.y*c13x2*c21.y*c23.x + 3*c11.y*c12.y*c13x2*c22.x*c22.y - 2*c12.x*c21.x*c12y2*c13.x*c23.y - 2*c12.x*c21.x*c12y2*c13.y*c23.x - 2*c12.x*c12y2*c13.x*c21.y*c23.x - 2*c12.x*c12y2*c13.x*c22.x*c22.y - 6*c20.y*c21.x*c13.x*c13y2*c23.x - 6*c21.x*c13.x*c21.y*c22.x*c13y2 + 6*c20.y*c13x2*c21.y*c13.y*c23.x + 2*c12x2*c21.x*c12.y*c13.y*c23.y + 2*c12x2*c12.y*c21.y*c13.y*c23.x + 2*c12x2*c12.y*c22.x*c13.y*c22.y - 3*c10.x*c22x2*c13y3 + 3*c20.x*c22x2*c13y3 + 3*c21x2*c22.x*c13y3 + c12y3*c13.x*c22x2 + 3*c10.y*c13.x*c22x2*c13y2 + c11.x*c12.y*c22x2*c13y2 + 2*c11.y*c12.x*c22x2*c13y2 - c12.x*c12y2*c22x2*c13.y - 3*c20.y*c13.x*c22x2*c13y2 - 3*c21x2*c13.x*c13y2*c22.y + c12x2*c12.y*c13.x*(2*c21.y*c23.y + c22y2) + c11.x*c12.x*c13.x*c13.y*(6*c21.y*c23.y + 3*c22y2) + c21.x*c13x2*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c12x3*c13.y*(-2*c21.y*c23.y - c22y2) + c10.y*c13x3*(6*c21.y*c23.y + 3*c22y2) + c11.y*c12.x*c13x2*(-2*c21.y*c23.y - c22y2) + c11.x*c12.y*c13x2*(-4*c21.y*c23.y - 2*c22y2) + c10.x*c13x2*c13.y*(-6*c21.y*c23.y - 3*c22y2) + c13x2*c22.x*c13.y*(6*c20.y*c22.y + 3*c21y2) + c20.x*c13x2*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c20.y*c21.y*c23.y - c22.y*(2*c20.y*c22.y + c21y2) - c20.y*(2*c21.y*c23.y + c22y2) - c21.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), -c10.x*c11.x*c12.y*c13.x*c13.y*c23.y + c10.x*c11.y*c12.x*c13.x*c13.y*c23.y + 6*c10.x*c11.y*c12.y*c13.x*c13.y*c23.x - 6*c10.y*c11.x*c12.x*c13.x*c13.y*c23.y - c10.y*c11.x*c12.y*c13.x*c13.y*c23.x + c10.y*c11.y*c12.x*c13.x*c13.y*c23.x + c11.x*c11.y*c12.x*c12.y*c13.x*c23.y - c11.x*c11.y*c12.x*c12.y*c13.y*c23.x + c11.x*c20.x*c12.y*c13.x*c13.y*c23.y + c11.x*c20.y*c12.y*c13.x*c13.y*c23.x + c11.x*c21.x*c12.y*c13.x*c13.y*c22.y + c11.x*c12.y*c13.x*c21.y*c22.x*c13.y - c20.x*c11.y*c12.x*c13.x*c13.y*c23.y - 6*c20.x*c11.y*c12.y*c13.x*c13.y*c23.x - c11.y*c12.x*c20.y*c13.x*c13.y*c23.x - c11.y*c12.x*c21.x*c13.x*c13.y*c22.y - c11.y*c12.x*c13.x*c21.y*c22.x*c13.y - 6*c11.y*c21.x*c12.y*c13.x*c22.x*c13.y - 6*c10.x*c20.x*c13y3*c23.x - 6*c10.x*c21.x*c22.x*c13y3 - 2*c10.x*c12y3*c13.x*c23.x + 6*c20.x*c21.x*c22.x*c13y3 + 2*c20.x*c12y3*c13.x*c23.x + 2*c21.x*c12y3*c13.x*c22.x + 2*c10.y*c12x3*c13.y*c23.y - 6*c10.x*c10.y*c13.x*c13y2*c23.x + 3*c10.x*c11.x*c12.x*c13y2*c23.y - 2*c10.x*c11.x*c12.y*c13y2*c23.x - 4*c10.x*c11.y*c12.x*c13y2*c23.x + 3*c10.y*c11.x*c12.x*c13y2*c23.x + 6*c10.x*c10.y*c13x2*c13.y*c23.y + 6*c10.x*c20.x*c13.x*c13y2*c23.y - 3*c10.x*c11.y*c12.y*c13x2*c23.y + 2*c10.x*c12.x*c12y2*c13.x*c23.y + 2*c10.x*c12.x*c12y2*c13.y*c23.x + 6*c10.x*c20.y*c13.x*c13y2*c23.x + 6*c10.x*c21.x*c13.x*c13y2*c22.y + 6*c10.x*c13.x*c21.y*c22.x*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c23.y + 6*c10.y*c20.x*c13.x*c13y2*c23.x + 2*c10.y*c11.y*c12.x*c13x2*c23.y - 3*c10.y*c11.y*c12.y*c13x2*c23.x + 2*c10.y*c12.x*c12y2*c13.x*c23.x + 6*c10.y*c21.x*c13.x*c22.x*c13y2 - 3*c11.x*c20.x*c12.x*c13y2*c23.y + 2*c11.x*c20.x*c12.y*c13y2*c23.x + c11.x*c11.y*c12y2*c13.x*c23.x - 3*c11.x*c12.x*c20.y*c13y2*c23.x - 3*c11.x*c12.x*c21.x*c13y2*c22.y - 3*c11.x*c12.x*c21.y*c22.x*c13y2 + 2*c11.x*c21.x*c12.y*c22.x*c13y2 + 4*c20.x*c11.y*c12.x*c13y2*c23.x + 4*c11.y*c12.x*c21.x*c22.x*c13y2 - 2*c10.x*c12x2*c12.y*c13.y*c23.y - 6*c10.y*c20.x*c13x2*c13.y*c23.y - 6*c10.y*c20.y*c13x2*c13.y*c23.x - 6*c10.y*c21.x*c13x2*c13.y*c22.y - 2*c10.y*c12x2*c12.y*c13.x*c23.y - 2*c10.y*c12x2*c12.y*c13.y*c23.x - 6*c10.y*c13x2*c21.y*c22.x*c13.y - c11.x*c11.y*c12x2*c13.y*c23.y - 2*c11.x*c11y2*c13.x*c13.y*c23.x + 3*c20.x*c11.y*c12.y*c13x2*c23.y - 2*c20.x*c12.x*c12y2*c13.x*c23.y - 2*c20.x*c12.x*c12y2*c13.y*c23.x - 6*c20.x*c20.y*c13.x*c13y2*c23.x - 6*c20.x*c21.x*c13.x*c13y2*c22.y - 6*c20.x*c13.x*c21.y*c22.x*c13y2 + 3*c11.y*c20.y*c12.y*c13x2*c23.x + 3*c11.y*c21.x*c12.y*c13x2*c22.y + 3*c11.y*c12.y*c13x2*c21.y*c22.x - 2*c12.x*c20.y*c12y2*c13.x*c23.x - 2*c12.x*c21.x*c12y2*c13.x*c22.y - 2*c12.x*c21.x*c12y2*c22.x*c13.y - 2*c12.x*c12y2*c13.x*c21.y*c22.x - 6*c20.y*c21.x*c13.x*c22.x*c13y2 - c11y2*c12.x*c12.y*c13.x*c23.x + 2*c20.x*c12x2*c12.y*c13.y*c23.y + 6*c20.y*c13x2*c21.y*c22.x*c13.y + 2*c11x2*c11.y*c13.x*c13.y*c23.y + c11x2*c12.x*c12.y*c13.y*c23.y + 2*c12x2*c20.y*c12.y*c13.y*c23.x + 2*c12x2*c21.x*c12.y*c13.y*c22.y + 2*c12x2*c12.y*c21.y*c22.x*c13.y + c21x3*c13y3 + 3*c10x2*c13y3*c23.x - 3*c10y2*c13x3*c23.y + 3*c20x2*c13y3*c23.x + c11y3*c13x2*c23.x - c11x3*c13y2*c23.y - c11.x*c11y2*c13x2*c23.y + c11x2*c11.y*c13y2*c23.x - 3*c10x2*c13.x*c13y2*c23.y + 3*c10y2*c13x2*c13.y*c23.x - c11x2*c12y2*c13.x*c23.y + c11y2*c12x2*c13.y*c23.x - 3*c21x2*c13.x*c21.y*c13y2 - 3*c20x2*c13.x*c13y2*c23.y + 3*c20y2*c13x2*c13.y*c23.x + c11.x*c12.x*c13.x*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c12x3*c13.y*(-2*c20.y*c23.y - 2*c21.y*c22.y) + c10.y*c13x3*(6*c20.y*c23.y + 6*c21.y*c22.y) + c11.y*c12.x*c13x2*(-2*c20.y*c23.y - 2*c21.y*c22.y) + c12x2*c12.y*c13.x*(2*c20.y*c23.y + 2*c21.y*c22.y) + c11.x*c12.y*c13x2*(-4*c20.y*c23.y - 4*c21.y*c22.y) + c10.x*c13x2*c13.y*(-6*c20.y*c23.y - 6*c21.y*c22.y) + c20.x*c13x2*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c21.x*c13x2*c13.y*(6*c20.y*c22.y + 3*c21y2) + c13x3*(-2*c20.y*c21.y*c22.y - c20y2*c23.y - c21.y*(2*c20.y*c22.y + c21y2) - c20.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), -c10.x*c11.x*c12.y*c13.x*c13.y*c22.y + c10.x*c11.y*c12.x*c13.x*c13.y*c22.y + 6*c10.x*c11.y*c12.y*c13.x*c22.x*c13.y - 6*c10.y*c11.x*c12.x*c13.x*c13.y*c22.y - c10.y*c11.x*c12.y*c13.x*c22.x*c13.y + c10.y*c11.y*c12.x*c13.x*c22.x*c13.y + c11.x*c11.y*c12.x*c12.y*c13.x*c22.y - c11.x*c11.y*c12.x*c12.y*c22.x*c13.y + c11.x*c20.x*c12.y*c13.x*c13.y*c22.y + c11.x*c20.y*c12.y*c13.x*c22.x*c13.y + c11.x*c21.x*c12.y*c13.x*c21.y*c13.y - c20.x*c11.y*c12.x*c13.x*c13.y*c22.y - 6*c20.x*c11.y*c12.y*c13.x*c22.x*c13.y - c11.y*c12.x*c20.y*c13.x*c22.x*c13.y - c11.y*c12.x*c21.x*c13.x*c21.y*c13.y - 6*c10.x*c20.x*c22.x*c13y3 - 2*c10.x*c12y3*c13.x*c22.x + 2*c20.x*c12y3*c13.x*c22.x + 2*c10.y*c12x3*c13.y*c22.y - 6*c10.x*c10.y*c13.x*c22.x*c13y2 + 3*c10.x*c11.x*c12.x*c13y2*c22.y - 2*c10.x*c11.x*c12.y*c22.x*c13y2 - 4*c10.x*c11.y*c12.x*c22.x*c13y2 + 3*c10.y*c11.x*c12.x*c22.x*c13y2 + 6*c10.x*c10.y*c13x2*c13.y*c22.y + 6*c10.x*c20.x*c13.x*c13y2*c22.y - 3*c10.x*c11.y*c12.y*c13x2*c22.y + 2*c10.x*c12.x*c12y2*c13.x*c22.y + 2*c10.x*c12.x*c12y2*c22.x*c13.y + 6*c10.x*c20.y*c13.x*c22.x*c13y2 + 6*c10.x*c21.x*c13.x*c21.y*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c22.y + 6*c10.y*c20.x*c13.x*c22.x*c13y2 + 2*c10.y*c11.y*c12.x*c13x2*c22.y - 3*c10.y*c11.y*c12.y*c13x2*c22.x + 2*c10.y*c12.x*c12y2*c13.x*c22.x - 3*c11.x*c20.x*c12.x*c13y2*c22.y + 2*c11.x*c20.x*c12.y*c22.x*c13y2 + c11.x*c11.y*c12y2*c13.x*c22.x - 3*c11.x*c12.x*c20.y*c22.x*c13y2 - 3*c11.x*c12.x*c21.x*c21.y*c13y2 + 4*c20.x*c11.y*c12.x*c22.x*c13y2 - 2*c10.x*c12x2*c12.y*c13.y*c22.y - 6*c10.y*c20.x*c13x2*c13.y*c22.y - 6*c10.y*c20.y*c13x2*c22.x*c13.y - 6*c10.y*c21.x*c13x2*c21.y*c13.y - 2*c10.y*c12x2*c12.y*c13.x*c22.y - 2*c10.y*c12x2*c12.y*c22.x*c13.y - c11.x*c11.y*c12x2*c13.y*c22.y - 2*c11.x*c11y2*c13.x*c22.x*c13.y + 3*c20.x*c11.y*c12.y*c13x2*c22.y - 2*c20.x*c12.x*c12y2*c13.x*c22.y - 2*c20.x*c12.x*c12y2*c22.x*c13.y - 6*c20.x*c20.y*c13.x*c22.x*c13y2 - 6*c20.x*c21.x*c13.x*c21.y*c13y2 + 3*c11.y*c20.y*c12.y*c13x2*c22.x + 3*c11.y*c21.x*c12.y*c13x2*c21.y - 2*c12.x*c20.y*c12y2*c13.x*c22.x - 2*c12.x*c21.x*c12y2*c13.x*c21.y - c11y2*c12.x*c12.y*c13.x*c22.x + 2*c20.x*c12x2*c12.y*c13.y*c22.y - 3*c11.y*c21x2*c12.y*c13.x*c13.y + 6*c20.y*c21.x*c13x2*c21.y*c13.y + 2*c11x2*c11.y*c13.x*c13.y*c22.y + c11x2*c12.x*c12.y*c13.y*c22.y + 2*c12x2*c20.y*c12.y*c22.x*c13.y + 2*c12x2*c21.x*c12.y*c21.y*c13.y - 3*c10.x*c21x2*c13y3 + 3*c20.x*c21x2*c13y3 + 3*c10x2*c22.x*c13y3 - 3*c10y2*c13x3*c22.y + 3*c20x2*c22.x*c13y3 + c21x2*c12y3*c13.x + c11y3*c13x2*c22.x - c11x3*c13y2*c22.y + 3*c10.y*c21x2*c13.x*c13y2 - c11.x*c11y2*c13x2*c22.y + c11.x*c21x2*c12.y*c13y2 + 2*c11.y*c12.x*c21x2*c13y2 + c11x2*c11.y*c22.x*c13y2 - c12.x*c21x2*c12y2*c13.y - 3*c20.y*c21x2*c13.x*c13y2 - 3*c10x2*c13.x*c13y2*c22.y + 3*c10y2*c13x2*c22.x*c13.y - c11x2*c12y2*c13.x*c22.y + c11y2*c12x2*c22.x*c13.y - 3*c20x2*c13.x*c13y2*c22.y + 3*c20y2*c13x2*c22.x*c13.y + c12x2*c12.y*c13.x*(2*c20.y*c22.y + c21y2) + c11.x*c12.x*c13.x*c13.y*(6*c20.y*c22.y + 3*c21y2) + c12x3*c13.y*(-2*c20.y*c22.y - c21y2) + c10.y*c13x3*(6*c20.y*c22.y + 3*c21y2) + c11.y*c12.x*c13x2*(-2*c20.y*c22.y - c21y2) + c11.x*c12.y*c13x2*(-4*c20.y*c22.y - 2*c21y2) + c10.x*c13x2*c13.y*(-6*c20.y*c22.y - 3*c21y2) + c20.x*c13x2*c13.y*(6*c20.y*c22.y + 3*c21y2) + c13x3*(-2*c20.y*c21y2 - c20y2*c22.y - c20.y*(2*c20.y*c22.y + c21y2)), -c10.x*c11.x*c12.y*c13.x*c21.y*c13.y + c10.x*c11.y*c12.x*c13.x*c21.y*c13.y + 6*c10.x*c11.y*c21.x*c12.y*c13.x*c13.y - 6*c10.y*c11.x*c12.x*c13.x*c21.y*c13.y - c10.y*c11.x*c21.x*c12.y*c13.x*c13.y + c10.y*c11.y*c12.x*c21.x*c13.x*c13.y - c11.x*c11.y*c12.x*c21.x*c12.y*c13.y + c11.x*c11.y*c12.x*c12.y*c13.x*c21.y + c11.x*c20.x*c12.y*c13.x*c21.y*c13.y + 6*c11.x*c12.x*c20.y*c13.x*c21.y*c13.y + c11.x*c20.y*c21.x*c12.y*c13.x*c13.y - c20.x*c11.y*c12.x*c13.x*c21.y*c13.y - 6*c20.x*c11.y*c21.x*c12.y*c13.x*c13.y - c11.y*c12.x*c20.y*c21.x*c13.x*c13.y - 6*c10.x*c20.x*c21.x*c13y3 - 2*c10.x*c21.x*c12y3*c13.x + 6*c10.y*c20.y*c13x3*c21.y + 2*c20.x*c21.x*c12y3*c13.x + 2*c10.y*c12x3*c21.y*c13.y - 2*c12x3*c20.y*c21.y*c13.y - 6*c10.x*c10.y*c21.x*c13.x*c13y2 + 3*c10.x*c11.x*c12.x*c21.y*c13y2 - 2*c10.x*c11.x*c21.x*c12.y*c13y2 - 4*c10.x*c11.y*c12.x*c21.x*c13y2 + 3*c10.y*c11.x*c12.x*c21.x*c13y2 + 6*c10.x*c10.y*c13x2*c21.y*c13.y + 6*c10.x*c20.x*c13.x*c21.y*c13y2 - 3*c10.x*c11.y*c12.y*c13x2*c21.y + 2*c10.x*c12.x*c21.x*c12y2*c13.y + 2*c10.x*c12.x*c12y2*c13.x*c21.y + 6*c10.x*c20.y*c21.x*c13.x*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c21.y + 6*c10.y*c20.x*c21.x*c13.x*c13y2 + 2*c10.y*c11.y*c12.x*c13x2*c21.y - 3*c10.y*c11.y*c21.x*c12.y*c13x2 + 2*c10.y*c12.x*c21.x*c12y2*c13.x - 3*c11.x*c20.x*c12.x*c21.y*c13y2 + 2*c11.x*c20.x*c21.x*c12.y*c13y2 + c11.x*c11.y*c21.x*c12y2*c13.x - 3*c11.x*c12.x*c20.y*c21.x*c13y2 + 4*c20.x*c11.y*c12.x*c21.x*c13y2 - 6*c10.x*c20.y*c13x2*c21.y*c13.y - 2*c10.x*c12x2*c12.y*c21.y*c13.y - 6*c10.y*c20.x*c13x2*c21.y*c13.y - 6*c10.y*c20.y*c21.x*c13x2*c13.y - 2*c10.y*c12x2*c21.x*c12.y*c13.y - 2*c10.y*c12x2*c12.y*c13.x*c21.y - c11.x*c11.y*c12x2*c21.y*c13.y - 4*c11.x*c20.y*c12.y*c13x2*c21.y - 2*c11.x*c11y2*c21.x*c13.x*c13.y + 3*c20.x*c11.y*c12.y*c13x2*c21.y - 2*c20.x*c12.x*c21.x*c12y2*c13.y - 2*c20.x*c12.x*c12y2*c13.x*c21.y - 6*c20.x*c20.y*c21.x*c13.x*c13y2 - 2*c11.y*c12.x*c20.y*c13x2*c21.y + 3*c11.y*c20.y*c21.x*c12.y*c13x2 - 2*c12.x*c20.y*c21.x*c12y2*c13.x - c11y2*c12.x*c21.x*c12.y*c13.x + 6*c20.x*c20.y*c13x2*c21.y*c13.y + 2*c20.x*c12x2*c12.y*c21.y*c13.y + 2*c11x2*c11.y*c13.x*c21.y*c13.y + c11x2*c12.x*c12.y*c21.y*c13.y + 2*c12x2*c20.y*c21.x*c12.y*c13.y + 2*c12x2*c20.y*c12.y*c13.x*c21.y + 3*c10x2*c21.x*c13y3 - 3*c10y2*c13x3*c21.y + 3*c20x2*c21.x*c13y3 + c11y3*c21.x*c13x2 - c11x3*c21.y*c13y2 - 3*c20y2*c13x3*c21.y - c11.x*c11y2*c13x2*c21.y + c11x2*c11.y*c21.x*c13y2 - 3*c10x2*c13.x*c21.y*c13y2 + 3*c10y2*c21.x*c13x2*c13.y - c11x2*c12y2*c13.x*c21.y + c11y2*c12x2*c21.x*c13.y - 3*c20x2*c13.x*c21.y*c13y2 + 3*c20y2*c21.x*c13x2*c13.y, c10.x*c10.y*c11.x*c12.y*c13.x*c13.y - c10.x*c10.y*c11.y*c12.x*c13.x*c13.y + c10.x*c11.x*c11.y*c12.x*c12.y*c13.y - c10.y*c11.x*c11.y*c12.x*c12.y*c13.x - c10.x*c11.x*c20.y*c12.y*c13.x*c13.y + 6*c10.x*c20.x*c11.y*c12.y*c13.x*c13.y + c10.x*c11.y*c12.x*c20.y*c13.x*c13.y - c10.y*c11.x*c20.x*c12.y*c13.x*c13.y - 6*c10.y*c11.x*c12.x*c20.y*c13.x*c13.y + c10.y*c20.x*c11.y*c12.x*c13.x*c13.y - c11.x*c20.x*c11.y*c12.x*c12.y*c13.y + c11.x*c11.y*c12.x*c20.y*c12.y*c13.x + c11.x*c20.x*c20.y*c12.y*c13.x*c13.y - c20.x*c11.y*c12.x*c20.y*c13.x*c13.y - 2*c10.x*c20.x*c12y3*c13.x + 2*c10.y*c12x3*c20.y*c13.y - 3*c10.x*c10.y*c11.x*c12.x*c13y2 - 6*c10.x*c10.y*c20.x*c13.x*c13y2 + 3*c10.x*c10.y*c11.y*c12.y*c13x2 - 2*c10.x*c10.y*c12.x*c12y2*c13.x - 2*c10.x*c11.x*c20.x*c12.y*c13y2 - c10.x*c11.x*c11.y*c12y2*c13.x + 3*c10.x*c11.x*c12.x*c20.y*c13y2 - 4*c10.x*c20.x*c11.y*c12.x*c13y2 + 3*c10.y*c11.x*c20.x*c12.x*c13y2 + 6*c10.x*c10.y*c20.y*c13x2*c13.y + 2*c10.x*c10.y*c12x2*c12.y*c13.y + 2*c10.x*c11.x*c11y2*c13.x*c13.y + 2*c10.x*c20.x*c12.x*c12y2*c13.y + 6*c10.x*c20.x*c20.y*c13.x*c13y2 - 3*c10.x*c11.y*c20.y*c12.y*c13x2 + 2*c10.x*c12.x*c20.y*c12y2*c13.x + c10.x*c11y2*c12.x*c12.y*c13.x + c10.y*c11.x*c11.y*c12x2*c13.y + 4*c10.y*c11.x*c20.y*c12.y*c13x2 - 3*c10.y*c20.x*c11.y*c12.y*c13x2 + 2*c10.y*c20.x*c12.x*c12y2*c13.x + 2*c10.y*c11.y*c12.x*c20.y*c13x2 + c11.x*c20.x*c11.y*c12y2*c13.x - 3*c11.x*c20.x*c12.x*c20.y*c13y2 - 2*c10.x*c12x2*c20.y*c12.y*c13.y - 6*c10.y*c20.x*c20.y*c13x2*c13.y - 2*c10.y*c20.x*c12x2*c12.y*c13.y - 2*c10.y*c11x2*c11.y*c13.x*c13.y - c10.y*c11x2*c12.x*c12.y*c13.y - 2*c10.y*c12x2*c20.y*c12.y*c13.x - 2*c11.x*c20.x*c11y2*c13.x*c13.y - c11.x*c11.y*c12x2*c20.y*c13.y + 3*c20.x*c11.y*c20.y*c12.y*c13x2 - 2*c20.x*c12.x*c20.y*c12y2*c13.x - c20.x*c11y2*c12.x*c12.y*c13.x + 3*c10y2*c11.x*c12.x*c13.x*c13.y + 3*c11.x*c12.x*c20y2*c13.x*c13.y + 2*c20.x*c12x2*c20.y*c12.y*c13.y - 3*c10x2*c11.y*c12.y*c13.x*c13.y + 2*c11x2*c11.y*c20.y*c13.x*c13.y + c11x2*c12.x*c20.y*c12.y*c13.y - 3*c20x2*c11.y*c12.y*c13.x*c13.y - c10x3*c13y3 + c10y3*c13x3 + c20x3*c13y3 - c20y3*c13x3 - 3*c10.x*c20x2*c13y3 - c10.x*c11y3*c13x2 + 3*c10x2*c20.x*c13y3 + c10.y*c11x3*c13y2 + 3*c10.y*c20y2*c13x3 + c20.x*c11y3*c13x2 + c10x2*c12y3*c13.x - 3*c10y2*c20.y*c13x3 - c10y2*c12x3*c13.y + c20x2*c12y3*c13.x - c11x3*c20.y*c13y2 - c12x3*c20y2*c13.y - c10.x*c11x2*c11.y*c13y2 + c10.y*c11.x*c11y2*c13x2 - 3*c10.x*c10y2*c13x2*c13.y - c10.x*c11y2*c12x2*c13.y + c10.y*c11x2*c12y2*c13.x - c11.x*c11y2*c20.y*c13x2 + 3*c10x2*c10.y*c13.x*c13y2 + c10x2*c11.x*c12.y*c13y2 + 2*c10x2*c11.y*c12.x*c13y2 - 2*c10y2*c11.x*c12.y*c13x2 - c10y2*c11.y*c12.x*c13x2 + c11x2*c20.x*c11.y*c13y2 - 3*c10.x*c20y2*c13x2*c13.y + 3*c10.y*c20x2*c13.x*c13y2 + c11.x*c20x2*c12.y*c13y2 - 2*c11.x*c20y2*c12.y*c13x2 + c20.x*c11y2*c12x2*c13.y - c11.y*c12.x*c20y2*c13x2 - c10x2*c12.x*c12y2*c13.y - 3*c10x2*c20.y*c13.x*c13y2 + 3*c10y2*c20.x*c13x2*c13.y + c10y2*c12x2*c12.y*c13.x - c11x2*c20.y*c12y2*c13.x + 2*c20x2*c11.y*c12.x*c13y2 + 3*c20.x*c20y2*c13x2*c13.y - c20x2*c12.x*c12y2*c13.y - 3*c20x2*c20.y*c13.x*c13y2 + c12x2*c20y2*c12.y*c13.x ]) roots = poly.rootsInterval(0, 1) for own i, s of roots xRoots = new Polynomial([ c13.x c12.x c11.x c10.x - c20.x - s * c21.x - s * s * c22.x - s * s * s * c23.x ]).roots() yRoots = new Polynomial([ c13.y c12.y c11.y c10.y - c20.y - s * c21.y - s * s * c22.y - s * s * s * c23.y ]).roots() if xRoots.length > 0 and yRoots.length > 0 # IMPORTANT # Tweaking this to be smaller can make it miss intersections. tolerance = 1e-2 for own j, xRoot of xRoots if 0 <= xRoot and xRoot <= 1 for own k, yRoot of yRoots if Math.abs(xRoot - yRoot) < tolerance results.push( c23.multiplyBy(s * s * s).add(c22.multiplyBy(s * s).add(c21.multiplyBy(s).add(c20)))) results
84191
### Internal representation of a cubic bezier line segment p1 p4 o o \\ // \\ // \ \ / / \ \ / / \ _ _ / \ __ __ / ° --_____-- ° p2 p3 I/P: p1: First absolute point, the moveto p2: The first point's curve handle p3: The second point's curve handle p4: The second absolute point In context with syntax: M[p1]C[p2] [p3] [p4] ### class CubicBezier constructor: (@p1, @p2, @p3, @p4, @source = @toCurveTo()) -> ### toString: -> "(Cubic bezier: #{@p1},#{@p2},#{@p3},#{@p4})" ### toString: -> "new CubicBezier(#{@p1}, #{@p2}, #{@p3}, #{@p4})" toCurveTo: -> new CurveTo(@p2.x, @p2.y, @p3.x, @p3.y, @p4.x, @p4.y) toSVGPoint: -> @toCurveTo() length: -> # Not that accurate lol @intoLineSegments(4).reduce((a, b) -> a + b.length) beginning: -> @p1 end: -> @p4 nudge: (x, y) -> @p1.nudge(x, y) @p2.nudge(x, y) @p3.nudge(x, y) @p4.nudge(x, y) @ scale: (x, y, origin) -> @p1.scale(x, y, origin) @p2.scale(x, y, origin) @p3.scale(x, y, origin) @p4.scale(x, y, origin) @ rotate: (angle, origin) -> @p1.rotate(angle, origin) @p2.rotate(angle, origin) @p3.rotate(angle, origin) @p4.rotate(angle, origin) @ reverse: -> # Note: this makes it lose its source new CubicBezier @p4, @p3, @p2, @p1 equal: (cbls) -> return false if cbls instanceof LineSegment (((@p1.equal cbls.p1) && (@p2.equal cbls.p2) && (@p3.equal cbls.p3) && (@p4.equal cbls.p4)) || ((@p1.equal cbls.p4) && (@p2.equal cbls.p3) && (@p3.equal cbls.p2) && (@p4.equal cbls.p1))) intersects: (other) -> inter = @intersection(other) inter instanceof Posn or (inter instanceof Array and inter.length > 0) intersection: (other) -> switch other.constructor when LineSegment return @intersectionWithLineSegment(other) when CubicBezier return @intersectionWithCubicBezier(other) xRange: -> @bounds().xr yRange: -> @bounds().yr ends: -> [@p1, @p4] midPoint: -> @splitAt(0.5)[0].p4 bounds: (useCached = false) -> if @boundsCached? and useCached return @boundsCached minx = miny = Infinity maxx = maxy = -Infinity top2x = @p2.x - @p1.x top2y = @p2.y - @p1.y top3x = @p3.x - @p2.x top3y = @p3.y - @p2.y top4x = @p4.x - @p3.x top4y = @p4.y - @p3.y for i in [0..40] d = i / 40 px = @p1.x + d * top2x py = @p1.y + d * top2y qx = @p2.x + d * top3x qy = @p2.y + d * top3y rx = @p3.x + d * top4x ry = @p3.y + d * top4y toqx = qx - px toqy = qy - py torx = rx - qx tory = ry - qy sx = px + d * toqx sy = py + d * toqy tx = qx + d * torx ty = qy + d * tory totx = tx - sx toty = ty - sy x = sx + d * totx y = sy + d * toty minx = Math.min(minx, x) miny = Math.min(miny, y) maxx = Math.max(maxx, x) maxy = Math.max(maxy, y) width = maxx - minx height = maxy - miny # Cache the bounds and return them at the same time @boundsCached = new Bounds(minx, miny, width, height) boundsCached: undefined intoLineSegments: (n) -> # Given n, split the bezier into n consecutive LineSegments, returned in an Array # # I/P: n, number # O/P: [LineSegment, LineSegment, LineSegment...] array segments = [] for m in [0..n] i = 1 / m x = Math.pow((1-i), 3) * @p1.x + 3 * Math.pow((1-i), 2) * i * @p2.x + 3 * (1 - i) * Math.pow(i, 2) * @p3.x + Math.pow(i, 3) * @p4.x y = Math.pow((1-i), 3) * @p1.y + 3 * Math.pow((1-i), 2) * i * @p2.y + 3 * (1 - i) * Math.pow(i, 2) * @p3.y + Math.pow(i, 3) * @p4.y if m % 2 == 0 last = new Posn(x, y) else segments.push new LineSegment(last, new Posn(x, y)) segments.splice 1 splitAt: (t, force = null) -> # Given a float t between 0 and 1, return two CubicBeziers that result from splitting this one at that percentage in. # # I/P: t, number between 0 and 1 # O/P: [CubicBezier, CubicBezier] array # # Uses de Casteljau's algorithm. Really damn good resources: # http://processingjs.nihongoresources.com/bezierinfo/ # http://en.wikipedia.org/wiki/De_Casteljau's_algorithm # # Example, splitting in half: # t = 0.5 # p1: (10,10), p2: (20, 5), p3: (40, 20), p4: (50, 10) # p5: (15, 7.5), p6: (30, 12.5), p7: (45, 15) # p8: (22.5, 10), p9: (37.5, 13.75) # p10: (30, 11.875) # # The split will happen at exactly p10, so the resulting curves will end and start there, respectively. # The resulting curves will be # [new CubicBezier(p1, p5, p8, p10), new CubicBezier(p10, p9, p7, p4)] if typeof t is "number" p5 = new LineSegment(@p1, @p2).posnAtPercent t p6 = new LineSegment(@p2, @p3).posnAtPercent t p7 = new LineSegment(@p3, @p4).posnAtPercent t p8 = new LineSegment(p5, p6).posnAtPercent t p9 = new LineSegment(p6, p7).posnAtPercent t p10 = if force then force else new LineSegment(p8, p9).posnAtPercent t return [new CubicBezier(@p1, p5, p8, p10), new CubicBezier(p10, p9, p7, @p4)] else if t instanceof Posn # Given a single Posn, find its percentage and then split the line on it. return @splitAt(@findPercentageOfPoint(t), t) else if t instanceof Array # Given a list of Posns, we have a bit more work to do. # We need to sort the Posns by their percentage along on the original line. # Then we recur on the line, splitting it on each posn that occurs from 0.0 to 1.0. # We always recur on the second half of the resulting split with # the next Posn in line. # We're going to use the Posns' percentages as keys # with which we'll sort them and split the line on them # one after the other. sortedPosns = {} # This will be the final array of split segments. segments = [] # Find percentage for each posn, save the posn under that percentage. for posn in t percent = @findPercentageOfPoint posn sortedPosns[percent] = posn # Sort the keys - the list of percentages at which posns are available. percentages = Object.keys(sortedPosns).map(parseFloat).sort(sortNumbers) # Start by splitting the entire bezier. tail = @ # For each posn, going in order of percentages... for perc in percentages # Split the tail on that single posn pair = tail.splitAt sortedPosns[perc] # Keep the first half segments.push pair[0] # And "recur" on the second half by redefining tail to be it tail = pair[1] # Don't abandon that last tail! ;) segments.push tail # Shazam return segments findPercentageOfPoint: (posn, tolerance = 1e-3, accumulated = 0.0, nextstep = 0.5) -> # Recursively find the percentage (float from 0 - 1) of given posn on this bezier, within tolerance given. # This works so well. I am so stoked about it. # Basically, this splits the given bezier in half. If the midpoint is within the tolerance of the posn we're looking for, # return the accumulated float. If not, it will recur on either or both of its halves, # adding (0.5 * n / 2) to the accumulator for the one on the right and keeping it the same for the one on the left # where n is the depth of recursion. # # I/P: posn: the Posn we're looking for # [tolerance]: find the value for within this much of the x and y of the given posn. # # Ignore the accumulated and nextstep values, those should start as they're precoded. # # O/P: A float between 0 and 1. split = @splitAt(0.5) a = split[0] b = split[1] # Base case - we've found it! Return the amt accumulated. if a.p4.within(tolerance, posn) or nextstep < 1e-4 return accumulated # Recursion ab = a.bounds() bb = b.bounds() # Both halves might contain the point, if we have a shape that overlaps itself for example. # For this reason we have to actually recur on both the left and right. # When staying with a, however, we don't add to the accumulator because we're not advancing to the second half of the line. # We're simply not making the jump, so we don't count it. But we might make the next smallest jump when we recur on a. if ab.xr.containsInclusive(posn.x, 0.2) and ab.yr.containsInclusive(posn.y, 0.2) ac = a.findPercentageOfPoint(posn, tolerance, accumulated, nextstep / 2) if bb.xr.containsInclusive(posn.x, 0.2) and bb.yr.containsInclusive(posn.y, 0.2) bc = b.findPercentageOfPoint(posn, tolerance, accumulated + nextstep, nextstep / 2) # This is where the recursion bottoms out. Null means it's not on the bezier line within the tolerance. # ############# # IMPORTANT # ############# # This is a compromise right now. Since the intersection algorithm is imperfect, we get as close as we can and # return accumulated if there are no options. NOT null, which it used to be. # All this means is that if a point is given that's a bit off the line the recursion will stop when it can't # get any closer to it. So it does what it can, basically. # # This means you can't just feed any point into this and expect it to ignore you given a bad point. # This also means there is some tolerance to a point being a little bit off, which can happen when calculating # several intersections on one curve. # # It's very accurate this way. Nothing to worry about. Just a note so I don't forget. <3 if ac? then ac else if bc? then bc else accumulated ### Intersection methods ### intersectionWithLineSegment: (l) -> ### Given a LineSegment, lists intersection point(s). I/P: LineSegment O/P: Array of Posns I am a cute sick <NAME> i love monodebe and I learn all about the flexible scemless data base Disclaimer: I don't really understand this but it passes my tests. ### min = l.a.min(l.b) max = l.a.max(l.b) results = [] a = @p1.multiplyBy -1 b = @p2.multiplyBy 3 c = @p3.multiplyBy -3 d = a.add(b.add(c.add(@p4))) c3 = new Posn(d.x, d.y) a = @p1.multiplyBy 3 b = @p2.multiplyBy -6 c = @p3.multiplyBy 3 d = a.add(b.add(c)) c2 = new Posn(d.x, d.y) a = @p1.multiplyBy -3 b = @p2.multiplyBy 3 c = a.add b c1 = new Posn(c.x, c.y) c0 = new Posn(@p1.x, @p1.y) n = new Posn(l.a.y - l.b.y, l.b.x - l.a.x) cl = l.a.x * l.b.y - l.b.x * l.a.y roots = new Polynomial([n.dot(c3), n.dot(c2), n.dot(c1), n.dot(c0) + cl]).roots() for i,t of roots if 0 <= t and t <= 1 p5 = @p1.lerp(@p2, t) p6 = @p2.lerp(@p3, t) p7 = @p3.lerp(@p4, t) p8 = p5.lerp(p6, t) p9 = p6.lerp(p7, t) p10 = p8.lerp(p9, t) if l.a.x is l.b.x if (min.y <= p10.y) and (p10.y <= max.y) results.push p10 else if l.a.y is l.b.y if min.x <= p10.x and p10.x <= max.x results.push p10 else if p10.gte(min) and p10.lte(max) results.push p10 results intersectionWithCubicBezier: (other) -> # I don't know. # # I/P: Another CubicBezier # O/P: Array of Posns. # # Source: http://www.kevlindev.com/gui/math/intersection/index.htm#Anchor-intersectBezie-45477 results = [] a = @p1.multiplyBy(-1) b = @p2.multiplyBy(3) c = @p3.multiplyBy(-3) d = a.add(b.add(c.add(@p4))) c13 = new Posn(d.x, d.y) a = @p1.multiplyBy(3) b = @p2.multiplyBy(-6) c = @p3.multiplyBy(3) d = a.add(b.add(c)) c12 = new Posn(d.x, d.y) a = @p1.multiplyBy(-3) b = @p2.multiplyBy(3) c = a.add(b) c11 = new Posn(c.x, c.y) c10 = new Posn(@p1.x, @p1.y) a = other.p1.multiplyBy(-1) b = other.p2.multiplyBy(3) c = other.p3.multiplyBy(-3) d = a.add(b.add(c.add(other.p4))) c23 = new Posn(d.x, d.y) a = other.p1.multiplyBy(3) b = other.p2.multiplyBy(-6) c = other.p3.multiplyBy(3) d = a.add(b.add(c)) c22 = new Posn(d.x, d.y) a = other.p1.multiplyBy(-3) b = other.p2.multiplyBy(3) c = a.add(b) c21 = new Posn(c.x, c.y) c20 = new Posn(other.p1.x, other.p1.y) c10x2 = c10.x * c10.x c10x3 = c10.x * c10.x * c10.x c10y2 = c10.y * c10.y c10y3 = c10.y * c10.y * c10.y c11x2 = c11.x * c11.x c11x3 = c11.x * c11.x * c11.x c11y2 = c11.y * c11.y c11y3 = c11.y * c11.y * c11.y c12x2 = c12.x * c12.x c12x3 = c12.x * c12.x * c12.x c12y2 = c12.y * c12.y c12y3 = c12.y * c12.y * c12.y c13x2 = c13.x * c13.x c13x3 = c13.x * c13.x * c13.x c13y2 = c13.y * c13.y c13y3 = c13.y * c13.y * c13.y c20x2 = c20.x * c20.x c20x3 = c20.x * c20.x * c20.x c20y2 = c20.y * c20.y c20y3 = c20.y * c20.y * c20.y c21x2 = c21.x * c21.x c21x3 = c21.x * c21.x * c21.x c21y2 = c21.y * c21.y c22x2 = c22.x * c22.x c22x3 = c22.x * c22.x * c22.x c22y2 = c22.y * c22.y c23x2 = c23.x * c23.x c23x3 = c23.x * c23.x * c23.x c23y2 = c23.y * c23.y c23y3 = c23.y * c23.y * c23.y poly = new Polynomial([ -c13x3*c23y3 + c13y3*c23x3 - 3*c13.x*c13y2*c23x2*c23.y + 3*c13x2*c13.y*c23.x*c23y2, -6*c13.x*c22.x*c13y2*c23.x*c23.y + 6*c13x2*c13.y*c22.y*c23.x*c23.y + 3*c22.x*c13y3*c23x2 - 3*c13x3*c22.y*c23y2 - 3*c13.x*c13y2*c22.y*c23x2 + 3*c13x2*c22.x*c13.y*c23y2, -6*c21.x*c13.x*c13y2*c23.x*c23.y - 6*c13.x*c22.x*c13y2*c22.y*c23.x + 6*c13x2*c22.x*c13.y*c22.y*c23.y + 3*c21.x*c13y3*c23x2 + 3*c22x2*c13y3*c23.x + 3*c21.x*c13x2*c13.y*c23y2 - 3*c13.x*c21.y*c13y2*c23x2 - 3*c13.x*c22x2*c13y2*c23.y + c13x2*c13.y*c23.x*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-c21.y*c23y2 - 2*c22y2*c23.y - c23.y*(2*c21.y*c23.y + c22y2)), c11.x*c12.y*c13.x*c13.y*c23.x*c23.y - c11.y*c12.x*c13.x*c13.y*c23.x*c23.y + 6*c21.x*c22.x*c13y3*c23.x + 3*c11.x*c12.x*c13.x*c13.y*c23y2 + 6*c10.x*c13.x*c13y2*c23.x*c23.y - 3*c11.x*c12.x*c13y2*c23.x*c23.y - 3*c11.y*c12.y*c13.x*c13.y*c23x2 - 6*c10.y*c13x2*c13.y*c23.x*c23.y - 6*c20.x*c13.x*c13y2*c23.x*c23.y + 3*c11.y*c12.y*c13x2*c23.x*c23.y - 2*c12.x*c12y2*c13.x*c23.x*c23.y - 6*c21.x*c13.x*c22.x*c13y2*c23.y - 6*c21.x*c13.x*c13y2*c22.y*c23.x - 6*c13.x*c21.y*c22.x*c13y2*c23.x + 6*c21.x*c13x2*c13.y*c22.y*c23.y + 2*c12x2*c12.y*c13.y*c23.x*c23.y + c22x3*c13y3 - 3*c10.x*c13y3*c23x2 + 3*c10.y*c13x3*c23y2 + 3*c20.x*c13y3*c23x2 + c12y3*c13.x*c23x2 - c12x3*c13.y*c23y2 - 3*c10.x*c13x2*c13.y*c23y2 + 3*c10.y*c13.x*c13y2*c23x2 - 2*c11.x*c12.y*c13x2*c23y2 + c11.x*c12.y*c13y2*c23x2 - c11.y*c12.x*c13x2*c23y2 + 2*c11.y*c12.x*c13y2*c23x2 + 3*c20.x*c13x2*c13.y*c23y2 - c12.x*c12y2*c13.y*c23x2 - 3*c20.y*c13.x*c13y2*c23x2 + c12x2*c12.y*c13.x*c23y2 - 3*c13.x*c22x2*c13y2*c22.y + c13x2*c13.y*c23.x*(6*c20.y*c23.y + 6*c21.y*c22.y) + c13x2*c22.x*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c21.y*c22.y*c23.y - c20.y*c23y2 - c22.y*(2*c21.y*c23.y + c22y2) - c23.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), 6*c11.x*c12.x*c13.x*c13.y*c22.y*c23.y + c11.x*c12.y*c13.x*c22.x*c13.y*c23.y + c11.x*c12.y*c13.x*c13.y*c22.y*c23.x - c11.y*c12.x*c13.x*c22.x*c13.y*c23.y - c11.y*c12.x*c13.x*c13.y*c22.y*c23.x - 6*c11.y*c12.y*c13.x*c22.x*c13.y*c23.x - 6*c10.x*c22.x*c13y3*c23.x + 6*c20.x*c22.x*c13y3*c23.x + 6*c10.y*c13x3*c22.y*c23.y + 2*c12y3*c13.x*c22.x*c23.x - 2*c12x3*c13.y*c22.y*c23.y + 6*c10.x*c13.x*c22.x*c13y2*c23.y + 6*c10.x*c13.x*c13y2*c22.y*c23.x + 6*c10.y*c13.x*c22.x*c13y2*c23.x - 3*c11.x*c12.x*c22.x*c13y2*c23.y - 3*c11.x*c12.x*c13y2*c22.y*c23.x + 2*c11.x*c12.y*c22.x*c13y2*c23.x + 4*c11.y*c12.x*c22.x*c13y2*c23.x - 6*c10.x*c13x2*c13.y*c22.y*c23.y - 6*c10.y*c13x2*c22.x*c13.y*c23.y - 6*c10.y*c13x2*c13.y*c22.y*c23.x - 4*c11.x*c12.y*c13x2*c22.y*c23.y - 6*c20.x*c13.x*c22.x*c13y2*c23.y - 6*c20.x*c13.x*c13y2*c22.y*c23.x - 2*c11.y*c12.x*c13x2*c22.y*c23.y + 3*c11.y*c12.y*c13x2*c22.x*c23.y + 3*c11.y*c12.y*c13x2*c22.y*c23.x - 2*c12.x*c12y2*c13.x*c22.x*c23.y - 2*c12.x*c12y2*c13.x*c22.y*c23.x - 2*c12.x*c12y2*c22.x*c13.y*c23.x - 6*c20.y*c13.x*c22.x*c13y2*c23.x - 6*c21.x*c13.x*c21.y*c13y2*c23.x - 6*c21.x*c13.x*c22.x*c13y2*c22.y + 6*c20.x*c13x2*c13.y*c22.y*c23.y + 2*c12x2*c12.y*c13.x*c22.y*c23.y + 2*c12x2*c12.y*c22.x*c13.y*c23.y + 2*c12x2*c12.y*c13.y*c22.y*c23.x + 3*c21.x*c22x2*c13y3 + 3*c21x2*c13y3*c23.x - 3*c13.x*c21.y*c22x2*c13y2 - 3*c21x2*c13.x*c13y2*c23.y + c13x2*c22.x*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c13x2*c13.y*c23.x*(6*c20.y*c22.y + 3*c21y2) + c21.x*c13x2*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c20.y*c22.y*c23.y - c23.y*(2*c20.y*c22.y + c21y2) - c21.y*(2*c21.y*c23.y + c22y2) - c22.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), c11.x*c21.x*c12.y*c13.x*c13.y*c23.y + c11.x*c12.y*c13.x*c21.y*c13.y*c23.x + c11.x*c12.y*c13.x*c22.x*c13.y*c22.y - c11.y*c12.x*c21.x*c13.x*c13.y*c23.y - c11.y*c12.x*c13.x*c21.y*c13.y*c23.x - c11.y*c12.x*c13.x*c22.x*c13.y*c22.y - 6*c11.y*c21.x*c12.y*c13.x*c13.y*c23.x - 6*c10.x*c21.x*c13y3*c23.x + 6*c20.x*c21.x*c13y3*c23.x + 2*c21.x*c12y3*c13.x*c23.x + 6*c10.x*c21.x*c13.x*c13y2*c23.y + 6*c10.x*c13.x*c21.y*c13y2*c23.x + 6*c10.x*c13.x*c22.x*c13y2*c22.y + 6*c10.y*c21.x*c13.x*c13y2*c23.x - 3*c11.x*c12.x*c21.x*c13y2*c23.y - 3*c11.x*c12.x*c21.y*c13y2*c23.x - 3*c11.x*c12.x*c22.x*c13y2*c22.y + 2*c11.x*c21.x*c12.y*c13y2*c23.x + 4*c11.y*c12.x*c21.x*c13y2*c23.x - 6*c10.y*c21.x*c13x2*c13.y*c23.y - 6*c10.y*c13x2*c21.y*c13.y*c23.x - 6*c10.y*c13x2*c22.x*c13.y*c22.y - 6*c20.x*c21.x*c13.x*c13y2*c23.y - 6*c20.x*c13.x*c21.y*c13y2*c23.x - 6*c20.x*c13.x*c22.x*c13y2*c22.y + 3*c11.y*c21.x*c12.y*c13x2*c23.y - 3*c11.y*c12.y*c13.x*c22x2*c13.y + 3*c11.y*c12.y*c13x2*c21.y*c23.x + 3*c11.y*c12.y*c13x2*c22.x*c22.y - 2*c12.x*c21.x*c12y2*c13.x*c23.y - 2*c12.x*c21.x*c12y2*c13.y*c23.x - 2*c12.x*c12y2*c13.x*c21.y*c23.x - 2*c12.x*c12y2*c13.x*c22.x*c22.y - 6*c20.y*c21.x*c13.x*c13y2*c23.x - 6*c21.x*c13.x*c21.y*c22.x*c13y2 + 6*c20.y*c13x2*c21.y*c13.y*c23.x + 2*c12x2*c21.x*c12.y*c13.y*c23.y + 2*c12x2*c12.y*c21.y*c13.y*c23.x + 2*c12x2*c12.y*c22.x*c13.y*c22.y - 3*c10.x*c22x2*c13y3 + 3*c20.x*c22x2*c13y3 + 3*c21x2*c22.x*c13y3 + c12y3*c13.x*c22x2 + 3*c10.y*c13.x*c22x2*c13y2 + c11.x*c12.y*c22x2*c13y2 + 2*c11.y*c12.x*c22x2*c13y2 - c12.x*c12y2*c22x2*c13.y - 3*c20.y*c13.x*c22x2*c13y2 - 3*c21x2*c13.x*c13y2*c22.y + c12x2*c12.y*c13.x*(2*c21.y*c23.y + c22y2) + c11.x*c12.x*c13.x*c13.y*(6*c21.y*c23.y + 3*c22y2) + c21.x*c13x2*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c12x3*c13.y*(-2*c21.y*c23.y - c22y2) + c10.y*c13x3*(6*c21.y*c23.y + 3*c22y2) + c11.y*c12.x*c13x2*(-2*c21.y*c23.y - c22y2) + c11.x*c12.y*c13x2*(-4*c21.y*c23.y - 2*c22y2) + c10.x*c13x2*c13.y*(-6*c21.y*c23.y - 3*c22y2) + c13x2*c22.x*c13.y*(6*c20.y*c22.y + 3*c21y2) + c20.x*c13x2*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c20.y*c21.y*c23.y - c22.y*(2*c20.y*c22.y + c21y2) - c20.y*(2*c21.y*c23.y + c22y2) - c21.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), -c10.x*c11.x*c12.y*c13.x*c13.y*c23.y + c10.x*c11.y*c12.x*c13.x*c13.y*c23.y + 6*c10.x*c11.y*c12.y*c13.x*c13.y*c23.x - 6*c10.y*c11.x*c12.x*c13.x*c13.y*c23.y - c10.y*c11.x*c12.y*c13.x*c13.y*c23.x + c10.y*c11.y*c12.x*c13.x*c13.y*c23.x + c11.x*c11.y*c12.x*c12.y*c13.x*c23.y - c11.x*c11.y*c12.x*c12.y*c13.y*c23.x + c11.x*c20.x*c12.y*c13.x*c13.y*c23.y + c11.x*c20.y*c12.y*c13.x*c13.y*c23.x + c11.x*c21.x*c12.y*c13.x*c13.y*c22.y + c11.x*c12.y*c13.x*c21.y*c22.x*c13.y - c20.x*c11.y*c12.x*c13.x*c13.y*c23.y - 6*c20.x*c11.y*c12.y*c13.x*c13.y*c23.x - c11.y*c12.x*c20.y*c13.x*c13.y*c23.x - c11.y*c12.x*c21.x*c13.x*c13.y*c22.y - c11.y*c12.x*c13.x*c21.y*c22.x*c13.y - 6*c11.y*c21.x*c12.y*c13.x*c22.x*c13.y - 6*c10.x*c20.x*c13y3*c23.x - 6*c10.x*c21.x*c22.x*c13y3 - 2*c10.x*c12y3*c13.x*c23.x + 6*c20.x*c21.x*c22.x*c13y3 + 2*c20.x*c12y3*c13.x*c23.x + 2*c21.x*c12y3*c13.x*c22.x + 2*c10.y*c12x3*c13.y*c23.y - 6*c10.x*c10.y*c13.x*c13y2*c23.x + 3*c10.x*c11.x*c12.x*c13y2*c23.y - 2*c10.x*c11.x*c12.y*c13y2*c23.x - 4*c10.x*c11.y*c12.x*c13y2*c23.x + 3*c10.y*c11.x*c12.x*c13y2*c23.x + 6*c10.x*c10.y*c13x2*c13.y*c23.y + 6*c10.x*c20.x*c13.x*c13y2*c23.y - 3*c10.x*c11.y*c12.y*c13x2*c23.y + 2*c10.x*c12.x*c12y2*c13.x*c23.y + 2*c10.x*c12.x*c12y2*c13.y*c23.x + 6*c10.x*c20.y*c13.x*c13y2*c23.x + 6*c10.x*c21.x*c13.x*c13y2*c22.y + 6*c10.x*c13.x*c21.y*c22.x*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c23.y + 6*c10.y*c20.x*c13.x*c13y2*c23.x + 2*c10.y*c11.y*c12.x*c13x2*c23.y - 3*c10.y*c11.y*c12.y*c13x2*c23.x + 2*c10.y*c12.x*c12y2*c13.x*c23.x + 6*c10.y*c21.x*c13.x*c22.x*c13y2 - 3*c11.x*c20.x*c12.x*c13y2*c23.y + 2*c11.x*c20.x*c12.y*c13y2*c23.x + c11.x*c11.y*c12y2*c13.x*c23.x - 3*c11.x*c12.x*c20.y*c13y2*c23.x - 3*c11.x*c12.x*c21.x*c13y2*c22.y - 3*c11.x*c12.x*c21.y*c22.x*c13y2 + 2*c11.x*c21.x*c12.y*c22.x*c13y2 + 4*c20.x*c11.y*c12.x*c13y2*c23.x + 4*c11.y*c12.x*c21.x*c22.x*c13y2 - 2*c10.x*c12x2*c12.y*c13.y*c23.y - 6*c10.y*c20.x*c13x2*c13.y*c23.y - 6*c10.y*c20.y*c13x2*c13.y*c23.x - 6*c10.y*c21.x*c13x2*c13.y*c22.y - 2*c10.y*c12x2*c12.y*c13.x*c23.y - 2*c10.y*c12x2*c12.y*c13.y*c23.x - 6*c10.y*c13x2*c21.y*c22.x*c13.y - c11.x*c11.y*c12x2*c13.y*c23.y - 2*c11.x*c11y2*c13.x*c13.y*c23.x + 3*c20.x*c11.y*c12.y*c13x2*c23.y - 2*c20.x*c12.x*c12y2*c13.x*c23.y - 2*c20.x*c12.x*c12y2*c13.y*c23.x - 6*c20.x*c20.y*c13.x*c13y2*c23.x - 6*c20.x*c21.x*c13.x*c13y2*c22.y - 6*c20.x*c13.x*c21.y*c22.x*c13y2 + 3*c11.y*c20.y*c12.y*c13x2*c23.x + 3*c11.y*c21.x*c12.y*c13x2*c22.y + 3*c11.y*c12.y*c13x2*c21.y*c22.x - 2*c12.x*c20.y*c12y2*c13.x*c23.x - 2*c12.x*c21.x*c12y2*c13.x*c22.y - 2*c12.x*c21.x*c12y2*c22.x*c13.y - 2*c12.x*c12y2*c13.x*c21.y*c22.x - 6*c20.y*c21.x*c13.x*c22.x*c13y2 - c11y2*c12.x*c12.y*c13.x*c23.x + 2*c20.x*c12x2*c12.y*c13.y*c23.y + 6*c20.y*c13x2*c21.y*c22.x*c13.y + 2*c11x2*c11.y*c13.x*c13.y*c23.y + c11x2*c12.x*c12.y*c13.y*c23.y + 2*c12x2*c20.y*c12.y*c13.y*c23.x + 2*c12x2*c21.x*c12.y*c13.y*c22.y + 2*c12x2*c12.y*c21.y*c22.x*c13.y + c21x3*c13y3 + 3*c10x2*c13y3*c23.x - 3*c10y2*c13x3*c23.y + 3*c20x2*c13y3*c23.x + c11y3*c13x2*c23.x - c11x3*c13y2*c23.y - c11.x*c11y2*c13x2*c23.y + c11x2*c11.y*c13y2*c23.x - 3*c10x2*c13.x*c13y2*c23.y + 3*c10y2*c13x2*c13.y*c23.x - c11x2*c12y2*c13.x*c23.y + c11y2*c12x2*c13.y*c23.x - 3*c21x2*c13.x*c21.y*c13y2 - 3*c20x2*c13.x*c13y2*c23.y + 3*c20y2*c13x2*c13.y*c23.x + c11.x*c12.x*c13.x*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c12x3*c13.y*(-2*c20.y*c23.y - 2*c21.y*c22.y) + c10.y*c13x3*(6*c20.y*c23.y + 6*c21.y*c22.y) + c11.y*c12.x*c13x2*(-2*c20.y*c23.y - 2*c21.y*c22.y) + c12x2*c12.y*c13.x*(2*c20.y*c23.y + 2*c21.y*c22.y) + c11.x*c12.y*c13x2*(-4*c20.y*c23.y - 4*c21.y*c22.y) + c10.x*c13x2*c13.y*(-6*c20.y*c23.y - 6*c21.y*c22.y) + c20.x*c13x2*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c21.x*c13x2*c13.y*(6*c20.y*c22.y + 3*c21y2) + c13x3*(-2*c20.y*c21.y*c22.y - c20y2*c23.y - c21.y*(2*c20.y*c22.y + c21y2) - c20.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), -c10.x*c11.x*c12.y*c13.x*c13.y*c22.y + c10.x*c11.y*c12.x*c13.x*c13.y*c22.y + 6*c10.x*c11.y*c12.y*c13.x*c22.x*c13.y - 6*c10.y*c11.x*c12.x*c13.x*c13.y*c22.y - c10.y*c11.x*c12.y*c13.x*c22.x*c13.y + c10.y*c11.y*c12.x*c13.x*c22.x*c13.y + c11.x*c11.y*c12.x*c12.y*c13.x*c22.y - c11.x*c11.y*c12.x*c12.y*c22.x*c13.y + c11.x*c20.x*c12.y*c13.x*c13.y*c22.y + c11.x*c20.y*c12.y*c13.x*c22.x*c13.y + c11.x*c21.x*c12.y*c13.x*c21.y*c13.y - c20.x*c11.y*c12.x*c13.x*c13.y*c22.y - 6*c20.x*c11.y*c12.y*c13.x*c22.x*c13.y - c11.y*c12.x*c20.y*c13.x*c22.x*c13.y - c11.y*c12.x*c21.x*c13.x*c21.y*c13.y - 6*c10.x*c20.x*c22.x*c13y3 - 2*c10.x*c12y3*c13.x*c22.x + 2*c20.x*c12y3*c13.x*c22.x + 2*c10.y*c12x3*c13.y*c22.y - 6*c10.x*c10.y*c13.x*c22.x*c13y2 + 3*c10.x*c11.x*c12.x*c13y2*c22.y - 2*c10.x*c11.x*c12.y*c22.x*c13y2 - 4*c10.x*c11.y*c12.x*c22.x*c13y2 + 3*c10.y*c11.x*c12.x*c22.x*c13y2 + 6*c10.x*c10.y*c13x2*c13.y*c22.y + 6*c10.x*c20.x*c13.x*c13y2*c22.y - 3*c10.x*c11.y*c12.y*c13x2*c22.y + 2*c10.x*c12.x*c12y2*c13.x*c22.y + 2*c10.x*c12.x*c12y2*c22.x*c13.y + 6*c10.x*c20.y*c13.x*c22.x*c13y2 + 6*c10.x*c21.x*c13.x*c21.y*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c22.y + 6*c10.y*c20.x*c13.x*c22.x*c13y2 + 2*c10.y*c11.y*c12.x*c13x2*c22.y - 3*c10.y*c11.y*c12.y*c13x2*c22.x + 2*c10.y*c12.x*c12y2*c13.x*c22.x - 3*c11.x*c20.x*c12.x*c13y2*c22.y + 2*c11.x*c20.x*c12.y*c22.x*c13y2 + c11.x*c11.y*c12y2*c13.x*c22.x - 3*c11.x*c12.x*c20.y*c22.x*c13y2 - 3*c11.x*c12.x*c21.x*c21.y*c13y2 + 4*c20.x*c11.y*c12.x*c22.x*c13y2 - 2*c10.x*c12x2*c12.y*c13.y*c22.y - 6*c10.y*c20.x*c13x2*c13.y*c22.y - 6*c10.y*c20.y*c13x2*c22.x*c13.y - 6*c10.y*c21.x*c13x2*c21.y*c13.y - 2*c10.y*c12x2*c12.y*c13.x*c22.y - 2*c10.y*c12x2*c12.y*c22.x*c13.y - c11.x*c11.y*c12x2*c13.y*c22.y - 2*c11.x*c11y2*c13.x*c22.x*c13.y + 3*c20.x*c11.y*c12.y*c13x2*c22.y - 2*c20.x*c12.x*c12y2*c13.x*c22.y - 2*c20.x*c12.x*c12y2*c22.x*c13.y - 6*c20.x*c20.y*c13.x*c22.x*c13y2 - 6*c20.x*c21.x*c13.x*c21.y*c13y2 + 3*c11.y*c20.y*c12.y*c13x2*c22.x + 3*c11.y*c21.x*c12.y*c13x2*c21.y - 2*c12.x*c20.y*c12y2*c13.x*c22.x - 2*c12.x*c21.x*c12y2*c13.x*c21.y - c11y2*c12.x*c12.y*c13.x*c22.x + 2*c20.x*c12x2*c12.y*c13.y*c22.y - 3*c11.y*c21x2*c12.y*c13.x*c13.y + 6*c20.y*c21.x*c13x2*c21.y*c13.y + 2*c11x2*c11.y*c13.x*c13.y*c22.y + c11x2*c12.x*c12.y*c13.y*c22.y + 2*c12x2*c20.y*c12.y*c22.x*c13.y + 2*c12x2*c21.x*c12.y*c21.y*c13.y - 3*c10.x*c21x2*c13y3 + 3*c20.x*c21x2*c13y3 + 3*c10x2*c22.x*c13y3 - 3*c10y2*c13x3*c22.y + 3*c20x2*c22.x*c13y3 + c21x2*c12y3*c13.x + c11y3*c13x2*c22.x - c11x3*c13y2*c22.y + 3*c10.y*c21x2*c13.x*c13y2 - c11.x*c11y2*c13x2*c22.y + c11.x*c21x2*c12.y*c13y2 + 2*c11.y*c12.x*c21x2*c13y2 + c11x2*c11.y*c22.x*c13y2 - c12.x*c21x2*c12y2*c13.y - 3*c20.y*c21x2*c13.x*c13y2 - 3*c10x2*c13.x*c13y2*c22.y + 3*c10y2*c13x2*c22.x*c13.y - c11x2*c12y2*c13.x*c22.y + c11y2*c12x2*c22.x*c13.y - 3*c20x2*c13.x*c13y2*c22.y + 3*c20y2*c13x2*c22.x*c13.y + c12x2*c12.y*c13.x*(2*c20.y*c22.y + c21y2) + c11.x*c12.x*c13.x*c13.y*(6*c20.y*c22.y + 3*c21y2) + c12x3*c13.y*(-2*c20.y*c22.y - c21y2) + c10.y*c13x3*(6*c20.y*c22.y + 3*c21y2) + c11.y*c12.x*c13x2*(-2*c20.y*c22.y - c21y2) + c11.x*c12.y*c13x2*(-4*c20.y*c22.y - 2*c21y2) + c10.x*c13x2*c13.y*(-6*c20.y*c22.y - 3*c21y2) + c20.x*c13x2*c13.y*(6*c20.y*c22.y + 3*c21y2) + c13x3*(-2*c20.y*c21y2 - c20y2*c22.y - c20.y*(2*c20.y*c22.y + c21y2)), -c10.x*c11.x*c12.y*c13.x*c21.y*c13.y + c10.x*c11.y*c12.x*c13.x*c21.y*c13.y + 6*c10.x*c11.y*c21.x*c12.y*c13.x*c13.y - 6*c10.y*c11.x*c12.x*c13.x*c21.y*c13.y - c10.y*c11.x*c21.x*c12.y*c13.x*c13.y + c10.y*c11.y*c12.x*c21.x*c13.x*c13.y - c11.x*c11.y*c12.x*c21.x*c12.y*c13.y + c11.x*c11.y*c12.x*c12.y*c13.x*c21.y + c11.x*c20.x*c12.y*c13.x*c21.y*c13.y + 6*c11.x*c12.x*c20.y*c13.x*c21.y*c13.y + c11.x*c20.y*c21.x*c12.y*c13.x*c13.y - c20.x*c11.y*c12.x*c13.x*c21.y*c13.y - 6*c20.x*c11.y*c21.x*c12.y*c13.x*c13.y - c11.y*c12.x*c20.y*c21.x*c13.x*c13.y - 6*c10.x*c20.x*c21.x*c13y3 - 2*c10.x*c21.x*c12y3*c13.x + 6*c10.y*c20.y*c13x3*c21.y + 2*c20.x*c21.x*c12y3*c13.x + 2*c10.y*c12x3*c21.y*c13.y - 2*c12x3*c20.y*c21.y*c13.y - 6*c10.x*c10.y*c21.x*c13.x*c13y2 + 3*c10.x*c11.x*c12.x*c21.y*c13y2 - 2*c10.x*c11.x*c21.x*c12.y*c13y2 - 4*c10.x*c11.y*c12.x*c21.x*c13y2 + 3*c10.y*c11.x*c12.x*c21.x*c13y2 + 6*c10.x*c10.y*c13x2*c21.y*c13.y + 6*c10.x*c20.x*c13.x*c21.y*c13y2 - 3*c10.x*c11.y*c12.y*c13x2*c21.y + 2*c10.x*c12.x*c21.x*c12y2*c13.y + 2*c10.x*c12.x*c12y2*c13.x*c21.y + 6*c10.x*c20.y*c21.x*c13.x*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c21.y + 6*c10.y*c20.x*c21.x*c13.x*c13y2 + 2*c10.y*c11.y*c12.x*c13x2*c21.y - 3*c10.y*c11.y*c21.x*c12.y*c13x2 + 2*c10.y*c12.x*c21.x*c12y2*c13.x - 3*c11.x*c20.x*c12.x*c21.y*c13y2 + 2*c11.x*c20.x*c21.x*c12.y*c13y2 + c11.x*c11.y*c21.x*c12y2*c13.x - 3*c11.x*c12.x*c20.y*c21.x*c13y2 + 4*c20.x*c11.y*c12.x*c21.x*c13y2 - 6*c10.x*c20.y*c13x2*c21.y*c13.y - 2*c10.x*c12x2*c12.y*c21.y*c13.y - 6*c10.y*c20.x*c13x2*c21.y*c13.y - 6*c10.y*c20.y*c21.x*c13x2*c13.y - 2*c10.y*c12x2*c21.x*c12.y*c13.y - 2*c10.y*c12x2*c12.y*c13.x*c21.y - c11.x*c11.y*c12x2*c21.y*c13.y - 4*c11.x*c20.y*c12.y*c13x2*c21.y - 2*c11.x*c11y2*c21.x*c13.x*c13.y + 3*c20.x*c11.y*c12.y*c13x2*c21.y - 2*c20.x*c12.x*c21.x*c12y2*c13.y - 2*c20.x*c12.x*c12y2*c13.x*c21.y - 6*c20.x*c20.y*c21.x*c13.x*c13y2 - 2*c11.y*c12.x*c20.y*c13x2*c21.y + 3*c11.y*c20.y*c21.x*c12.y*c13x2 - 2*c12.x*c20.y*c21.x*c12y2*c13.x - c11y2*c12.x*c21.x*c12.y*c13.x + 6*c20.x*c20.y*c13x2*c21.y*c13.y + 2*c20.x*c12x2*c12.y*c21.y*c13.y + 2*c11x2*c11.y*c13.x*c21.y*c13.y + c11x2*c12.x*c12.y*c21.y*c13.y + 2*c12x2*c20.y*c21.x*c12.y*c13.y + 2*c12x2*c20.y*c12.y*c13.x*c21.y + 3*c10x2*c21.x*c13y3 - 3*c10y2*c13x3*c21.y + 3*c20x2*c21.x*c13y3 + c11y3*c21.x*c13x2 - c11x3*c21.y*c13y2 - 3*c20y2*c13x3*c21.y - c11.x*c11y2*c13x2*c21.y + c11x2*c11.y*c21.x*c13y2 - 3*c10x2*c13.x*c21.y*c13y2 + 3*c10y2*c21.x*c13x2*c13.y - c11x2*c12y2*c13.x*c21.y + c11y2*c12x2*c21.x*c13.y - 3*c20x2*c13.x*c21.y*c13y2 + 3*c20y2*c21.x*c13x2*c13.y, c10.x*c10.y*c11.x*c12.y*c13.x*c13.y - c10.x*c10.y*c11.y*c12.x*c13.x*c13.y + c10.x*c11.x*c11.y*c12.x*c12.y*c13.y - c10.y*c11.x*c11.y*c12.x*c12.y*c13.x - c10.x*c11.x*c20.y*c12.y*c13.x*c13.y + 6*c10.x*c20.x*c11.y*c12.y*c13.x*c13.y + c10.x*c11.y*c12.x*c20.y*c13.x*c13.y - c10.y*c11.x*c20.x*c12.y*c13.x*c13.y - 6*c10.y*c11.x*c12.x*c20.y*c13.x*c13.y + c10.y*c20.x*c11.y*c12.x*c13.x*c13.y - c11.x*c20.x*c11.y*c12.x*c12.y*c13.y + c11.x*c11.y*c12.x*c20.y*c12.y*c13.x + c11.x*c20.x*c20.y*c12.y*c13.x*c13.y - c20.x*c11.y*c12.x*c20.y*c13.x*c13.y - 2*c10.x*c20.x*c12y3*c13.x + 2*c10.y*c12x3*c20.y*c13.y - 3*c10.x*c10.y*c11.x*c12.x*c13y2 - 6*c10.x*c10.y*c20.x*c13.x*c13y2 + 3*c10.x*c10.y*c11.y*c12.y*c13x2 - 2*c10.x*c10.y*c12.x*c12y2*c13.x - 2*c10.x*c11.x*c20.x*c12.y*c13y2 - c10.x*c11.x*c11.y*c12y2*c13.x + 3*c10.x*c11.x*c12.x*c20.y*c13y2 - 4*c10.x*c20.x*c11.y*c12.x*c13y2 + 3*c10.y*c11.x*c20.x*c12.x*c13y2 + 6*c10.x*c10.y*c20.y*c13x2*c13.y + 2*c10.x*c10.y*c12x2*c12.y*c13.y + 2*c10.x*c11.x*c11y2*c13.x*c13.y + 2*c10.x*c20.x*c12.x*c12y2*c13.y + 6*c10.x*c20.x*c20.y*c13.x*c13y2 - 3*c10.x*c11.y*c20.y*c12.y*c13x2 + 2*c10.x*c12.x*c20.y*c12y2*c13.x + c10.x*c11y2*c12.x*c12.y*c13.x + c10.y*c11.x*c11.y*c12x2*c13.y + 4*c10.y*c11.x*c20.y*c12.y*c13x2 - 3*c10.y*c20.x*c11.y*c12.y*c13x2 + 2*c10.y*c20.x*c12.x*c12y2*c13.x + 2*c10.y*c11.y*c12.x*c20.y*c13x2 + c11.x*c20.x*c11.y*c12y2*c13.x - 3*c11.x*c20.x*c12.x*c20.y*c13y2 - 2*c10.x*c12x2*c20.y*c12.y*c13.y - 6*c10.y*c20.x*c20.y*c13x2*c13.y - 2*c10.y*c20.x*c12x2*c12.y*c13.y - 2*c10.y*c11x2*c11.y*c13.x*c13.y - c10.y*c11x2*c12.x*c12.y*c13.y - 2*c10.y*c12x2*c20.y*c12.y*c13.x - 2*c11.x*c20.x*c11y2*c13.x*c13.y - c11.x*c11.y*c12x2*c20.y*c13.y + 3*c20.x*c11.y*c20.y*c12.y*c13x2 - 2*c20.x*c12.x*c20.y*c12y2*c13.x - c20.x*c11y2*c12.x*c12.y*c13.x + 3*c10y2*c11.x*c12.x*c13.x*c13.y + 3*c11.x*c12.x*c20y2*c13.x*c13.y + 2*c20.x*c12x2*c20.y*c12.y*c13.y - 3*c10x2*c11.y*c12.y*c13.x*c13.y + 2*c11x2*c11.y*c20.y*c13.x*c13.y + c11x2*c12.x*c20.y*c12.y*c13.y - 3*c20x2*c11.y*c12.y*c13.x*c13.y - c10x3*c13y3 + c10y3*c13x3 + c20x3*c13y3 - c20y3*c13x3 - 3*c10.x*c20x2*c13y3 - c10.x*c11y3*c13x2 + 3*c10x2*c20.x*c13y3 + c10.y*c11x3*c13y2 + 3*c10.y*c20y2*c13x3 + c20.x*c11y3*c13x2 + c10x2*c12y3*c13.x - 3*c10y2*c20.y*c13x3 - c10y2*c12x3*c13.y + c20x2*c12y3*c13.x - c11x3*c20.y*c13y2 - c12x3*c20y2*c13.y - c10.x*c11x2*c11.y*c13y2 + c10.y*c11.x*c11y2*c13x2 - 3*c10.x*c10y2*c13x2*c13.y - c10.x*c11y2*c12x2*c13.y + c10.y*c11x2*c12y2*c13.x - c11.x*c11y2*c20.y*c13x2 + 3*c10x2*c10.y*c13.x*c13y2 + c10x2*c11.x*c12.y*c13y2 + 2*c10x2*c11.y*c12.x*c13y2 - 2*c10y2*c11.x*c12.y*c13x2 - c10y2*c11.y*c12.x*c13x2 + c11x2*c20.x*c11.y*c13y2 - 3*c10.x*c20y2*c13x2*c13.y + 3*c10.y*c20x2*c13.x*c13y2 + c11.x*c20x2*c12.y*c13y2 - 2*c11.x*c20y2*c12.y*c13x2 + c20.x*c11y2*c12x2*c13.y - c11.y*c12.x*c20y2*c13x2 - c10x2*c12.x*c12y2*c13.y - 3*c10x2*c20.y*c13.x*c13y2 + 3*c10y2*c20.x*c13x2*c13.y + c10y2*c12x2*c12.y*c13.x - c11x2*c20.y*c12y2*c13.x + 2*c20x2*c11.y*c12.x*c13y2 + 3*c20.x*c20y2*c13x2*c13.y - c20x2*c12.x*c12y2*c13.y - 3*c20x2*c20.y*c13.x*c13y2 + c12x2*c20y2*c12.y*c13.x ]) roots = poly.rootsInterval(0, 1) for own i, s of roots xRoots = new Polynomial([ c13.x c12.x c11.x c10.x - c20.x - s * c21.x - s * s * c22.x - s * s * s * c23.x ]).roots() yRoots = new Polynomial([ c13.y c12.y c11.y c10.y - c20.y - s * c21.y - s * s * c22.y - s * s * s * c23.y ]).roots() if xRoots.length > 0 and yRoots.length > 0 # IMPORTANT # Tweaking this to be smaller can make it miss intersections. tolerance = 1e-2 for own j, xRoot of xRoots if 0 <= xRoot and xRoot <= 1 for own k, yRoot of yRoots if Math.abs(xRoot - yRoot) < tolerance results.push( c23.multiplyBy(s * s * s).add(c22.multiplyBy(s * s).add(c21.multiplyBy(s).add(c20)))) results
true
### Internal representation of a cubic bezier line segment p1 p4 o o \\ // \\ // \ \ / / \ \ / / \ _ _ / \ __ __ / ° --_____-- ° p2 p3 I/P: p1: First absolute point, the moveto p2: The first point's curve handle p3: The second point's curve handle p4: The second absolute point In context with syntax: M[p1]C[p2] [p3] [p4] ### class CubicBezier constructor: (@p1, @p2, @p3, @p4, @source = @toCurveTo()) -> ### toString: -> "(Cubic bezier: #{@p1},#{@p2},#{@p3},#{@p4})" ### toString: -> "new CubicBezier(#{@p1}, #{@p2}, #{@p3}, #{@p4})" toCurveTo: -> new CurveTo(@p2.x, @p2.y, @p3.x, @p3.y, @p4.x, @p4.y) toSVGPoint: -> @toCurveTo() length: -> # Not that accurate lol @intoLineSegments(4).reduce((a, b) -> a + b.length) beginning: -> @p1 end: -> @p4 nudge: (x, y) -> @p1.nudge(x, y) @p2.nudge(x, y) @p3.nudge(x, y) @p4.nudge(x, y) @ scale: (x, y, origin) -> @p1.scale(x, y, origin) @p2.scale(x, y, origin) @p3.scale(x, y, origin) @p4.scale(x, y, origin) @ rotate: (angle, origin) -> @p1.rotate(angle, origin) @p2.rotate(angle, origin) @p3.rotate(angle, origin) @p4.rotate(angle, origin) @ reverse: -> # Note: this makes it lose its source new CubicBezier @p4, @p3, @p2, @p1 equal: (cbls) -> return false if cbls instanceof LineSegment (((@p1.equal cbls.p1) && (@p2.equal cbls.p2) && (@p3.equal cbls.p3) && (@p4.equal cbls.p4)) || ((@p1.equal cbls.p4) && (@p2.equal cbls.p3) && (@p3.equal cbls.p2) && (@p4.equal cbls.p1))) intersects: (other) -> inter = @intersection(other) inter instanceof Posn or (inter instanceof Array and inter.length > 0) intersection: (other) -> switch other.constructor when LineSegment return @intersectionWithLineSegment(other) when CubicBezier return @intersectionWithCubicBezier(other) xRange: -> @bounds().xr yRange: -> @bounds().yr ends: -> [@p1, @p4] midPoint: -> @splitAt(0.5)[0].p4 bounds: (useCached = false) -> if @boundsCached? and useCached return @boundsCached minx = miny = Infinity maxx = maxy = -Infinity top2x = @p2.x - @p1.x top2y = @p2.y - @p1.y top3x = @p3.x - @p2.x top3y = @p3.y - @p2.y top4x = @p4.x - @p3.x top4y = @p4.y - @p3.y for i in [0..40] d = i / 40 px = @p1.x + d * top2x py = @p1.y + d * top2y qx = @p2.x + d * top3x qy = @p2.y + d * top3y rx = @p3.x + d * top4x ry = @p3.y + d * top4y toqx = qx - px toqy = qy - py torx = rx - qx tory = ry - qy sx = px + d * toqx sy = py + d * toqy tx = qx + d * torx ty = qy + d * tory totx = tx - sx toty = ty - sy x = sx + d * totx y = sy + d * toty minx = Math.min(minx, x) miny = Math.min(miny, y) maxx = Math.max(maxx, x) maxy = Math.max(maxy, y) width = maxx - minx height = maxy - miny # Cache the bounds and return them at the same time @boundsCached = new Bounds(minx, miny, width, height) boundsCached: undefined intoLineSegments: (n) -> # Given n, split the bezier into n consecutive LineSegments, returned in an Array # # I/P: n, number # O/P: [LineSegment, LineSegment, LineSegment...] array segments = [] for m in [0..n] i = 1 / m x = Math.pow((1-i), 3) * @p1.x + 3 * Math.pow((1-i), 2) * i * @p2.x + 3 * (1 - i) * Math.pow(i, 2) * @p3.x + Math.pow(i, 3) * @p4.x y = Math.pow((1-i), 3) * @p1.y + 3 * Math.pow((1-i), 2) * i * @p2.y + 3 * (1 - i) * Math.pow(i, 2) * @p3.y + Math.pow(i, 3) * @p4.y if m % 2 == 0 last = new Posn(x, y) else segments.push new LineSegment(last, new Posn(x, y)) segments.splice 1 splitAt: (t, force = null) -> # Given a float t between 0 and 1, return two CubicBeziers that result from splitting this one at that percentage in. # # I/P: t, number between 0 and 1 # O/P: [CubicBezier, CubicBezier] array # # Uses de Casteljau's algorithm. Really damn good resources: # http://processingjs.nihongoresources.com/bezierinfo/ # http://en.wikipedia.org/wiki/De_Casteljau's_algorithm # # Example, splitting in half: # t = 0.5 # p1: (10,10), p2: (20, 5), p3: (40, 20), p4: (50, 10) # p5: (15, 7.5), p6: (30, 12.5), p7: (45, 15) # p8: (22.5, 10), p9: (37.5, 13.75) # p10: (30, 11.875) # # The split will happen at exactly p10, so the resulting curves will end and start there, respectively. # The resulting curves will be # [new CubicBezier(p1, p5, p8, p10), new CubicBezier(p10, p9, p7, p4)] if typeof t is "number" p5 = new LineSegment(@p1, @p2).posnAtPercent t p6 = new LineSegment(@p2, @p3).posnAtPercent t p7 = new LineSegment(@p3, @p4).posnAtPercent t p8 = new LineSegment(p5, p6).posnAtPercent t p9 = new LineSegment(p6, p7).posnAtPercent t p10 = if force then force else new LineSegment(p8, p9).posnAtPercent t return [new CubicBezier(@p1, p5, p8, p10), new CubicBezier(p10, p9, p7, @p4)] else if t instanceof Posn # Given a single Posn, find its percentage and then split the line on it. return @splitAt(@findPercentageOfPoint(t), t) else if t instanceof Array # Given a list of Posns, we have a bit more work to do. # We need to sort the Posns by their percentage along on the original line. # Then we recur on the line, splitting it on each posn that occurs from 0.0 to 1.0. # We always recur on the second half of the resulting split with # the next Posn in line. # We're going to use the Posns' percentages as keys # with which we'll sort them and split the line on them # one after the other. sortedPosns = {} # This will be the final array of split segments. segments = [] # Find percentage for each posn, save the posn under that percentage. for posn in t percent = @findPercentageOfPoint posn sortedPosns[percent] = posn # Sort the keys - the list of percentages at which posns are available. percentages = Object.keys(sortedPosns).map(parseFloat).sort(sortNumbers) # Start by splitting the entire bezier. tail = @ # For each posn, going in order of percentages... for perc in percentages # Split the tail on that single posn pair = tail.splitAt sortedPosns[perc] # Keep the first half segments.push pair[0] # And "recur" on the second half by redefining tail to be it tail = pair[1] # Don't abandon that last tail! ;) segments.push tail # Shazam return segments findPercentageOfPoint: (posn, tolerance = 1e-3, accumulated = 0.0, nextstep = 0.5) -> # Recursively find the percentage (float from 0 - 1) of given posn on this bezier, within tolerance given. # This works so well. I am so stoked about it. # Basically, this splits the given bezier in half. If the midpoint is within the tolerance of the posn we're looking for, # return the accumulated float. If not, it will recur on either or both of its halves, # adding (0.5 * n / 2) to the accumulator for the one on the right and keeping it the same for the one on the left # where n is the depth of recursion. # # I/P: posn: the Posn we're looking for # [tolerance]: find the value for within this much of the x and y of the given posn. # # Ignore the accumulated and nextstep values, those should start as they're precoded. # # O/P: A float between 0 and 1. split = @splitAt(0.5) a = split[0] b = split[1] # Base case - we've found it! Return the amt accumulated. if a.p4.within(tolerance, posn) or nextstep < 1e-4 return accumulated # Recursion ab = a.bounds() bb = b.bounds() # Both halves might contain the point, if we have a shape that overlaps itself for example. # For this reason we have to actually recur on both the left and right. # When staying with a, however, we don't add to the accumulator because we're not advancing to the second half of the line. # We're simply not making the jump, so we don't count it. But we might make the next smallest jump when we recur on a. if ab.xr.containsInclusive(posn.x, 0.2) and ab.yr.containsInclusive(posn.y, 0.2) ac = a.findPercentageOfPoint(posn, tolerance, accumulated, nextstep / 2) if bb.xr.containsInclusive(posn.x, 0.2) and bb.yr.containsInclusive(posn.y, 0.2) bc = b.findPercentageOfPoint(posn, tolerance, accumulated + nextstep, nextstep / 2) # This is where the recursion bottoms out. Null means it's not on the bezier line within the tolerance. # ############# # IMPORTANT # ############# # This is a compromise right now. Since the intersection algorithm is imperfect, we get as close as we can and # return accumulated if there are no options. NOT null, which it used to be. # All this means is that if a point is given that's a bit off the line the recursion will stop when it can't # get any closer to it. So it does what it can, basically. # # This means you can't just feed any point into this and expect it to ignore you given a bad point. # This also means there is some tolerance to a point being a little bit off, which can happen when calculating # several intersections on one curve. # # It's very accurate this way. Nothing to worry about. Just a note so I don't forget. <3 if ac? then ac else if bc? then bc else accumulated ### Intersection methods ### intersectionWithLineSegment: (l) -> ### Given a LineSegment, lists intersection point(s). I/P: LineSegment O/P: Array of Posns I am a cute sick PI:NAME:<NAME>END_PI i love monodebe and I learn all about the flexible scemless data base Disclaimer: I don't really understand this but it passes my tests. ### min = l.a.min(l.b) max = l.a.max(l.b) results = [] a = @p1.multiplyBy -1 b = @p2.multiplyBy 3 c = @p3.multiplyBy -3 d = a.add(b.add(c.add(@p4))) c3 = new Posn(d.x, d.y) a = @p1.multiplyBy 3 b = @p2.multiplyBy -6 c = @p3.multiplyBy 3 d = a.add(b.add(c)) c2 = new Posn(d.x, d.y) a = @p1.multiplyBy -3 b = @p2.multiplyBy 3 c = a.add b c1 = new Posn(c.x, c.y) c0 = new Posn(@p1.x, @p1.y) n = new Posn(l.a.y - l.b.y, l.b.x - l.a.x) cl = l.a.x * l.b.y - l.b.x * l.a.y roots = new Polynomial([n.dot(c3), n.dot(c2), n.dot(c1), n.dot(c0) + cl]).roots() for i,t of roots if 0 <= t and t <= 1 p5 = @p1.lerp(@p2, t) p6 = @p2.lerp(@p3, t) p7 = @p3.lerp(@p4, t) p8 = p5.lerp(p6, t) p9 = p6.lerp(p7, t) p10 = p8.lerp(p9, t) if l.a.x is l.b.x if (min.y <= p10.y) and (p10.y <= max.y) results.push p10 else if l.a.y is l.b.y if min.x <= p10.x and p10.x <= max.x results.push p10 else if p10.gte(min) and p10.lte(max) results.push p10 results intersectionWithCubicBezier: (other) -> # I don't know. # # I/P: Another CubicBezier # O/P: Array of Posns. # # Source: http://www.kevlindev.com/gui/math/intersection/index.htm#Anchor-intersectBezie-45477 results = [] a = @p1.multiplyBy(-1) b = @p2.multiplyBy(3) c = @p3.multiplyBy(-3) d = a.add(b.add(c.add(@p4))) c13 = new Posn(d.x, d.y) a = @p1.multiplyBy(3) b = @p2.multiplyBy(-6) c = @p3.multiplyBy(3) d = a.add(b.add(c)) c12 = new Posn(d.x, d.y) a = @p1.multiplyBy(-3) b = @p2.multiplyBy(3) c = a.add(b) c11 = new Posn(c.x, c.y) c10 = new Posn(@p1.x, @p1.y) a = other.p1.multiplyBy(-1) b = other.p2.multiplyBy(3) c = other.p3.multiplyBy(-3) d = a.add(b.add(c.add(other.p4))) c23 = new Posn(d.x, d.y) a = other.p1.multiplyBy(3) b = other.p2.multiplyBy(-6) c = other.p3.multiplyBy(3) d = a.add(b.add(c)) c22 = new Posn(d.x, d.y) a = other.p1.multiplyBy(-3) b = other.p2.multiplyBy(3) c = a.add(b) c21 = new Posn(c.x, c.y) c20 = new Posn(other.p1.x, other.p1.y) c10x2 = c10.x * c10.x c10x3 = c10.x * c10.x * c10.x c10y2 = c10.y * c10.y c10y3 = c10.y * c10.y * c10.y c11x2 = c11.x * c11.x c11x3 = c11.x * c11.x * c11.x c11y2 = c11.y * c11.y c11y3 = c11.y * c11.y * c11.y c12x2 = c12.x * c12.x c12x3 = c12.x * c12.x * c12.x c12y2 = c12.y * c12.y c12y3 = c12.y * c12.y * c12.y c13x2 = c13.x * c13.x c13x3 = c13.x * c13.x * c13.x c13y2 = c13.y * c13.y c13y3 = c13.y * c13.y * c13.y c20x2 = c20.x * c20.x c20x3 = c20.x * c20.x * c20.x c20y2 = c20.y * c20.y c20y3 = c20.y * c20.y * c20.y c21x2 = c21.x * c21.x c21x3 = c21.x * c21.x * c21.x c21y2 = c21.y * c21.y c22x2 = c22.x * c22.x c22x3 = c22.x * c22.x * c22.x c22y2 = c22.y * c22.y c23x2 = c23.x * c23.x c23x3 = c23.x * c23.x * c23.x c23y2 = c23.y * c23.y c23y3 = c23.y * c23.y * c23.y poly = new Polynomial([ -c13x3*c23y3 + c13y3*c23x3 - 3*c13.x*c13y2*c23x2*c23.y + 3*c13x2*c13.y*c23.x*c23y2, -6*c13.x*c22.x*c13y2*c23.x*c23.y + 6*c13x2*c13.y*c22.y*c23.x*c23.y + 3*c22.x*c13y3*c23x2 - 3*c13x3*c22.y*c23y2 - 3*c13.x*c13y2*c22.y*c23x2 + 3*c13x2*c22.x*c13.y*c23y2, -6*c21.x*c13.x*c13y2*c23.x*c23.y - 6*c13.x*c22.x*c13y2*c22.y*c23.x + 6*c13x2*c22.x*c13.y*c22.y*c23.y + 3*c21.x*c13y3*c23x2 + 3*c22x2*c13y3*c23.x + 3*c21.x*c13x2*c13.y*c23y2 - 3*c13.x*c21.y*c13y2*c23x2 - 3*c13.x*c22x2*c13y2*c23.y + c13x2*c13.y*c23.x*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-c21.y*c23y2 - 2*c22y2*c23.y - c23.y*(2*c21.y*c23.y + c22y2)), c11.x*c12.y*c13.x*c13.y*c23.x*c23.y - c11.y*c12.x*c13.x*c13.y*c23.x*c23.y + 6*c21.x*c22.x*c13y3*c23.x + 3*c11.x*c12.x*c13.x*c13.y*c23y2 + 6*c10.x*c13.x*c13y2*c23.x*c23.y - 3*c11.x*c12.x*c13y2*c23.x*c23.y - 3*c11.y*c12.y*c13.x*c13.y*c23x2 - 6*c10.y*c13x2*c13.y*c23.x*c23.y - 6*c20.x*c13.x*c13y2*c23.x*c23.y + 3*c11.y*c12.y*c13x2*c23.x*c23.y - 2*c12.x*c12y2*c13.x*c23.x*c23.y - 6*c21.x*c13.x*c22.x*c13y2*c23.y - 6*c21.x*c13.x*c13y2*c22.y*c23.x - 6*c13.x*c21.y*c22.x*c13y2*c23.x + 6*c21.x*c13x2*c13.y*c22.y*c23.y + 2*c12x2*c12.y*c13.y*c23.x*c23.y + c22x3*c13y3 - 3*c10.x*c13y3*c23x2 + 3*c10.y*c13x3*c23y2 + 3*c20.x*c13y3*c23x2 + c12y3*c13.x*c23x2 - c12x3*c13.y*c23y2 - 3*c10.x*c13x2*c13.y*c23y2 + 3*c10.y*c13.x*c13y2*c23x2 - 2*c11.x*c12.y*c13x2*c23y2 + c11.x*c12.y*c13y2*c23x2 - c11.y*c12.x*c13x2*c23y2 + 2*c11.y*c12.x*c13y2*c23x2 + 3*c20.x*c13x2*c13.y*c23y2 - c12.x*c12y2*c13.y*c23x2 - 3*c20.y*c13.x*c13y2*c23x2 + c12x2*c12.y*c13.x*c23y2 - 3*c13.x*c22x2*c13y2*c22.y + c13x2*c13.y*c23.x*(6*c20.y*c23.y + 6*c21.y*c22.y) + c13x2*c22.x*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c21.y*c22.y*c23.y - c20.y*c23y2 - c22.y*(2*c21.y*c23.y + c22y2) - c23.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), 6*c11.x*c12.x*c13.x*c13.y*c22.y*c23.y + c11.x*c12.y*c13.x*c22.x*c13.y*c23.y + c11.x*c12.y*c13.x*c13.y*c22.y*c23.x - c11.y*c12.x*c13.x*c22.x*c13.y*c23.y - c11.y*c12.x*c13.x*c13.y*c22.y*c23.x - 6*c11.y*c12.y*c13.x*c22.x*c13.y*c23.x - 6*c10.x*c22.x*c13y3*c23.x + 6*c20.x*c22.x*c13y3*c23.x + 6*c10.y*c13x3*c22.y*c23.y + 2*c12y3*c13.x*c22.x*c23.x - 2*c12x3*c13.y*c22.y*c23.y + 6*c10.x*c13.x*c22.x*c13y2*c23.y + 6*c10.x*c13.x*c13y2*c22.y*c23.x + 6*c10.y*c13.x*c22.x*c13y2*c23.x - 3*c11.x*c12.x*c22.x*c13y2*c23.y - 3*c11.x*c12.x*c13y2*c22.y*c23.x + 2*c11.x*c12.y*c22.x*c13y2*c23.x + 4*c11.y*c12.x*c22.x*c13y2*c23.x - 6*c10.x*c13x2*c13.y*c22.y*c23.y - 6*c10.y*c13x2*c22.x*c13.y*c23.y - 6*c10.y*c13x2*c13.y*c22.y*c23.x - 4*c11.x*c12.y*c13x2*c22.y*c23.y - 6*c20.x*c13.x*c22.x*c13y2*c23.y - 6*c20.x*c13.x*c13y2*c22.y*c23.x - 2*c11.y*c12.x*c13x2*c22.y*c23.y + 3*c11.y*c12.y*c13x2*c22.x*c23.y + 3*c11.y*c12.y*c13x2*c22.y*c23.x - 2*c12.x*c12y2*c13.x*c22.x*c23.y - 2*c12.x*c12y2*c13.x*c22.y*c23.x - 2*c12.x*c12y2*c22.x*c13.y*c23.x - 6*c20.y*c13.x*c22.x*c13y2*c23.x - 6*c21.x*c13.x*c21.y*c13y2*c23.x - 6*c21.x*c13.x*c22.x*c13y2*c22.y + 6*c20.x*c13x2*c13.y*c22.y*c23.y + 2*c12x2*c12.y*c13.x*c22.y*c23.y + 2*c12x2*c12.y*c22.x*c13.y*c23.y + 2*c12x2*c12.y*c13.y*c22.y*c23.x + 3*c21.x*c22x2*c13y3 + 3*c21x2*c13y3*c23.x - 3*c13.x*c21.y*c22x2*c13y2 - 3*c21x2*c13.x*c13y2*c23.y + c13x2*c22.x*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c13x2*c13.y*c23.x*(6*c20.y*c22.y + 3*c21y2) + c21.x*c13x2*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c20.y*c22.y*c23.y - c23.y*(2*c20.y*c22.y + c21y2) - c21.y*(2*c21.y*c23.y + c22y2) - c22.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), c11.x*c21.x*c12.y*c13.x*c13.y*c23.y + c11.x*c12.y*c13.x*c21.y*c13.y*c23.x + c11.x*c12.y*c13.x*c22.x*c13.y*c22.y - c11.y*c12.x*c21.x*c13.x*c13.y*c23.y - c11.y*c12.x*c13.x*c21.y*c13.y*c23.x - c11.y*c12.x*c13.x*c22.x*c13.y*c22.y - 6*c11.y*c21.x*c12.y*c13.x*c13.y*c23.x - 6*c10.x*c21.x*c13y3*c23.x + 6*c20.x*c21.x*c13y3*c23.x + 2*c21.x*c12y3*c13.x*c23.x + 6*c10.x*c21.x*c13.x*c13y2*c23.y + 6*c10.x*c13.x*c21.y*c13y2*c23.x + 6*c10.x*c13.x*c22.x*c13y2*c22.y + 6*c10.y*c21.x*c13.x*c13y2*c23.x - 3*c11.x*c12.x*c21.x*c13y2*c23.y - 3*c11.x*c12.x*c21.y*c13y2*c23.x - 3*c11.x*c12.x*c22.x*c13y2*c22.y + 2*c11.x*c21.x*c12.y*c13y2*c23.x + 4*c11.y*c12.x*c21.x*c13y2*c23.x - 6*c10.y*c21.x*c13x2*c13.y*c23.y - 6*c10.y*c13x2*c21.y*c13.y*c23.x - 6*c10.y*c13x2*c22.x*c13.y*c22.y - 6*c20.x*c21.x*c13.x*c13y2*c23.y - 6*c20.x*c13.x*c21.y*c13y2*c23.x - 6*c20.x*c13.x*c22.x*c13y2*c22.y + 3*c11.y*c21.x*c12.y*c13x2*c23.y - 3*c11.y*c12.y*c13.x*c22x2*c13.y + 3*c11.y*c12.y*c13x2*c21.y*c23.x + 3*c11.y*c12.y*c13x2*c22.x*c22.y - 2*c12.x*c21.x*c12y2*c13.x*c23.y - 2*c12.x*c21.x*c12y2*c13.y*c23.x - 2*c12.x*c12y2*c13.x*c21.y*c23.x - 2*c12.x*c12y2*c13.x*c22.x*c22.y - 6*c20.y*c21.x*c13.x*c13y2*c23.x - 6*c21.x*c13.x*c21.y*c22.x*c13y2 + 6*c20.y*c13x2*c21.y*c13.y*c23.x + 2*c12x2*c21.x*c12.y*c13.y*c23.y + 2*c12x2*c12.y*c21.y*c13.y*c23.x + 2*c12x2*c12.y*c22.x*c13.y*c22.y - 3*c10.x*c22x2*c13y3 + 3*c20.x*c22x2*c13y3 + 3*c21x2*c22.x*c13y3 + c12y3*c13.x*c22x2 + 3*c10.y*c13.x*c22x2*c13y2 + c11.x*c12.y*c22x2*c13y2 + 2*c11.y*c12.x*c22x2*c13y2 - c12.x*c12y2*c22x2*c13.y - 3*c20.y*c13.x*c22x2*c13y2 - 3*c21x2*c13.x*c13y2*c22.y + c12x2*c12.y*c13.x*(2*c21.y*c23.y + c22y2) + c11.x*c12.x*c13.x*c13.y*(6*c21.y*c23.y + 3*c22y2) + c21.x*c13x2*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c12x3*c13.y*(-2*c21.y*c23.y - c22y2) + c10.y*c13x3*(6*c21.y*c23.y + 3*c22y2) + c11.y*c12.x*c13x2*(-2*c21.y*c23.y - c22y2) + c11.x*c12.y*c13x2*(-4*c21.y*c23.y - 2*c22y2) + c10.x*c13x2*c13.y*(-6*c21.y*c23.y - 3*c22y2) + c13x2*c22.x*c13.y*(6*c20.y*c22.y + 3*c21y2) + c20.x*c13x2*c13.y*(6*c21.y*c23.y + 3*c22y2) + c13x3*(-2*c20.y*c21.y*c23.y - c22.y*(2*c20.y*c22.y + c21y2) - c20.y*(2*c21.y*c23.y + c22y2) - c21.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), -c10.x*c11.x*c12.y*c13.x*c13.y*c23.y + c10.x*c11.y*c12.x*c13.x*c13.y*c23.y + 6*c10.x*c11.y*c12.y*c13.x*c13.y*c23.x - 6*c10.y*c11.x*c12.x*c13.x*c13.y*c23.y - c10.y*c11.x*c12.y*c13.x*c13.y*c23.x + c10.y*c11.y*c12.x*c13.x*c13.y*c23.x + c11.x*c11.y*c12.x*c12.y*c13.x*c23.y - c11.x*c11.y*c12.x*c12.y*c13.y*c23.x + c11.x*c20.x*c12.y*c13.x*c13.y*c23.y + c11.x*c20.y*c12.y*c13.x*c13.y*c23.x + c11.x*c21.x*c12.y*c13.x*c13.y*c22.y + c11.x*c12.y*c13.x*c21.y*c22.x*c13.y - c20.x*c11.y*c12.x*c13.x*c13.y*c23.y - 6*c20.x*c11.y*c12.y*c13.x*c13.y*c23.x - c11.y*c12.x*c20.y*c13.x*c13.y*c23.x - c11.y*c12.x*c21.x*c13.x*c13.y*c22.y - c11.y*c12.x*c13.x*c21.y*c22.x*c13.y - 6*c11.y*c21.x*c12.y*c13.x*c22.x*c13.y - 6*c10.x*c20.x*c13y3*c23.x - 6*c10.x*c21.x*c22.x*c13y3 - 2*c10.x*c12y3*c13.x*c23.x + 6*c20.x*c21.x*c22.x*c13y3 + 2*c20.x*c12y3*c13.x*c23.x + 2*c21.x*c12y3*c13.x*c22.x + 2*c10.y*c12x3*c13.y*c23.y - 6*c10.x*c10.y*c13.x*c13y2*c23.x + 3*c10.x*c11.x*c12.x*c13y2*c23.y - 2*c10.x*c11.x*c12.y*c13y2*c23.x - 4*c10.x*c11.y*c12.x*c13y2*c23.x + 3*c10.y*c11.x*c12.x*c13y2*c23.x + 6*c10.x*c10.y*c13x2*c13.y*c23.y + 6*c10.x*c20.x*c13.x*c13y2*c23.y - 3*c10.x*c11.y*c12.y*c13x2*c23.y + 2*c10.x*c12.x*c12y2*c13.x*c23.y + 2*c10.x*c12.x*c12y2*c13.y*c23.x + 6*c10.x*c20.y*c13.x*c13y2*c23.x + 6*c10.x*c21.x*c13.x*c13y2*c22.y + 6*c10.x*c13.x*c21.y*c22.x*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c23.y + 6*c10.y*c20.x*c13.x*c13y2*c23.x + 2*c10.y*c11.y*c12.x*c13x2*c23.y - 3*c10.y*c11.y*c12.y*c13x2*c23.x + 2*c10.y*c12.x*c12y2*c13.x*c23.x + 6*c10.y*c21.x*c13.x*c22.x*c13y2 - 3*c11.x*c20.x*c12.x*c13y2*c23.y + 2*c11.x*c20.x*c12.y*c13y2*c23.x + c11.x*c11.y*c12y2*c13.x*c23.x - 3*c11.x*c12.x*c20.y*c13y2*c23.x - 3*c11.x*c12.x*c21.x*c13y2*c22.y - 3*c11.x*c12.x*c21.y*c22.x*c13y2 + 2*c11.x*c21.x*c12.y*c22.x*c13y2 + 4*c20.x*c11.y*c12.x*c13y2*c23.x + 4*c11.y*c12.x*c21.x*c22.x*c13y2 - 2*c10.x*c12x2*c12.y*c13.y*c23.y - 6*c10.y*c20.x*c13x2*c13.y*c23.y - 6*c10.y*c20.y*c13x2*c13.y*c23.x - 6*c10.y*c21.x*c13x2*c13.y*c22.y - 2*c10.y*c12x2*c12.y*c13.x*c23.y - 2*c10.y*c12x2*c12.y*c13.y*c23.x - 6*c10.y*c13x2*c21.y*c22.x*c13.y - c11.x*c11.y*c12x2*c13.y*c23.y - 2*c11.x*c11y2*c13.x*c13.y*c23.x + 3*c20.x*c11.y*c12.y*c13x2*c23.y - 2*c20.x*c12.x*c12y2*c13.x*c23.y - 2*c20.x*c12.x*c12y2*c13.y*c23.x - 6*c20.x*c20.y*c13.x*c13y2*c23.x - 6*c20.x*c21.x*c13.x*c13y2*c22.y - 6*c20.x*c13.x*c21.y*c22.x*c13y2 + 3*c11.y*c20.y*c12.y*c13x2*c23.x + 3*c11.y*c21.x*c12.y*c13x2*c22.y + 3*c11.y*c12.y*c13x2*c21.y*c22.x - 2*c12.x*c20.y*c12y2*c13.x*c23.x - 2*c12.x*c21.x*c12y2*c13.x*c22.y - 2*c12.x*c21.x*c12y2*c22.x*c13.y - 2*c12.x*c12y2*c13.x*c21.y*c22.x - 6*c20.y*c21.x*c13.x*c22.x*c13y2 - c11y2*c12.x*c12.y*c13.x*c23.x + 2*c20.x*c12x2*c12.y*c13.y*c23.y + 6*c20.y*c13x2*c21.y*c22.x*c13.y + 2*c11x2*c11.y*c13.x*c13.y*c23.y + c11x2*c12.x*c12.y*c13.y*c23.y + 2*c12x2*c20.y*c12.y*c13.y*c23.x + 2*c12x2*c21.x*c12.y*c13.y*c22.y + 2*c12x2*c12.y*c21.y*c22.x*c13.y + c21x3*c13y3 + 3*c10x2*c13y3*c23.x - 3*c10y2*c13x3*c23.y + 3*c20x2*c13y3*c23.x + c11y3*c13x2*c23.x - c11x3*c13y2*c23.y - c11.x*c11y2*c13x2*c23.y + c11x2*c11.y*c13y2*c23.x - 3*c10x2*c13.x*c13y2*c23.y + 3*c10y2*c13x2*c13.y*c23.x - c11x2*c12y2*c13.x*c23.y + c11y2*c12x2*c13.y*c23.x - 3*c21x2*c13.x*c21.y*c13y2 - 3*c20x2*c13.x*c13y2*c23.y + 3*c20y2*c13x2*c13.y*c23.x + c11.x*c12.x*c13.x*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c12x3*c13.y*(-2*c20.y*c23.y - 2*c21.y*c22.y) + c10.y*c13x3*(6*c20.y*c23.y + 6*c21.y*c22.y) + c11.y*c12.x*c13x2*(-2*c20.y*c23.y - 2*c21.y*c22.y) + c12x2*c12.y*c13.x*(2*c20.y*c23.y + 2*c21.y*c22.y) + c11.x*c12.y*c13x2*(-4*c20.y*c23.y - 4*c21.y*c22.y) + c10.x*c13x2*c13.y*(-6*c20.y*c23.y - 6*c21.y*c22.y) + c20.x*c13x2*c13.y*(6*c20.y*c23.y + 6*c21.y*c22.y) + c21.x*c13x2*c13.y*(6*c20.y*c22.y + 3*c21y2) + c13x3*(-2*c20.y*c21.y*c22.y - c20y2*c23.y - c21.y*(2*c20.y*c22.y + c21y2) - c20.y*(2*c20.y*c23.y + 2*c21.y*c22.y)), -c10.x*c11.x*c12.y*c13.x*c13.y*c22.y + c10.x*c11.y*c12.x*c13.x*c13.y*c22.y + 6*c10.x*c11.y*c12.y*c13.x*c22.x*c13.y - 6*c10.y*c11.x*c12.x*c13.x*c13.y*c22.y - c10.y*c11.x*c12.y*c13.x*c22.x*c13.y + c10.y*c11.y*c12.x*c13.x*c22.x*c13.y + c11.x*c11.y*c12.x*c12.y*c13.x*c22.y - c11.x*c11.y*c12.x*c12.y*c22.x*c13.y + c11.x*c20.x*c12.y*c13.x*c13.y*c22.y + c11.x*c20.y*c12.y*c13.x*c22.x*c13.y + c11.x*c21.x*c12.y*c13.x*c21.y*c13.y - c20.x*c11.y*c12.x*c13.x*c13.y*c22.y - 6*c20.x*c11.y*c12.y*c13.x*c22.x*c13.y - c11.y*c12.x*c20.y*c13.x*c22.x*c13.y - c11.y*c12.x*c21.x*c13.x*c21.y*c13.y - 6*c10.x*c20.x*c22.x*c13y3 - 2*c10.x*c12y3*c13.x*c22.x + 2*c20.x*c12y3*c13.x*c22.x + 2*c10.y*c12x3*c13.y*c22.y - 6*c10.x*c10.y*c13.x*c22.x*c13y2 + 3*c10.x*c11.x*c12.x*c13y2*c22.y - 2*c10.x*c11.x*c12.y*c22.x*c13y2 - 4*c10.x*c11.y*c12.x*c22.x*c13y2 + 3*c10.y*c11.x*c12.x*c22.x*c13y2 + 6*c10.x*c10.y*c13x2*c13.y*c22.y + 6*c10.x*c20.x*c13.x*c13y2*c22.y - 3*c10.x*c11.y*c12.y*c13x2*c22.y + 2*c10.x*c12.x*c12y2*c13.x*c22.y + 2*c10.x*c12.x*c12y2*c22.x*c13.y + 6*c10.x*c20.y*c13.x*c22.x*c13y2 + 6*c10.x*c21.x*c13.x*c21.y*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c22.y + 6*c10.y*c20.x*c13.x*c22.x*c13y2 + 2*c10.y*c11.y*c12.x*c13x2*c22.y - 3*c10.y*c11.y*c12.y*c13x2*c22.x + 2*c10.y*c12.x*c12y2*c13.x*c22.x - 3*c11.x*c20.x*c12.x*c13y2*c22.y + 2*c11.x*c20.x*c12.y*c22.x*c13y2 + c11.x*c11.y*c12y2*c13.x*c22.x - 3*c11.x*c12.x*c20.y*c22.x*c13y2 - 3*c11.x*c12.x*c21.x*c21.y*c13y2 + 4*c20.x*c11.y*c12.x*c22.x*c13y2 - 2*c10.x*c12x2*c12.y*c13.y*c22.y - 6*c10.y*c20.x*c13x2*c13.y*c22.y - 6*c10.y*c20.y*c13x2*c22.x*c13.y - 6*c10.y*c21.x*c13x2*c21.y*c13.y - 2*c10.y*c12x2*c12.y*c13.x*c22.y - 2*c10.y*c12x2*c12.y*c22.x*c13.y - c11.x*c11.y*c12x2*c13.y*c22.y - 2*c11.x*c11y2*c13.x*c22.x*c13.y + 3*c20.x*c11.y*c12.y*c13x2*c22.y - 2*c20.x*c12.x*c12y2*c13.x*c22.y - 2*c20.x*c12.x*c12y2*c22.x*c13.y - 6*c20.x*c20.y*c13.x*c22.x*c13y2 - 6*c20.x*c21.x*c13.x*c21.y*c13y2 + 3*c11.y*c20.y*c12.y*c13x2*c22.x + 3*c11.y*c21.x*c12.y*c13x2*c21.y - 2*c12.x*c20.y*c12y2*c13.x*c22.x - 2*c12.x*c21.x*c12y2*c13.x*c21.y - c11y2*c12.x*c12.y*c13.x*c22.x + 2*c20.x*c12x2*c12.y*c13.y*c22.y - 3*c11.y*c21x2*c12.y*c13.x*c13.y + 6*c20.y*c21.x*c13x2*c21.y*c13.y + 2*c11x2*c11.y*c13.x*c13.y*c22.y + c11x2*c12.x*c12.y*c13.y*c22.y + 2*c12x2*c20.y*c12.y*c22.x*c13.y + 2*c12x2*c21.x*c12.y*c21.y*c13.y - 3*c10.x*c21x2*c13y3 + 3*c20.x*c21x2*c13y3 + 3*c10x2*c22.x*c13y3 - 3*c10y2*c13x3*c22.y + 3*c20x2*c22.x*c13y3 + c21x2*c12y3*c13.x + c11y3*c13x2*c22.x - c11x3*c13y2*c22.y + 3*c10.y*c21x2*c13.x*c13y2 - c11.x*c11y2*c13x2*c22.y + c11.x*c21x2*c12.y*c13y2 + 2*c11.y*c12.x*c21x2*c13y2 + c11x2*c11.y*c22.x*c13y2 - c12.x*c21x2*c12y2*c13.y - 3*c20.y*c21x2*c13.x*c13y2 - 3*c10x2*c13.x*c13y2*c22.y + 3*c10y2*c13x2*c22.x*c13.y - c11x2*c12y2*c13.x*c22.y + c11y2*c12x2*c22.x*c13.y - 3*c20x2*c13.x*c13y2*c22.y + 3*c20y2*c13x2*c22.x*c13.y + c12x2*c12.y*c13.x*(2*c20.y*c22.y + c21y2) + c11.x*c12.x*c13.x*c13.y*(6*c20.y*c22.y + 3*c21y2) + c12x3*c13.y*(-2*c20.y*c22.y - c21y2) + c10.y*c13x3*(6*c20.y*c22.y + 3*c21y2) + c11.y*c12.x*c13x2*(-2*c20.y*c22.y - c21y2) + c11.x*c12.y*c13x2*(-4*c20.y*c22.y - 2*c21y2) + c10.x*c13x2*c13.y*(-6*c20.y*c22.y - 3*c21y2) + c20.x*c13x2*c13.y*(6*c20.y*c22.y + 3*c21y2) + c13x3*(-2*c20.y*c21y2 - c20y2*c22.y - c20.y*(2*c20.y*c22.y + c21y2)), -c10.x*c11.x*c12.y*c13.x*c21.y*c13.y + c10.x*c11.y*c12.x*c13.x*c21.y*c13.y + 6*c10.x*c11.y*c21.x*c12.y*c13.x*c13.y - 6*c10.y*c11.x*c12.x*c13.x*c21.y*c13.y - c10.y*c11.x*c21.x*c12.y*c13.x*c13.y + c10.y*c11.y*c12.x*c21.x*c13.x*c13.y - c11.x*c11.y*c12.x*c21.x*c12.y*c13.y + c11.x*c11.y*c12.x*c12.y*c13.x*c21.y + c11.x*c20.x*c12.y*c13.x*c21.y*c13.y + 6*c11.x*c12.x*c20.y*c13.x*c21.y*c13.y + c11.x*c20.y*c21.x*c12.y*c13.x*c13.y - c20.x*c11.y*c12.x*c13.x*c21.y*c13.y - 6*c20.x*c11.y*c21.x*c12.y*c13.x*c13.y - c11.y*c12.x*c20.y*c21.x*c13.x*c13.y - 6*c10.x*c20.x*c21.x*c13y3 - 2*c10.x*c21.x*c12y3*c13.x + 6*c10.y*c20.y*c13x3*c21.y + 2*c20.x*c21.x*c12y3*c13.x + 2*c10.y*c12x3*c21.y*c13.y - 2*c12x3*c20.y*c21.y*c13.y - 6*c10.x*c10.y*c21.x*c13.x*c13y2 + 3*c10.x*c11.x*c12.x*c21.y*c13y2 - 2*c10.x*c11.x*c21.x*c12.y*c13y2 - 4*c10.x*c11.y*c12.x*c21.x*c13y2 + 3*c10.y*c11.x*c12.x*c21.x*c13y2 + 6*c10.x*c10.y*c13x2*c21.y*c13.y + 6*c10.x*c20.x*c13.x*c21.y*c13y2 - 3*c10.x*c11.y*c12.y*c13x2*c21.y + 2*c10.x*c12.x*c21.x*c12y2*c13.y + 2*c10.x*c12.x*c12y2*c13.x*c21.y + 6*c10.x*c20.y*c21.x*c13.x*c13y2 + 4*c10.y*c11.x*c12.y*c13x2*c21.y + 6*c10.y*c20.x*c21.x*c13.x*c13y2 + 2*c10.y*c11.y*c12.x*c13x2*c21.y - 3*c10.y*c11.y*c21.x*c12.y*c13x2 + 2*c10.y*c12.x*c21.x*c12y2*c13.x - 3*c11.x*c20.x*c12.x*c21.y*c13y2 + 2*c11.x*c20.x*c21.x*c12.y*c13y2 + c11.x*c11.y*c21.x*c12y2*c13.x - 3*c11.x*c12.x*c20.y*c21.x*c13y2 + 4*c20.x*c11.y*c12.x*c21.x*c13y2 - 6*c10.x*c20.y*c13x2*c21.y*c13.y - 2*c10.x*c12x2*c12.y*c21.y*c13.y - 6*c10.y*c20.x*c13x2*c21.y*c13.y - 6*c10.y*c20.y*c21.x*c13x2*c13.y - 2*c10.y*c12x2*c21.x*c12.y*c13.y - 2*c10.y*c12x2*c12.y*c13.x*c21.y - c11.x*c11.y*c12x2*c21.y*c13.y - 4*c11.x*c20.y*c12.y*c13x2*c21.y - 2*c11.x*c11y2*c21.x*c13.x*c13.y + 3*c20.x*c11.y*c12.y*c13x2*c21.y - 2*c20.x*c12.x*c21.x*c12y2*c13.y - 2*c20.x*c12.x*c12y2*c13.x*c21.y - 6*c20.x*c20.y*c21.x*c13.x*c13y2 - 2*c11.y*c12.x*c20.y*c13x2*c21.y + 3*c11.y*c20.y*c21.x*c12.y*c13x2 - 2*c12.x*c20.y*c21.x*c12y2*c13.x - c11y2*c12.x*c21.x*c12.y*c13.x + 6*c20.x*c20.y*c13x2*c21.y*c13.y + 2*c20.x*c12x2*c12.y*c21.y*c13.y + 2*c11x2*c11.y*c13.x*c21.y*c13.y + c11x2*c12.x*c12.y*c21.y*c13.y + 2*c12x2*c20.y*c21.x*c12.y*c13.y + 2*c12x2*c20.y*c12.y*c13.x*c21.y + 3*c10x2*c21.x*c13y3 - 3*c10y2*c13x3*c21.y + 3*c20x2*c21.x*c13y3 + c11y3*c21.x*c13x2 - c11x3*c21.y*c13y2 - 3*c20y2*c13x3*c21.y - c11.x*c11y2*c13x2*c21.y + c11x2*c11.y*c21.x*c13y2 - 3*c10x2*c13.x*c21.y*c13y2 + 3*c10y2*c21.x*c13x2*c13.y - c11x2*c12y2*c13.x*c21.y + c11y2*c12x2*c21.x*c13.y - 3*c20x2*c13.x*c21.y*c13y2 + 3*c20y2*c21.x*c13x2*c13.y, c10.x*c10.y*c11.x*c12.y*c13.x*c13.y - c10.x*c10.y*c11.y*c12.x*c13.x*c13.y + c10.x*c11.x*c11.y*c12.x*c12.y*c13.y - c10.y*c11.x*c11.y*c12.x*c12.y*c13.x - c10.x*c11.x*c20.y*c12.y*c13.x*c13.y + 6*c10.x*c20.x*c11.y*c12.y*c13.x*c13.y + c10.x*c11.y*c12.x*c20.y*c13.x*c13.y - c10.y*c11.x*c20.x*c12.y*c13.x*c13.y - 6*c10.y*c11.x*c12.x*c20.y*c13.x*c13.y + c10.y*c20.x*c11.y*c12.x*c13.x*c13.y - c11.x*c20.x*c11.y*c12.x*c12.y*c13.y + c11.x*c11.y*c12.x*c20.y*c12.y*c13.x + c11.x*c20.x*c20.y*c12.y*c13.x*c13.y - c20.x*c11.y*c12.x*c20.y*c13.x*c13.y - 2*c10.x*c20.x*c12y3*c13.x + 2*c10.y*c12x3*c20.y*c13.y - 3*c10.x*c10.y*c11.x*c12.x*c13y2 - 6*c10.x*c10.y*c20.x*c13.x*c13y2 + 3*c10.x*c10.y*c11.y*c12.y*c13x2 - 2*c10.x*c10.y*c12.x*c12y2*c13.x - 2*c10.x*c11.x*c20.x*c12.y*c13y2 - c10.x*c11.x*c11.y*c12y2*c13.x + 3*c10.x*c11.x*c12.x*c20.y*c13y2 - 4*c10.x*c20.x*c11.y*c12.x*c13y2 + 3*c10.y*c11.x*c20.x*c12.x*c13y2 + 6*c10.x*c10.y*c20.y*c13x2*c13.y + 2*c10.x*c10.y*c12x2*c12.y*c13.y + 2*c10.x*c11.x*c11y2*c13.x*c13.y + 2*c10.x*c20.x*c12.x*c12y2*c13.y + 6*c10.x*c20.x*c20.y*c13.x*c13y2 - 3*c10.x*c11.y*c20.y*c12.y*c13x2 + 2*c10.x*c12.x*c20.y*c12y2*c13.x + c10.x*c11y2*c12.x*c12.y*c13.x + c10.y*c11.x*c11.y*c12x2*c13.y + 4*c10.y*c11.x*c20.y*c12.y*c13x2 - 3*c10.y*c20.x*c11.y*c12.y*c13x2 + 2*c10.y*c20.x*c12.x*c12y2*c13.x + 2*c10.y*c11.y*c12.x*c20.y*c13x2 + c11.x*c20.x*c11.y*c12y2*c13.x - 3*c11.x*c20.x*c12.x*c20.y*c13y2 - 2*c10.x*c12x2*c20.y*c12.y*c13.y - 6*c10.y*c20.x*c20.y*c13x2*c13.y - 2*c10.y*c20.x*c12x2*c12.y*c13.y - 2*c10.y*c11x2*c11.y*c13.x*c13.y - c10.y*c11x2*c12.x*c12.y*c13.y - 2*c10.y*c12x2*c20.y*c12.y*c13.x - 2*c11.x*c20.x*c11y2*c13.x*c13.y - c11.x*c11.y*c12x2*c20.y*c13.y + 3*c20.x*c11.y*c20.y*c12.y*c13x2 - 2*c20.x*c12.x*c20.y*c12y2*c13.x - c20.x*c11y2*c12.x*c12.y*c13.x + 3*c10y2*c11.x*c12.x*c13.x*c13.y + 3*c11.x*c12.x*c20y2*c13.x*c13.y + 2*c20.x*c12x2*c20.y*c12.y*c13.y - 3*c10x2*c11.y*c12.y*c13.x*c13.y + 2*c11x2*c11.y*c20.y*c13.x*c13.y + c11x2*c12.x*c20.y*c12.y*c13.y - 3*c20x2*c11.y*c12.y*c13.x*c13.y - c10x3*c13y3 + c10y3*c13x3 + c20x3*c13y3 - c20y3*c13x3 - 3*c10.x*c20x2*c13y3 - c10.x*c11y3*c13x2 + 3*c10x2*c20.x*c13y3 + c10.y*c11x3*c13y2 + 3*c10.y*c20y2*c13x3 + c20.x*c11y3*c13x2 + c10x2*c12y3*c13.x - 3*c10y2*c20.y*c13x3 - c10y2*c12x3*c13.y + c20x2*c12y3*c13.x - c11x3*c20.y*c13y2 - c12x3*c20y2*c13.y - c10.x*c11x2*c11.y*c13y2 + c10.y*c11.x*c11y2*c13x2 - 3*c10.x*c10y2*c13x2*c13.y - c10.x*c11y2*c12x2*c13.y + c10.y*c11x2*c12y2*c13.x - c11.x*c11y2*c20.y*c13x2 + 3*c10x2*c10.y*c13.x*c13y2 + c10x2*c11.x*c12.y*c13y2 + 2*c10x2*c11.y*c12.x*c13y2 - 2*c10y2*c11.x*c12.y*c13x2 - c10y2*c11.y*c12.x*c13x2 + c11x2*c20.x*c11.y*c13y2 - 3*c10.x*c20y2*c13x2*c13.y + 3*c10.y*c20x2*c13.x*c13y2 + c11.x*c20x2*c12.y*c13y2 - 2*c11.x*c20y2*c12.y*c13x2 + c20.x*c11y2*c12x2*c13.y - c11.y*c12.x*c20y2*c13x2 - c10x2*c12.x*c12y2*c13.y - 3*c10x2*c20.y*c13.x*c13y2 + 3*c10y2*c20.x*c13x2*c13.y + c10y2*c12x2*c12.y*c13.x - c11x2*c20.y*c12y2*c13.x + 2*c20x2*c11.y*c12.x*c13y2 + 3*c20.x*c20y2*c13x2*c13.y - c20x2*c12.x*c12y2*c13.y - 3*c20x2*c20.y*c13.x*c13y2 + c12x2*c20y2*c12.y*c13.x ]) roots = poly.rootsInterval(0, 1) for own i, s of roots xRoots = new Polynomial([ c13.x c12.x c11.x c10.x - c20.x - s * c21.x - s * s * c22.x - s * s * s * c23.x ]).roots() yRoots = new Polynomial([ c13.y c12.y c11.y c10.y - c20.y - s * c21.y - s * s * c22.y - s * s * s * c23.y ]).roots() if xRoots.length > 0 and yRoots.length > 0 # IMPORTANT # Tweaking this to be smaller can make it miss intersections. tolerance = 1e-2 for own j, xRoot of xRoots if 0 <= xRoot and xRoot <= 1 for own k, yRoot of yRoots if Math.abs(xRoot - yRoot) < tolerance results.push( c23.multiplyBy(s * s * s).add(c22.multiplyBy(s * s).add(c21.multiplyBy(s).add(c20)))) results
[ { "context": "/API/sigv4-post-example.html\n\t\t\t\t\t\t_testsecret = \"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\"\n\t\t\t\t\t\t_region = \"us-east-1\"\n\t\t\t\t\t\t_policy = \"eyA", "end": 2177, "score": 0.9997460842132568, "start": 2137, "tag": "KEY", "value": "wJalrXUtnFEMI/K7MDENG/bPxRfi...
_src/test/main.coffee
blend/aws-s3-form
0
path = require( "path" ) fs = require( "fs" ) crypto = require( "crypto" ) url = require( "url" ) should = require('should') request = require( "request" ) mime = require('mime-nofs') xmlParse = require('xml2js').parseString Module = require( "../." ) utils = require( "../lib/utils" ) _moduleInst = null _config = null redirPre = "://localhost:3010/redir/" testfileStreamA = null testfileStreamB = null testfileStreamC = null testfileStreamD = null testfileStreamE = null testfileStreamF = null testfileName = null testfileMime = null initFileStreams = -> testfileStreamA = fs.createReadStream(_config.mocha.file) testfileStreamB = fs.createReadStream(_config.mocha.file) testfileStreamC = fs.createReadStream(_config.mocha.file) testfileStreamD = fs.createReadStream(_config.mocha.file) testfileStreamE = fs.createReadStream(_config.mocha.file) testfileStreamF = fs.createReadStream(_config.mocha.file) testfileStreamG = fs.createReadStream(_config.mocha.file) return mimes = [ "application/pdf", "image/jpeg", "text/plain" ] describe "----- aws-s3-form TESTS -----", -> before ( done )-> _config = require( "../config_test.json" ) testfileName = path.basename( _config.mocha.file ) testfileMime = mime.lookup( _config.mocha.file ) _config.s3.keyPrefix = "test_" _moduleInst = new Module( _config.s3 ) # TODO add initialisation Code done() return after ( done )-> # TODO teardown done() return for cryptomod in [ "crypto", "crypto-js" ] (( cryptomod )-> describe "Main Tests with \"#{cryptomod}\"", -> _dataA = null _filenameA = null _dataB = null _filenameB = null _dataC = null _filenameC = null _dataD = null _filenameD = null _dataE = null _filenameE = null _dataF = null _filenameF = null _dataG = null _filenameG = null describe 'Signing', -> it 'Set cyrpto module', -> _moduleInst._setCryptoModule( cryptomod ) return it "test signing", ( done )-> # Example out of http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html _testsecret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" _region = "us-east-1" _policy = "eyAiZXhwaXJhdGlvbiI6ICIyMDEzLTA4LTA3VDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJleGFtcGxlYnVja2V0In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIka2V5IiwgInVzZXIvdXNlcjEvIl0sDQogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwNCiAgICB7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9leGFtcGxlYnVja2V0LnMzLmFtYXpvbmF3cy5jb20vc3VjY2Vzc2Z1bF91cGxvYWQuaHRtbCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwNCiAgICB7IngtYW16LW1ldGEtdXVpZCI6ICIxNDM2NTEyMzY1MTI3NCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJHgtYW16LW1ldGEtdGFnIiwgIiJdLA0KDQogICAgeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFJT1NGT0ROTjdFWEFNUExFLzIwMTMwODA2L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSwNCiAgICB7IngtYW16LWFsZ29yaXRobSI6ICJBV1M0LUhNQUMtU0hBMjU2In0sDQogICAgeyJ4LWFtei1kYXRlIjogIjIwMTMwODA2VDAwMDAwMFoiIH0NCiAgXQ0KfQ==" _signature = _moduleInst.sign _policy, signdate: "20130806" secretAccessKey: _testsecret region: _region should.equal _signature, "21496b44de44ccb73d545f1a995c68214c9cb0d41c45a17a5daeec0b1a6db047" done() return return describe 'SSL', -> it "init filestreams", -> initFileStreams() return # Implement tests cases here it "create data", ( done )-> _filenameA = utils.randomString( 10 ) _opt = redirectUrlTemplate: "https" + redirPre + _filenameA secure: true _dataA = _moduleInst.create( _filenameA, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataA.fields formdata.file = value: testfileStreamA options: filename: testfileName contentType: testfileMime #console.log _dataA request.post { url: _dataA.action, formData: formdata }, ( err, resp, body )-> #console.log err, resp, body if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataA.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameA done() return return it "check if file exists in s3", ( done )-> _url = "https://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameA}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'No SSL', -> # Implement tests cases here it "create data", ( done )-> _filenameB = utils.randomString( 10 ) _opt = redirectUrlTemplate: "http" + redirPre + _filenameB secure: false _dataB = _moduleInst.create( _filenameB, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataB.fields formdata.file = value: testfileStreamB options: filename: testfileName contentType: testfileMime #console.log _dataB request.post { url: _dataB.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataB.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameB done() return return it "check if file exists in s3 (no ssl)", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameB}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'With Mime', -> # Implement tests cases here it "create data", ( done )-> _filenameC = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameC secure: false contentType: testfileMime _dataC = _moduleInst.create( _filenameC, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataC.fields formdata.file = value: testfileStreamC options: filename: testfileName contentType: testfileMime #console.log _dataC request.post { url: _dataC.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataC.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameC done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameC}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime', -> # Implement tests cases here it "create data", ( done )-> _filenameD = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameD secure: false contentType: true _dataD = _moduleInst.create( _filenameD, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataD.fields formdata.file = value: testfileStreamD options: filename: testfileName contentType: testfileMime #console.log _dataD request.post { url: _dataD.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataD.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameD done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameD}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime and valid condition', -> # Implement tests cases here it "create data", ( done )-> _filenameE = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameE secure: false contentType: true customConditions: [ ["starts-with", "$content-type", "image/"] ] _dataE = _moduleInst.create( _filenameE, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataE.fields formdata.file = value: testfileStreamE options: filename: testfileName contentType: testfileMime #console.log _dataE request.post { url: _dataE.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataE.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameE done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameE}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime and invalid condition', -> # Implement tests cases here it "create data with mimetype", ( done )-> _filenameF = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameF secure: false contentType: true customConditions: [ ["starts-with", "$content-type", "application/"] ] _dataF = _moduleInst.create( _filenameF, _opt ) done() return it "send file to s3 with mimetype", ( done )-> @timeout( 30000 ) formdata = _dataF.fields formdata.file = value: testfileStreamF options: filename: testfileName contentType: testfileMime #console.log _dataF request.post { url: _dataF.action, formData: formdata }, ( err, resp, body )-> if err console.log "ERR", err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err errorCode = data?.Error?.Code?[0] errorMsg = data?.Error?.Message?[0] errorCode.should.eql( "AccessDenied" ) errorMsg.should.startWith( "Invalid according to Policy" ) errorMsg.should.match( /\$content-type/i ) done() return throw new Error( "should fail" ) return return it "check if file not exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameF}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 403 ) done() return return return describe 'Custom condition', -> it "create data with numeric custom max length condtion", ( done )-> _filenameG = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = contentType: 'contentType' customConditions: [ ['content-length-range', 0, 1048576], ] _dataG = _moduleInst.create( _filenameF, _opt ) done() return return return )( cryptomod ) return
105197
path = require( "path" ) fs = require( "fs" ) crypto = require( "crypto" ) url = require( "url" ) should = require('should') request = require( "request" ) mime = require('mime-nofs') xmlParse = require('xml2js').parseString Module = require( "../." ) utils = require( "../lib/utils" ) _moduleInst = null _config = null redirPre = "://localhost:3010/redir/" testfileStreamA = null testfileStreamB = null testfileStreamC = null testfileStreamD = null testfileStreamE = null testfileStreamF = null testfileName = null testfileMime = null initFileStreams = -> testfileStreamA = fs.createReadStream(_config.mocha.file) testfileStreamB = fs.createReadStream(_config.mocha.file) testfileStreamC = fs.createReadStream(_config.mocha.file) testfileStreamD = fs.createReadStream(_config.mocha.file) testfileStreamE = fs.createReadStream(_config.mocha.file) testfileStreamF = fs.createReadStream(_config.mocha.file) testfileStreamG = fs.createReadStream(_config.mocha.file) return mimes = [ "application/pdf", "image/jpeg", "text/plain" ] describe "----- aws-s3-form TESTS -----", -> before ( done )-> _config = require( "../config_test.json" ) testfileName = path.basename( _config.mocha.file ) testfileMime = mime.lookup( _config.mocha.file ) _config.s3.keyPrefix = "test_" _moduleInst = new Module( _config.s3 ) # TODO add initialisation Code done() return after ( done )-> # TODO teardown done() return for cryptomod in [ "crypto", "crypto-js" ] (( cryptomod )-> describe "Main Tests with \"#{cryptomod}\"", -> _dataA = null _filenameA = null _dataB = null _filenameB = null _dataC = null _filenameC = null _dataD = null _filenameD = null _dataE = null _filenameE = null _dataF = null _filenameF = null _dataG = null _filenameG = null describe 'Signing', -> it 'Set cyrpto module', -> _moduleInst._setCryptoModule( cryptomod ) return it "test signing", ( done )-> # Example out of http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html _testsecret = "<KEY>" _region = "us-east-1" _policy = "<KEY> _signature = _moduleInst.sign _policy, signdate: "20130806" secretAccessKey: _testsecret region: _region should.equal _signature, "21496b44de44ccb73d545f1a995c68214c9cb0d41c45a17a5daeec0b1a6db047" done() return return describe 'SSL', -> it "init filestreams", -> initFileStreams() return # Implement tests cases here it "create data", ( done )-> _filenameA = utils.randomString( 10 ) _opt = redirectUrlTemplate: "https" + redirPre + _filenameA secure: true _dataA = _moduleInst.create( _filenameA, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataA.fields formdata.file = value: testfileStreamA options: filename: testfileName contentType: testfileMime #console.log _dataA request.post { url: _dataA.action, formData: formdata }, ( err, resp, body )-> #console.log err, resp, body if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataA.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameA done() return return it "check if file exists in s3", ( done )-> _url = "https://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameA}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'No SSL', -> # Implement tests cases here it "create data", ( done )-> _filenameB = utils.randomString( 10 ) _opt = redirectUrlTemplate: "http" + redirPre + _filenameB secure: false _dataB = _moduleInst.create( _filenameB, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataB.fields formdata.file = value: testfileStreamB options: filename: testfileName contentType: testfileMime #console.log _dataB request.post { url: _dataB.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataB.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameB done() return return it "check if file exists in s3 (no ssl)", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameB}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'With Mime', -> # Implement tests cases here it "create data", ( done )-> _filenameC = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameC secure: false contentType: testfileMime _dataC = _moduleInst.create( _filenameC, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataC.fields formdata.file = value: testfileStreamC options: filename: testfileName contentType: testfileMime #console.log _dataC request.post { url: _dataC.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataC.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameC done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameC}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime', -> # Implement tests cases here it "create data", ( done )-> _filenameD = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameD secure: false contentType: true _dataD = _moduleInst.create( _filenameD, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataD.fields formdata.file = value: testfileStreamD options: filename: testfileName contentType: testfileMime #console.log _dataD request.post { url: _dataD.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataD.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameD done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameD}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime and valid condition', -> # Implement tests cases here it "create data", ( done )-> _filenameE = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameE secure: false contentType: true customConditions: [ ["starts-with", "$content-type", "image/"] ] _dataE = _moduleInst.create( _filenameE, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataE.fields formdata.file = value: testfileStreamE options: filename: testfileName contentType: testfileMime #console.log _dataE request.post { url: _dataE.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataE.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameE done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameE}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime and invalid condition', -> # Implement tests cases here it "create data with mimetype", ( done )-> _filenameF = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameF secure: false contentType: true customConditions: [ ["starts-with", "$content-type", "application/"] ] _dataF = _moduleInst.create( _filenameF, _opt ) done() return it "send file to s3 with mimetype", ( done )-> @timeout( 30000 ) formdata = _dataF.fields formdata.file = value: testfileStreamF options: filename: testfileName contentType: testfileMime #console.log _dataF request.post { url: _dataF.action, formData: formdata }, ( err, resp, body )-> if err console.log "ERR", err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err errorCode = data?.Error?.Code?[0] errorMsg = data?.Error?.Message?[0] errorCode.should.eql( "AccessDenied" ) errorMsg.should.startWith( "Invalid according to Policy" ) errorMsg.should.match( /\$content-type/i ) done() return throw new Error( "should fail" ) return return it "check if file not exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameF}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 403 ) done() return return return describe 'Custom condition', -> it "create data with numeric custom max length condtion", ( done )-> _filenameG = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = contentType: 'contentType' customConditions: [ ['content-length-range', 0, 1048576], ] _dataG = _moduleInst.create( _filenameF, _opt ) done() return return return )( cryptomod ) return
true
path = require( "path" ) fs = require( "fs" ) crypto = require( "crypto" ) url = require( "url" ) should = require('should') request = require( "request" ) mime = require('mime-nofs') xmlParse = require('xml2js').parseString Module = require( "../." ) utils = require( "../lib/utils" ) _moduleInst = null _config = null redirPre = "://localhost:3010/redir/" testfileStreamA = null testfileStreamB = null testfileStreamC = null testfileStreamD = null testfileStreamE = null testfileStreamF = null testfileName = null testfileMime = null initFileStreams = -> testfileStreamA = fs.createReadStream(_config.mocha.file) testfileStreamB = fs.createReadStream(_config.mocha.file) testfileStreamC = fs.createReadStream(_config.mocha.file) testfileStreamD = fs.createReadStream(_config.mocha.file) testfileStreamE = fs.createReadStream(_config.mocha.file) testfileStreamF = fs.createReadStream(_config.mocha.file) testfileStreamG = fs.createReadStream(_config.mocha.file) return mimes = [ "application/pdf", "image/jpeg", "text/plain" ] describe "----- aws-s3-form TESTS -----", -> before ( done )-> _config = require( "../config_test.json" ) testfileName = path.basename( _config.mocha.file ) testfileMime = mime.lookup( _config.mocha.file ) _config.s3.keyPrefix = "test_" _moduleInst = new Module( _config.s3 ) # TODO add initialisation Code done() return after ( done )-> # TODO teardown done() return for cryptomod in [ "crypto", "crypto-js" ] (( cryptomod )-> describe "Main Tests with \"#{cryptomod}\"", -> _dataA = null _filenameA = null _dataB = null _filenameB = null _dataC = null _filenameC = null _dataD = null _filenameD = null _dataE = null _filenameE = null _dataF = null _filenameF = null _dataG = null _filenameG = null describe 'Signing', -> it 'Set cyrpto module', -> _moduleInst._setCryptoModule( cryptomod ) return it "test signing", ( done )-> # Example out of http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html _testsecret = "PI:KEY:<KEY>END_PI" _region = "us-east-1" _policy = "PI:KEY:<KEY>END_PI _signature = _moduleInst.sign _policy, signdate: "20130806" secretAccessKey: _testsecret region: _region should.equal _signature, "21496b44de44ccb73d545f1a995c68214c9cb0d41c45a17a5daeec0b1a6db047" done() return return describe 'SSL', -> it "init filestreams", -> initFileStreams() return # Implement tests cases here it "create data", ( done )-> _filenameA = utils.randomString( 10 ) _opt = redirectUrlTemplate: "https" + redirPre + _filenameA secure: true _dataA = _moduleInst.create( _filenameA, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataA.fields formdata.file = value: testfileStreamA options: filename: testfileName contentType: testfileMime #console.log _dataA request.post { url: _dataA.action, formData: formdata }, ( err, resp, body )-> #console.log err, resp, body if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataA.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameA done() return return it "check if file exists in s3", ( done )-> _url = "https://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameA}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'No SSL', -> # Implement tests cases here it "create data", ( done )-> _filenameB = utils.randomString( 10 ) _opt = redirectUrlTemplate: "http" + redirPre + _filenameB secure: false _dataB = _moduleInst.create( _filenameB, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataB.fields formdata.file = value: testfileStreamB options: filename: testfileName contentType: testfileMime #console.log _dataB request.post { url: _dataB.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataB.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameB done() return return it "check if file exists in s3 (no ssl)", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameB}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'With Mime', -> # Implement tests cases here it "create data", ( done )-> _filenameC = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameC secure: false contentType: testfileMime _dataC = _moduleInst.create( _filenameC, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataC.fields formdata.file = value: testfileStreamC options: filename: testfileName contentType: testfileMime #console.log _dataC request.post { url: _dataC.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataC.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameC done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameC}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime', -> # Implement tests cases here it "create data", ( done )-> _filenameD = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameD secure: false contentType: true _dataD = _moduleInst.create( _filenameD, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataD.fields formdata.file = value: testfileStreamD options: filename: testfileName contentType: testfileMime #console.log _dataD request.post { url: _dataD.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataD.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameD done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameD}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime and valid condition', -> # Implement tests cases here it "create data", ( done )-> _filenameE = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameE secure: false contentType: true customConditions: [ ["starts-with", "$content-type", "image/"] ] _dataE = _moduleInst.create( _filenameE, _opt ) done() return it "send file to s3", ( done )-> @timeout( 30000 ) formdata = _dataE.fields formdata.file = value: testfileStreamE options: filename: testfileName contentType: testfileMime #console.log _dataE request.post { url: _dataE.action, formData: formdata }, ( err, resp, body )-> if err console.log err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err console.error( data ) throw new Error( "AWS ERROR" ) return if resp.statusCode is 303 _redirUrl = resp.headers.location _pathobj = url.parse( _redirUrl, true ) _redirobj = url.parse( _dataE.fields.success_action_redirect ) should.equal _pathobj.pathname, _redirobj.pathname should.equal _pathobj.query.bucket, _config.s3.bucket should.equal _pathobj.query.key, _config.s3.keyPrefix + _filenameE done() return return it "check if file exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameE}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 200 ) done() return return return describe 'Auto mime and invalid condition', -> # Implement tests cases here it "create data with mimetype", ( done )-> _filenameF = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = redirectUrlTemplate: "http" + redirPre + _filenameF secure: false contentType: true customConditions: [ ["starts-with", "$content-type", "application/"] ] _dataF = _moduleInst.create( _filenameF, _opt ) done() return it "send file to s3 with mimetype", ( done )-> @timeout( 30000 ) formdata = _dataF.fields formdata.file = value: testfileStreamF options: filename: testfileName contentType: testfileMime #console.log _dataF request.post { url: _dataF.action, formData: formdata }, ( err, resp, body )-> if err console.log "ERR", err throw err if resp.statusCode >= 400 or resp.statusCode < 200 xmlParse body, ( err, data )-> if err console.log err throw err errorCode = data?.Error?.Code?[0] errorMsg = data?.Error?.Message?[0] errorCode.should.eql( "AccessDenied" ) errorMsg.should.startWith( "Invalid according to Policy" ) errorMsg.should.match( /\$content-type/i ) done() return throw new Error( "should fail" ) return return it "check if file not exists in s3", ( done )-> _url = "http://s3.#{ _config.s3.region }.amazonaws.com/#{ _config.s3.bucket }/#{_config.s3.keyPrefix + _filenameF}" request.head _url, ( err, resp, body )-> if err throw err should.equal( resp.statusCode, 403 ) done() return return return describe 'Custom condition', -> it "create data with numeric custom max length condtion", ( done )-> _filenameG = utils.randomString( 10 ) + "." + mime.extension(testfileMime) _opt = contentType: 'contentType' customConditions: [ ['content-length-range', 0, 1048576], ] _dataG = _moduleInst.create( _filenameF, _opt ) done() return return return )( cryptomod ) 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.9998860359191895, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Je...
node_modules/konsserto/lib/src/Konsserto/Bundle/FrameworkBundle/FrameworkBundle.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. ### Bundle = use('@Konsserto/Component/Bundle/Bundle') # # FrameworkBundle # # @author Jessym Reziga <jessym@konsserto.com> # class FrameworkBundle extends Bundle module.exports = new FrameworkBundle
197972
### * 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. ### Bundle = use('@Konsserto/Component/Bundle/Bundle') # # FrameworkBundle # # @author <NAME> <<EMAIL>> # class FrameworkBundle extends Bundle module.exports = new FrameworkBundle
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. ### Bundle = use('@Konsserto/Component/Bundle/Bundle') # # FrameworkBundle # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # class FrameworkBundle extends Bundle module.exports = new FrameworkBundle
[ { "context": " title: 'Återställ lösenord'\n newPassword: 'Nytt lösenord'\n newPasswordAgain: 'Nytt lösenord (upprepa)'\n", "end": 101, "score": 0.999065101146698, "start": 88, "tag": "PASSWORD", "value": "Nytt lösenord" }, { "context": "wPassword: 'Nytt lösenord'\n newPa...
client/settings/accounts-sv-i18n.coffee
hfogelberg/fogelmat
0
i18n.map 'sv', resetPasswordDialog: title: 'Återställ lösenord' newPassword: 'Nytt lösenord' newPasswordAgain: 'Nytt lösenord (upprepa)' cancel: 'Avbryt' submit: 'Ändra lösenord' enrollAccountDialog: title: 'Ange lösenord' newPassword: 'Nytt lösenord' newPasswordAgain: 'Upprepa lösenord' cancel: 'Avbryt' submit: 'Ändra lösenord' justVerifiedEmailDialog: verified: 'Epost adress bekräftad' dismiss: 'Avbryt' loginButtonsMessagesDialog: dismiss: 'Avbryt' loginButtonsLoggedInDropdownActions: password: 'Ändra lösenord' signOut: 'Logga ut' loginButtonsLoggedOutDropdown: signIn: 'Logga in' up: 'Skapa konto' loginButtonsLoggedOutPasswordServiceSeparator: or: 'eller' loginButtonsLoggedOutPasswordService: create: 'Skapa konto' signIn: 'Logga in' forgot: 'Glömt lösenord?' createAcc: 'Skapa konto' forgotPasswordForm: email: 'Email' reset: 'Återställ lösenord' invalidEmail: 'Ogiltig epostadress' loginButtonsBackToLoginLink: back: 'Åter' loginButtonsChangePassword: submit: 'Ändra lösenord' cancel: 'Avbryt' loginButtonsLoggedOutSingleLoginButton: signInWith: 'Logga in med' configure: 'Ändra' loginButtonsLoggedInSingleLogoutButton: signOut: 'Logga ut' loginButtonsLoggedOut: noLoginServices: 'Ingen inloggningstjänst inställd' loginFields: usernameOrEmail: 'Användarnamn eller Epost' username: 'Användarnamn' email: 'Epost' password: 'Lösenord' signupFields: username: 'Användarnamn' email: 'Epost' emailOpt: 'Frivillig postadress' password: 'Lösenord' passwordAgain: 'Upprepa lösenord' changePasswordFields: currentPassword: 'Nuvarande lösenord' newPassword: 'Nytt lösenord' newPasswordAgain: 'Upprepa lösenord' infoMessages: sent: 'Epost sänt' passwordChanged: 'LÖsenord ändrat' errorMessages: userNotFound: 'Ingen användare funnen' invalidEmail: 'Ogiltig epostadress' incorrectPassword: 'Felaktigt lösenord' usernameTooShort: 'Användarnamnet måste vara minst tre tecken långt' passwordTooShort: 'Lösenordet måste vara minst sex tecken långt' passwordsDontMatch: 'Lösenorden stämmer inte överens' newPasswordSameAsOld: 'Det nya lösenordet får inte vara samma som det gamla'
33444
i18n.map 'sv', resetPasswordDialog: title: 'Återställ lösenord' newPassword: '<PASSWORD>' newPasswordAgain: '<PASSWORD> (upprepa)' cancel: 'Avbryt' submit: 'Ändra lösenord' enrollAccountDialog: title: 'Ange lösenord' newPassword: '<PASSWORD>' newPasswordAgain: '<PASSWORD>' cancel: 'Avbryt' submit: 'Ändra lösenord' justVerifiedEmailDialog: verified: 'Epost adress bekräftad' dismiss: 'Avbryt' loginButtonsMessagesDialog: dismiss: 'Avbryt' loginButtonsLoggedInDropdownActions: password: '<PASSWORD>' signOut: 'Logga ut' loginButtonsLoggedOutDropdown: signIn: 'Logga in' up: 'Skapa konto' loginButtonsLoggedOutPasswordServiceSeparator: or: 'eller' loginButtonsLoggedOutPasswordService: create: 'Skapa konto' signIn: 'Logga in' forgot: 'Glömt lösenord?' createAcc: 'Skapa konto' forgotPasswordForm: email: 'Email' reset: 'Återställ lösenord' invalidEmail: 'Ogiltig epostadress' loginButtonsBackToLoginLink: back: 'Åter' loginButtonsChangePassword: submit: 'Ändra lösenord' cancel: 'Avbryt' loginButtonsLoggedOutSingleLoginButton: signInWith: 'Logga in med' configure: 'Ändra' loginButtonsLoggedInSingleLogoutButton: signOut: 'Logga ut' loginButtonsLoggedOut: noLoginServices: 'Ingen inloggningstjänst inställd' loginFields: usernameOrEmail: 'Användarnamn eller Epost' username: 'Användarnamn' email: 'Epost' password: '<PASSWORD>' signupFields: username: 'Användarnamn' email: 'Epost' emailOpt: 'Frivillig postadress' password: '<PASSWORD>' passwordAgain: '<PASSWORD>' changePasswordFields: currentPassword: '<PASSWORD>' newPassword: '<PASSWORD>' newPasswordAgain: '<PASSWORD>' infoMessages: sent: 'Epost sänt' passwordChanged: '<PASSWORD>' errorMessages: userNotFound: 'Ingen användare funnen' invalidEmail: 'Ogiltig epostadress' incorrectPassword: '<PASSWORD>' usernameTooShort: 'Användarnamnet måste vara minst tre tecken långt' passwordTooShort: '<PASSWORD> vara minst sex tecken långt' passwordsDontMatch: 'Lösenorden stämmer inte överens' newPasswordSameAsOld: 'Det nya lösenordet får inte vara samma som det gamla'
true
i18n.map 'sv', resetPasswordDialog: title: 'Återställ lösenord' newPassword: 'PI:PASSWORD:<PASSWORD>END_PI' newPasswordAgain: 'PI:PASSWORD:<PASSWORD>END_PI (upprepa)' cancel: 'Avbryt' submit: 'Ändra lösenord' enrollAccountDialog: title: 'Ange lösenord' newPassword: 'PI:PASSWORD:<PASSWORD>END_PI' newPasswordAgain: 'PI:PASSWORD:<PASSWORD>END_PI' cancel: 'Avbryt' submit: 'Ändra lösenord' justVerifiedEmailDialog: verified: 'Epost adress bekräftad' dismiss: 'Avbryt' loginButtonsMessagesDialog: dismiss: 'Avbryt' loginButtonsLoggedInDropdownActions: password: 'PI:PASSWORD:<PASSWORD>END_PI' signOut: 'Logga ut' loginButtonsLoggedOutDropdown: signIn: 'Logga in' up: 'Skapa konto' loginButtonsLoggedOutPasswordServiceSeparator: or: 'eller' loginButtonsLoggedOutPasswordService: create: 'Skapa konto' signIn: 'Logga in' forgot: 'Glömt lösenord?' createAcc: 'Skapa konto' forgotPasswordForm: email: 'Email' reset: 'Återställ lösenord' invalidEmail: 'Ogiltig epostadress' loginButtonsBackToLoginLink: back: 'Åter' loginButtonsChangePassword: submit: 'Ändra lösenord' cancel: 'Avbryt' loginButtonsLoggedOutSingleLoginButton: signInWith: 'Logga in med' configure: 'Ändra' loginButtonsLoggedInSingleLogoutButton: signOut: 'Logga ut' loginButtonsLoggedOut: noLoginServices: 'Ingen inloggningstjänst inställd' loginFields: usernameOrEmail: 'Användarnamn eller Epost' username: 'Användarnamn' email: 'Epost' password: 'PI:PASSWORD:<PASSWORD>END_PI' signupFields: username: 'Användarnamn' email: 'Epost' emailOpt: 'Frivillig postadress' password: 'PI:PASSWORD:<PASSWORD>END_PI' passwordAgain: 'PI:PASSWORD:<PASSWORD>END_PI' changePasswordFields: currentPassword: 'PI:PASSWORD:<PASSWORD>END_PI' newPassword: 'PI:PASSWORD:<PASSWORD>END_PI' newPasswordAgain: 'PI:PASSWORD:<PASSWORD>END_PI' infoMessages: sent: 'Epost sänt' passwordChanged: 'PI:PASSWORD:<PASSWORD>END_PI' errorMessages: userNotFound: 'Ingen användare funnen' invalidEmail: 'Ogiltig epostadress' incorrectPassword: 'PI:PASSWORD:<PASSWORD>END_PI' usernameTooShort: 'Användarnamnet måste vara minst tre tecken långt' passwordTooShort: 'PI:PASSWORD:<PASSWORD>END_PI vara minst sex tecken långt' passwordsDontMatch: 'Lösenorden stämmer inte överens' newPasswordSameAsOld: 'Det nya lösenordet får inte vara samma som det gamla'
[ { "context": "rect id\"\n equal wrapData.authors, \"R.Fleischer,R.Knegjens\", \n \"Get back corre", "end": 3323, "score": 0.9998834133148193, "start": 3312, "tag": "NAME", "value": "R.Fleischer" }, { "context": " equal wrapData.authors, \...
js/coffee/world_test.coffee
paperscape/paperscape-mapclient
83
define ['app/Vec2D','app/ajax','app/world'], (Vec2D, AJAX, WORLD) -> run : -> module "WORLD" test "Load world tile data", -> AJAX.setDefaults() testCallback = (dims) -> #dims = WORLD.getDimensions() #ok not isNaN(dims.padding) and dims.padding >= 0, # "World padding should be non-negative number: #{dims.padding}" ok not isNaN(dims.tile_px_w) and dims.tile_px_w > 0 and not isNaN(dims.tile_px_h) and dims.tile_px_h > 0, "Tile pixel width and height should be positive numbers: #{dims.tile_px_w}x#{dims.tile_px_h}" ok not isNaN(dims.x_min) and not isNaN(dims.y_min) and not isNaN(dims.x_max) and not isNaN(dims.y_max) and dims.x_min < dims.x_max and dims.y_min < dims.y_max, "World dimensions should not be zero or negative: x = [#{dims.x_min},#{dims.x_max}] , y = [#{dims.y_min},#{dims.y_max}]" latestPaperId = WORLD.getLatestPaperId() ok not isNaN(latestPaperId) and latestPaperId.toString().length == 10, "Latest paper id should be 10 digit number: #{latestPaperId}" newPaperBoundaryId = WORLD.getNewPaperBoundaryId() ok not isNaN(newPaperBoundaryId) and newPaperBoundaryId.toString().length == 10 and newPaperBoundaryId < latestPaperId, "Boundary paper id should be 10 digit number: #{latestPaperId}, and less than latest paper id" ## Test tilings (tune as necessary with tile data) ok WORLD.isWorldReady(), "World ready" # TODO #equal WORLD.getClosestTiling(5).depth, 0 #equal WORLD.getClosestTiling(5).numx, 4 #equal WORLD.getClosestTiling(120).depth, 3 #equal WORLD.getClosestTiling(120).numx, 72 #equal WORLD.getClosestTiling(200).depth, 4 #equal WORLD.getClosestTiling(200).numx, 216 # Test tile urls #dims = WORLD.getDimensions() maxTileWidth = 1e8 depth = WORLD.getClosestTiling(maxTileWidth).depth # Currently x direction sets the y-tiling farEdge = dims.x_max - 50 -dims.x_min # Add 10 as rounding errors adding up! middle = Math.ceil((dims.x_max - dims.x_min)/2)+50 tileInfo = WORLD.getTileInfoAtPosition(depth,farEdge,middle) equal tileInfo.path, "tiles/0/4/3.png" equal WORLD.getClosestLabelZone(5).depth, 8 start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.loadWorldData(testCallback,errorCallback) test "Meta for paper id", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData.id, testId, "Get back correct id" equal wrapData.authors, "R.Fleischer,R.Knegjens", "Get back correct author" equal wrapData.title[..18], "Effective Lifetimes", "Get back correct title" equal wrapData.arxivId, "1109.5115", "Get back correct arxiv id" equal wrapData.categories, "hep-ph,hep-ex", "Get back correct categories" equal wrapData.inspire, "928287", "Get back correct inspire record" equal wrapData.journal[..9], "EuroPhysJC", "Get back correct journal" ok not isNaN(wrapData.numCites), "Number cites given as number" start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.fetchMetaForPaperId(testId,testCallback,errorCallback) test "Abstract for paper id", -> testId = 2115344314 stop() AJAX.setDefaults() testCallback = (wrapData) -> equal(wrapData.id, testId, "Get back correct id") abstStr = wrapData.abstract[..10] ok abstStr == "Measurement" or abstStr == "(no abstrac", "Get back first 10 characters of abstract" start() errorCallback = -> ok false, "Callback error" start() WORLD.fetchAbstractForPaperId(testId,testCallback,errorCallback) test "Fetch location of paper id", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData[0].id, testId, "Get back correct id" ok wrapData[0].x? and wrapData[0].y? and wrapData[0].r?, "x,y,r defined" start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.fetchLocationsForPaperIds([testId],testCallback,errorCallback) test "Fetch paper id at location (calls inverse first)", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData.id, 2115344314, "Get back correct id" start() errorCallback = -> ok false, "Callback error" start() prepCallback = (wrapData) -> WORLD.fetchPaperIdAtLocation(wrapData[0].x,wrapData[0].y,testCallback,errorCallback) stop() WORLD.fetchLocationsForPaperIds([testId],prepCallback,errorCallback) ### test "Fetch keywords in window", -> AJAX.setDefaults() stop() testCallback = (wrapData) -> equal wrapData[0].kw, "test keyword", "Get back correct keyword" start() errorCallback = -> ok false, "Callback error" start() WORLD.fetchKeywordInWindow(0,0,100,100,testCallback,errorCallback) ###
55523
define ['app/Vec2D','app/ajax','app/world'], (Vec2D, AJAX, WORLD) -> run : -> module "WORLD" test "Load world tile data", -> AJAX.setDefaults() testCallback = (dims) -> #dims = WORLD.getDimensions() #ok not isNaN(dims.padding) and dims.padding >= 0, # "World padding should be non-negative number: #{dims.padding}" ok not isNaN(dims.tile_px_w) and dims.tile_px_w > 0 and not isNaN(dims.tile_px_h) and dims.tile_px_h > 0, "Tile pixel width and height should be positive numbers: #{dims.tile_px_w}x#{dims.tile_px_h}" ok not isNaN(dims.x_min) and not isNaN(dims.y_min) and not isNaN(dims.x_max) and not isNaN(dims.y_max) and dims.x_min < dims.x_max and dims.y_min < dims.y_max, "World dimensions should not be zero or negative: x = [#{dims.x_min},#{dims.x_max}] , y = [#{dims.y_min},#{dims.y_max}]" latestPaperId = WORLD.getLatestPaperId() ok not isNaN(latestPaperId) and latestPaperId.toString().length == 10, "Latest paper id should be 10 digit number: #{latestPaperId}" newPaperBoundaryId = WORLD.getNewPaperBoundaryId() ok not isNaN(newPaperBoundaryId) and newPaperBoundaryId.toString().length == 10 and newPaperBoundaryId < latestPaperId, "Boundary paper id should be 10 digit number: #{latestPaperId}, and less than latest paper id" ## Test tilings (tune as necessary with tile data) ok WORLD.isWorldReady(), "World ready" # TODO #equal WORLD.getClosestTiling(5).depth, 0 #equal WORLD.getClosestTiling(5).numx, 4 #equal WORLD.getClosestTiling(120).depth, 3 #equal WORLD.getClosestTiling(120).numx, 72 #equal WORLD.getClosestTiling(200).depth, 4 #equal WORLD.getClosestTiling(200).numx, 216 # Test tile urls #dims = WORLD.getDimensions() maxTileWidth = 1e8 depth = WORLD.getClosestTiling(maxTileWidth).depth # Currently x direction sets the y-tiling farEdge = dims.x_max - 50 -dims.x_min # Add 10 as rounding errors adding up! middle = Math.ceil((dims.x_max - dims.x_min)/2)+50 tileInfo = WORLD.getTileInfoAtPosition(depth,farEdge,middle) equal tileInfo.path, "tiles/0/4/3.png" equal WORLD.getClosestLabelZone(5).depth, 8 start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.loadWorldData(testCallback,errorCallback) test "Meta for paper id", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData.id, testId, "Get back correct id" equal wrapData.authors, "<NAME>,<NAME>", "Get back correct author" equal wrapData.title[..18], "Effective Lifetimes", "Get back correct title" equal wrapData.arxivId, "1109.5115", "Get back correct arxiv id" equal wrapData.categories, "hep-ph,hep-ex", "Get back correct categories" equal wrapData.inspire, "928287", "Get back correct inspire record" equal wrapData.journal[..9], "EuroPhysJC", "Get back correct journal" ok not isNaN(wrapData.numCites), "Number cites given as number" start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.fetchMetaForPaperId(testId,testCallback,errorCallback) test "Abstract for paper id", -> testId = 2115344314 stop() AJAX.setDefaults() testCallback = (wrapData) -> equal(wrapData.id, testId, "Get back correct id") abstStr = wrapData.abstract[..10] ok abstStr == "Measurement" or abstStr == "(no abstrac", "Get back first 10 characters of abstract" start() errorCallback = -> ok false, "Callback error" start() WORLD.fetchAbstractForPaperId(testId,testCallback,errorCallback) test "Fetch location of paper id", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData[0].id, testId, "Get back correct id" ok wrapData[0].x? and wrapData[0].y? and wrapData[0].r?, "x,y,r defined" start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.fetchLocationsForPaperIds([testId],testCallback,errorCallback) test "Fetch paper id at location (calls inverse first)", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData.id, 2115344314, "Get back correct id" start() errorCallback = -> ok false, "Callback error" start() prepCallback = (wrapData) -> WORLD.fetchPaperIdAtLocation(wrapData[0].x,wrapData[0].y,testCallback,errorCallback) stop() WORLD.fetchLocationsForPaperIds([testId],prepCallback,errorCallback) ### test "Fetch keywords in window", -> AJAX.setDefaults() stop() testCallback = (wrapData) -> equal wrapData[0].kw, "test keyword", "Get back correct keyword" start() errorCallback = -> ok false, "Callback error" start() WORLD.fetchKeywordInWindow(0,0,100,100,testCallback,errorCallback) ###
true
define ['app/Vec2D','app/ajax','app/world'], (Vec2D, AJAX, WORLD) -> run : -> module "WORLD" test "Load world tile data", -> AJAX.setDefaults() testCallback = (dims) -> #dims = WORLD.getDimensions() #ok not isNaN(dims.padding) and dims.padding >= 0, # "World padding should be non-negative number: #{dims.padding}" ok not isNaN(dims.tile_px_w) and dims.tile_px_w > 0 and not isNaN(dims.tile_px_h) and dims.tile_px_h > 0, "Tile pixel width and height should be positive numbers: #{dims.tile_px_w}x#{dims.tile_px_h}" ok not isNaN(dims.x_min) and not isNaN(dims.y_min) and not isNaN(dims.x_max) and not isNaN(dims.y_max) and dims.x_min < dims.x_max and dims.y_min < dims.y_max, "World dimensions should not be zero or negative: x = [#{dims.x_min},#{dims.x_max}] , y = [#{dims.y_min},#{dims.y_max}]" latestPaperId = WORLD.getLatestPaperId() ok not isNaN(latestPaperId) and latestPaperId.toString().length == 10, "Latest paper id should be 10 digit number: #{latestPaperId}" newPaperBoundaryId = WORLD.getNewPaperBoundaryId() ok not isNaN(newPaperBoundaryId) and newPaperBoundaryId.toString().length == 10 and newPaperBoundaryId < latestPaperId, "Boundary paper id should be 10 digit number: #{latestPaperId}, and less than latest paper id" ## Test tilings (tune as necessary with tile data) ok WORLD.isWorldReady(), "World ready" # TODO #equal WORLD.getClosestTiling(5).depth, 0 #equal WORLD.getClosestTiling(5).numx, 4 #equal WORLD.getClosestTiling(120).depth, 3 #equal WORLD.getClosestTiling(120).numx, 72 #equal WORLD.getClosestTiling(200).depth, 4 #equal WORLD.getClosestTiling(200).numx, 216 # Test tile urls #dims = WORLD.getDimensions() maxTileWidth = 1e8 depth = WORLD.getClosestTiling(maxTileWidth).depth # Currently x direction sets the y-tiling farEdge = dims.x_max - 50 -dims.x_min # Add 10 as rounding errors adding up! middle = Math.ceil((dims.x_max - dims.x_min)/2)+50 tileInfo = WORLD.getTileInfoAtPosition(depth,farEdge,middle) equal tileInfo.path, "tiles/0/4/3.png" equal WORLD.getClosestLabelZone(5).depth, 8 start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.loadWorldData(testCallback,errorCallback) test "Meta for paper id", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData.id, testId, "Get back correct id" equal wrapData.authors, "PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI", "Get back correct author" equal wrapData.title[..18], "Effective Lifetimes", "Get back correct title" equal wrapData.arxivId, "1109.5115", "Get back correct arxiv id" equal wrapData.categories, "hep-ph,hep-ex", "Get back correct categories" equal wrapData.inspire, "928287", "Get back correct inspire record" equal wrapData.journal[..9], "EuroPhysJC", "Get back correct journal" ok not isNaN(wrapData.numCites), "Number cites given as number" start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.fetchMetaForPaperId(testId,testCallback,errorCallback) test "Abstract for paper id", -> testId = 2115344314 stop() AJAX.setDefaults() testCallback = (wrapData) -> equal(wrapData.id, testId, "Get back correct id") abstStr = wrapData.abstract[..10] ok abstStr == "Measurement" or abstStr == "(no abstrac", "Get back first 10 characters of abstract" start() errorCallback = -> ok false, "Callback error" start() WORLD.fetchAbstractForPaperId(testId,testCallback,errorCallback) test "Fetch location of paper id", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData[0].id, testId, "Get back correct id" ok wrapData[0].x? and wrapData[0].y? and wrapData[0].r?, "x,y,r defined" start() errorCallback = -> ok false, "Callback error" start() stop() WORLD.fetchLocationsForPaperIds([testId],testCallback,errorCallback) test "Fetch paper id at location (calls inverse first)", -> testId = 2115344314 AJAX.setDefaults() testCallback = (wrapData) -> equal wrapData.id, 2115344314, "Get back correct id" start() errorCallback = -> ok false, "Callback error" start() prepCallback = (wrapData) -> WORLD.fetchPaperIdAtLocation(wrapData[0].x,wrapData[0].y,testCallback,errorCallback) stop() WORLD.fetchLocationsForPaperIds([testId],prepCallback,errorCallback) ### test "Fetch keywords in window", -> AJAX.setDefaults() stop() testCallback = (wrapData) -> equal wrapData[0].kw, "test keyword", "Get back correct keyword" start() errorCallback = -> ok false, "Callback error" start() WORLD.fetchKeywordInWindow(0,0,100,100,testCallback,errorCallback) ###
[ { "context": "pi.wit.ai\")\n .header(\"Authorization\", \"Bearer DRZ2GX4X7HTGJU3Q7BZ77TNDJLL6EC7K\")\n .p", "end": 1717, "score": 0.912705659866333, "start": 1711, "tag": "KEY", "value": "Bearer" }, { "context": ".ai\")\n .header(\"Authorization\", \"...
src/adapters/shell.coffee
kevinmarx/hubot
0
Readline = require 'readline' Robot = require '../robot' Adapter = require '../adapter' {TextMessage} = require '../message' exec = require('child_process').exec async = require 'async' HttpClient = require 'scoped-http-client' class Shell extends Adapter send: (envelope, strings...) -> unless process.platform is 'win32' for str in strings console.log "\x1b[01;32m#{str}\x1b[0m" strArr = str.split(/\n/g) ex = [] speech = (says) -> return (callback) -> exec('say ' + says, () -> callback()) for i in strArr by 1 sayString = i ex.push speech(sayString) async.series(ex) else for str in strings console.log "#{str}" exec('say #{str}') @repl.prompt() emote: (envelope, strings...) -> @send envelope, "* #{str}" for str in strings reply: (envelope, strings...) -> strings = strings.map (s) -> "#{envelope.user.name}: #{s}" @send envelope, strings... run: -> self = @ stdin = process.openStdin() stdout = process.stdout process.on 'uncaughtException', (err) => @robot.logger.error err.stack @repl = Readline.createInterface stdin, stdout, null @repl.on 'close', => stdin.destroy() @robot.shutdown() process.exit 0 @repl.on 'line', (buffer) => @repl.close() if buffer.toLowerCase() is 'exit' @repl.prompt() user = @robot.brain.userForId '1', name: 'Shell', room: 'Shell' if buffer.replace(/^\s\s*/, '').replace(/\s\s*$/, '') async.auto brain: (callback) -> HttpClient.create("https://api.wit.ai") .header("Authorization", "Bearer DRZ2GX4X7HTGJU3Q7BZ77TNDJLL6EC7K") .path("/message") .query(q: buffer) .get() (err, res, body) -> callback err, body , (err, results) => @receive new TextMessage user, results.brain, 'messageId' self.emit 'connected' @repl.setPrompt "#{@robot.name}> " @repl.prompt() exports.use = (robot) -> new Shell robot
20634
Readline = require 'readline' Robot = require '../robot' Adapter = require '../adapter' {TextMessage} = require '../message' exec = require('child_process').exec async = require 'async' HttpClient = require 'scoped-http-client' class Shell extends Adapter send: (envelope, strings...) -> unless process.platform is 'win32' for str in strings console.log "\x1b[01;32m#{str}\x1b[0m" strArr = str.split(/\n/g) ex = [] speech = (says) -> return (callback) -> exec('say ' + says, () -> callback()) for i in strArr by 1 sayString = i ex.push speech(sayString) async.series(ex) else for str in strings console.log "#{str}" exec('say #{str}') @repl.prompt() emote: (envelope, strings...) -> @send envelope, "* #{str}" for str in strings reply: (envelope, strings...) -> strings = strings.map (s) -> "#{envelope.user.name}: #{s}" @send envelope, strings... run: -> self = @ stdin = process.openStdin() stdout = process.stdout process.on 'uncaughtException', (err) => @robot.logger.error err.stack @repl = Readline.createInterface stdin, stdout, null @repl.on 'close', => stdin.destroy() @robot.shutdown() process.exit 0 @repl.on 'line', (buffer) => @repl.close() if buffer.toLowerCase() is 'exit' @repl.prompt() user = @robot.brain.userForId '1', name: 'Shell', room: 'Shell' if buffer.replace(/^\s\s*/, '').replace(/\s\s*$/, '') async.auto brain: (callback) -> HttpClient.create("https://api.wit.ai") .header("Authorization", "<KEY> <KEY>") .path("/message") .query(q: buffer) .get() (err, res, body) -> callback err, body , (err, results) => @receive new TextMessage user, results.brain, 'messageId' self.emit 'connected' @repl.setPrompt "#{@robot.name}> " @repl.prompt() exports.use = (robot) -> new Shell robot
true
Readline = require 'readline' Robot = require '../robot' Adapter = require '../adapter' {TextMessage} = require '../message' exec = require('child_process').exec async = require 'async' HttpClient = require 'scoped-http-client' class Shell extends Adapter send: (envelope, strings...) -> unless process.platform is 'win32' for str in strings console.log "\x1b[01;32m#{str}\x1b[0m" strArr = str.split(/\n/g) ex = [] speech = (says) -> return (callback) -> exec('say ' + says, () -> callback()) for i in strArr by 1 sayString = i ex.push speech(sayString) async.series(ex) else for str in strings console.log "#{str}" exec('say #{str}') @repl.prompt() emote: (envelope, strings...) -> @send envelope, "* #{str}" for str in strings reply: (envelope, strings...) -> strings = strings.map (s) -> "#{envelope.user.name}: #{s}" @send envelope, strings... run: -> self = @ stdin = process.openStdin() stdout = process.stdout process.on 'uncaughtException', (err) => @robot.logger.error err.stack @repl = Readline.createInterface stdin, stdout, null @repl.on 'close', => stdin.destroy() @robot.shutdown() process.exit 0 @repl.on 'line', (buffer) => @repl.close() if buffer.toLowerCase() is 'exit' @repl.prompt() user = @robot.brain.userForId '1', name: 'Shell', room: 'Shell' if buffer.replace(/^\s\s*/, '').replace(/\s\s*$/, '') async.auto brain: (callback) -> HttpClient.create("https://api.wit.ai") .header("Authorization", "PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI") .path("/message") .query(q: buffer) .get() (err, res, body) -> callback err, body , (err, results) => @receive new TextMessage user, results.brain, 'messageId' self.emit 'connected' @repl.setPrompt "#{@robot.name}> " @repl.prompt() exports.use = (robot) -> new Shell robot
[ { "context": "Greetings\n\ngreetings = [\n [ \"Afrikaans\", \"Goeie môre\" ]\n [ \"Albanian\", \"Mirëmëngjes\" ]\n [ ", "end": 65, "score": 0.9547140002250671, "start": 55, "tag": "NAME", "value": "Goeie môre" }, { "context": "ns\", \"Goeie môre\" ]\n [ \"...
support/greetings.coffee
dshoreman/liona
9
# Da Greetings greetings = [ [ "Afrikaans", "Goeie môre" ] [ "Albanian", "Mirëmëngjes" ] [ "Amharic", "Endermen aderkh" ] [ "Arabic", "Sabah-il-kheir" ] [ "Aramaic", "Yasetel liesbukh" ] [ "Armenian", "Bari luys" ] [ "Assyrian", "Kedamtookh brikhta" ] [ "Azerbaijani", "Sabahiniz Xeyr" ] [ "Bamougoum", "Oli yah" ] [ "Bangla", "Shuvo sokal" ] [ "Basque", "Egun on" ] [ "Belarussian", "Dobray ranitsy" ] [ "Bemba", "Mwashibukeni" ] [ "Bengali", "Shu-probhaat" ] [ "Bisaya", "Maayong adlaw" ] [ "Binary", "011001110110111101101111011001000010000001101101011011110111001001101110011010010110111001100111" ] [ "Bosnian", "Dobro jutro" ] [ "Bulgarian", "Dobro utro" ] [ "Cantonese", "Zou san" ] [ "Catalan", "Bon dia" ] [ "Cebuano", "Maayong buntag!" ] [ "Chichewa", "Mwadzuka bwanji" ] [ "Chinese", "Zao shang hao" ] [ "Mandarin", "Zao shang hao" ] [ "Cornish", "Myttin da" ] [ "Corse", "Bun ghjiornu" ] [ "Creole", "Bonjou" ] [ "Croatian", "Dobro jutro" ] [ "Czech", "Dobré ráno" ] [ "Danish", "God morgen" ] [ "Dari", "Sob Bakhaer" ] [ "Divehi", "Baajjaveri hedhuneh" ] [ "Dutch", "Goedemorgen" ] [ "English", "Good morning" ] [ "Esperanto", "Bonan matenon" ] [ "Estonian", "Tere hommikust" ] [ "Etsakor", "Naigbia" ] [ "Fanti", "Me ma wo akye" ] [ "Fijian", "Sa Yadra" ] [ "Filipino", "Magandang umaga po" ] [ "Finnish", "Hyvää huomenta" ] [ "Flanders", "Hey-Diddly-Ho" ] [ "Flemish", "Goeie morgen" ] [ "French", "Bonjour" ] [ "Frisian", "Goeie moarn" ] [ "Galician", "Bos dias" ] [ "Georgian", "Dila mshvidobisa" ] [ "German", "Guten Morgen" ] [ "Greek", "Kali mera" ] [ "Greenlandic", "Iterluarit" ] [ "Gujarati", "Subh Prabhat" ] [ "Hakka", "On zoh" ] [ "Hausa", "Inaa kwana" ] [ "Hawaiian", "Aloha kakahiaka" ] [ "Hebrew", "Boker tov" ] [ "Hexadecimal", "67 6F 6F 64 20 6D 6F 72 6E 69 6E 67" ] [ "Hiligaynon", "Maayong aga" ] [ "Hindi", "Shubh prabhat" ] [ "Hungarian", "Jo reggelt" ] [ "Icelandic", "Gódan daginn" ] [ "Ilocano", "Naimbag nga Aldaw" ] [ "Indonesian", "Selamat pagi" ] [ "Irish", "Dia duit ar maidin" ] [ "Italian", "Buon giorno" ] [ "Japanese", "Ohayo gozaimasu" ] [ "Kannada", "Shubhodaya" ] [ "Kapampangan", "Mayap a abak" ] [ "Kazakh", "Kairly Tan" ] [ "Khmer", "Arrun Suo Sdey" ] [ "Kimeru", "Muga rukiiri" ] [ "Kinyarwanda", "Muraho" ] [ "Konkani", "Dev Tuka Boro Dis Divum" ] [ "Korean", "Annyunghaseyo" ] [ "Kurdish Badini", "Spede bash" ] [ "Kurdish Sorani", "Beyani bash" ] [ "Lao", "Sabaidee" ] [ "Latin", "Bonum mane" ] [ "Latvian", "Labrit" ] [ "Lithuanian", "Labas rytas" ] [ "Lozi", "U zuhile" ] [ "Luganda", "Wasuze otyano" ] [ "Luo", "Oyawore" ] [ "Luxembourg", "Gudde moien" ] [ "Macedonian", "Dobro utro" ] [ "Malayalam", "Suprabhatham" ] [ "Malay", "Selamat pagi" ] [ "Maltese", "Għodwa it-tajba" ] [ "Manx", "Moghrey mie" ] [ "Maori", "Ata marie" ] [ "Mapudungun", "Mari mari" ] [ "Marathi", "Suprabhat" ] [ "Mongolian", "Öglouny mend" ] [ "Navajo", "Yá'át'ééh abíní" ] [ "Ndebele", "Livukenjani" ] [ "Nepali", "Subha prabhat" ] [ "Northern Sotho", "Thobela" ] [ "Norwegian", "God morgen" ] [ "Owambo", "Wa lalapo" ] [ "Pashto", "Sahar de pa Khair" ] [ "Persian", "Subbakhair" ] [ "Pingu", "Noot noot!" ] [ "Pirate", "Avast, ye scurvy dog" ] [ "Polish", "Witaj" ] [ "Polynesian", "Ia ora na" ] [ "Portuguese", "Bom dia" ] [ "Punjabi", "Sat Shri Akal" ] [ "Rapa Nui", "Iorana" ] [ "Romanian", "Buna dimineata" ] [ "Russian", "Dobroye utro" ] [ "Samoan", "Talofa lava" ] [ "Sanskrit", "Suprabhataha" ] [ "Sardinian", "Bona dia" ] [ "Serbian", "Dobro jutro" ] [ "Shona", "Mangwanani" ] [ "Sinhalese", "Suba Udesanak Wewa" ] [ "Slovak", "Dobré ráno" ] [ "Slovenian", "Dobro jutro" ] [ "Somalian", "Subax wanaagsan" ] [ "Southern Sotho", "Dumela" ] [ "Spanish", "Buenos dias" ] [ "Swahili", "Habari za asubuhi" ] [ "Swazi", "Sawubona" ] [ "Swedish", "God morgon" ] [ "Tagalog", "Magandang umaga" ] [ "Taiwanese", "Gau cha" ] [ "Tamil", "Kaalai Vannakkam" ] [ "Telugu", "Subhodayamu" ] [ "Tetum", "Dader diak" ] [ "Thai", "Aroon-Sawass" ] [ "Tibetan", "Nyado delek" ] [ "Tonga", "Mwabuka buti" ] [ "Tswana", "Dumela" ] [ "Twi", "Me ma wo maakye" ] [ "Turkish", "Günaydin" ] [ "Turkmen", "Ertiringiz haiyirli bolsun" ] [ "Ukrainian", "Dobri ranok" ] [ "Urdu", "Subha Ba-khair" ] [ "Uzbek", "Khairli kun" ] [ "Vietnamese", "Xin chao" ] [ "Welsh", "Bore da" ] [ "Xhosa", "Bhota" ] [ "Xitsonga", "Avuxeni" ] [ "Yoruba", "E karo" ] [ "Zulu", "Sawubona" ] [ "!Kung san", "Tuwa" ] [ "Australian", "G'day" ] [ "Klingon", "nuqneH" ] [ "tlhIngan Hol", "nuqneH" ] [ "Vulcan", "Dif-tor heh smusma" ] [ "Romulan", "Brhon mnekha" ] [ "Ferengi", "Welcome to our home. Please place your thumbprint on the legal waivers and deposit your admission fee in the slot by the door. Remember, my house is my house," ] [ "Bajoran", "Soraya neryshu" ] [ "Malkovich", "Malkovich Malkovich Malkovich," ] [ "Frozen", "Let it go," ] [ "Doc", "Great Scott," ] [ "Captain Jack", "http://33.media.tumblr.com/d27594fa4e9788bd23c98e1617737527/tumblr_n70xx6I4ZA1s9qnu2o2_500.gif" ] [ "Pintel", "Hello Poppet," ] [ "Buzz", "To infinity and beyond," ] [ "Thundercats", "Thundercats Ho," ] [ "Anchorman", "News team assemble!" ] [ "Wonka", "Good morning starshine, the earth says hello," ] [ "Pink Floyd", "Hello, is there anybody in there? Just nod if you can hear me. Is there anyone at home?" ] [ "Lionel Richie", "Hello! Is it me you're looking for?" ] [ "Beatles", "Good morning, good morning. Good morning ah" ] [ "Megamind", "Ollo?" ] [ "Rickroll", "Never gonna give you up, Never gonna let you down, Never gonna run around and desert you, Never gonna make you cry, Never gonna say goodbye, Never gonna tell a lie and hurt you." ] [ "Wookiee", "raaaaaahhgh raaaaaahhgh aaaaahnr" ] [ "Taelon", "Sinuai Euhura" ] [ "Bart Simpson", "Eat my shorts" ] [ "Homer Simpson", "D'oh" ] [ "Fonzie", "Ayyy" ] [ "verax", "yooooooooooooooooooooooooooooooooooooooooooooooo" ] [ "Protoss", "You must construct additional pylons," ] [ "Terran", "Additional supply depots required," ] [ "Zerg", "Spawn more overlords," ] [ "A Flock of Seagulls", "And I ran, I ran so far away, I just ran, I ran all night and day, I couldn't get away," ] [ "Dothraki", "Aena shekhikhi" ] [ "Valyrian", "Sȳz ñāqes" ] [ "Pig Latin", "Oodgay orningmay" ] [ "Ed McMahon", "Heeeere's ..." ] [ "Garey Coleman", "What'choo talkin' 'bout, " ] [ "Superman", "Look! Up in the sky! It's a bird! It's a plane! It's" ] [ "Mission Impossible", "This tape will self-destruct in five seconds" ] [ "Spock", "Live long and prosper" ] [ "Picard", "Make it so" ] [ "Mork", "Na-nu Na-nu" ] [ "Otaku", "Sniff my pantsu, " ] [ "Bitconnect", "Wassa-wassa-wassa-wassa-wassa-wassa-wassa-wassuuuuup! BitConneeeeeeeeect!" ] [ "Hulk Hogan", "Whatcha gonna do brother, when Hulkamania runs WILD on you?" ] [ "Office Space", "Uh, I just wanted to make sure you knew that we did start at the, um, usual time this morning. Yeah, it isn't a half day or anything like that"] ] class GreetingsRepository GREETINGS = [] constructor: -> for greeting in greetings [lang, greet] = greeting[0..1] GREETINGS[lang.toLowerCase()] = lang: lang, greeting: greet find: (name) -> GREETINGS[name.toLowerCase()] findOrRandom: (robot, name) -> name? && @find(name) || @random(robot) greeting: (name) -> @find(name)?.greeting all: -> GREETINGS names: -> for v of GREETINGS v.lang keys: -> Object.keys(GREETINGS) random: (robot) -> GREETINGS[robot.random @keys()] module.exports = GreetingsRepository
71403
# Da Greetings greetings = [ [ "Afrikaans", "<NAME>" ] [ "Albanian", "<NAME>" ] [ "Amharic", "<NAME>" ] [ "Arabic", "Sabah-il-kheir" ] [ "Aramaic", "<NAME>" ] [ "Armenian", "Bari luys" ] [ "Assyrian", "Kedamtook<NAME>hta" ] [ "Azerbaijani", "<NAME>" ] [ "Bamougoum", "<NAME>" ] [ "Bangla", "Shuvo sokal" ] [ "Basque", "Egun on" ] [ "Belarussian", "Dobr<NAME>" ] [ "Bemba", "<NAME>i" ] [ "Bengali", "Shu-probhaat" ] [ "Bisaya", "<NAME>ayong <NAME>" ] [ "Binary", "011001110110111101101111011001000010000001101101011011110111001001101110011010010110111001100111" ] [ "Bosnian", "Dobro jutro" ] [ "Bulgarian", "Dobro utro" ] [ "Cantonese", "Zou san" ] [ "Catalan", "Bon dia" ] [ "Cebuano", "Maayong buntag!" ] [ "Chichewa", "<NAME>adzuka bwanji" ] [ "Chinese", "Zao shang hao" ] [ "Mandarin", "Zao shang hao" ] [ "Cornish", "<NAME>" ] [ "<NAME>", "<NAME>" ] [ "Creole", "Bonjou" ] [ "Croatian", "<NAME>" ] [ "Czech", "Do<NAME>" ] [ "Danish", "God <NAME>" ] [ "Dari", "<NAME>" ] [ "Divehi", "Baajjaveri hedhuneh" ] [ "Dutch", "Goedemorgen" ] [ "English", "Good morning" ] [ "Esperanto", "Bonan matenon" ] [ "Estonian", "<NAME>" ] [ "Etsakor", "Naigbia" ] [ "Fanti", "Me ma wo akye" ] [ "Fijian", "Sa Yadra" ] [ "Filipino", "Magandang umaga po" ] [ "Finnish", "Hyvää huomenta" ] [ "Flanders", "Hey-Diddly-Ho" ] [ "Flemish", "Go<NAME>ie m<NAME>en" ] [ "French", "Bonjour" ] [ "Frisian", "Goeie moarn" ] [ "Galician", "Bos dias" ] [ "Georgian", "<NAME>" ] [ "German", "Guten Morgen" ] [ "Greek", "Kali mera" ] [ "Greenlandic", "Iterluarit" ] [ "Gujarati", "Subh Prabhat" ] [ "Hakka", "On zoh" ] [ "Hausa", "Inaa kwana" ] [ "Hawaiian", "Aloha kakahiaka" ] [ "Hebrew", "Boker tov" ] [ "Hexadecimal", "67 6F 6F 64 20 6D 6F 72 6E 69 6E 67" ] [ "Hiligaynon", "Maayong aga" ] [ "Hindi", "Shubh prabhat" ] [ "Hungarian", "Jo reggelt" ] [ "Icelandic", "<NAME>" ] [ "Ilocano", "Naimbag nga Aldaw" ] [ "Indonesian", "Selamat pagi" ] [ "Irish", "Dia duit ar maidin" ] [ "Italian", "Buon giorno" ] [ "Japanese", "Ohayo gozaimasu" ] [ "Kannada", "Shubhodaya" ] [ "Kapampangan", "Mayap a abak" ] [ "Kazakh", "<NAME>" ] [ "Khmer", "<NAME>" ] [ "Kimeru", "Muga rukiiri" ] [ "Kinyarwanda", "Muraho" ] [ "Konkani", "Dev Tuka Boro Dis Divum" ] [ "Korean", "Annyunghaseyo" ] [ "Kurdish Badini", "Spede bash" ] [ "Kurdish Sorani", "Beyani bash" ] [ "Lao", "Sabaidee" ] [ "Latin", "Bonum mane" ] [ "Latvian", "Labrit" ] [ "Lithuanian", "Labas rytas" ] [ "Lozi", "U zuhile" ] [ "Luganda", "Wasuze otyano" ] [ "Luo", "Oyawore" ] [ "Luxembourg", "Gudde moien" ] [ "Macedonian", "Dobro utro" ] [ "Malayalam", "Suprabhatham" ] [ "Malay", "Selamat pagi" ] [ "Maltese", "Għodwa it-taj<NAME>" ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "<NAME>" ] [ "Mongolian", "Ögloun<NAME>" ] [ "<NAME>avajo", "Yá'át'ééh abíní" ] [ "Ndebele", "Livukenjani" ] [ "Nepali", "Subha prabhat" ] [ "Northern Sotho", "Thobela" ] [ "Norwegian", "God morgen" ] [ "Ow<NAME>bo", "Wa lalapo" ] [ "Pas<NAME>o", "<NAME>" ] [ "Persian", "Subbakhair" ] [ "Pingu", "Noot noot!" ] [ "Pirate", "Avast, ye scurvy dog" ] [ "Polish", "<NAME>itaj" ] [ "Polynesian", "Ia ora na" ] [ "Portuguese", "Bom dia" ] [ "Punjabi", "Sat <NAME> Akal" ] [ "Rapa Nui", "Iorana" ] [ "Romanian", "Buna dimineata" ] [ "Russian", "Dobroye utro" ] [ "Samoan", "Talofa lava" ] [ "Sanskrit", "Suprabhataha" ] [ "Sardinian", "Bona dia" ] [ "Serbian", "D<NAME>ro jutro" ] [ "Shona", "Mangwanani" ] [ "Sinhalese", "Suba Udesanak Wewa" ] [ "Slovak", "Dobré ráno" ] [ "Slovenian", "Dobro jutro" ] [ "Somalian", "Subax wanaagsan" ] [ "Southern Sotho", "Dumela" ] [ "Spanish", "Buenos dias" ] [ "Swahili", "Habari za asubuhi" ] [ "Swazi", "Sawubona" ] [ "Swedish", "God morgon" ] [ "Tagalog", "Magandang umaga" ] [ "Taiwanese", "Gau cha" ] [ "Tamil", "Kaalai Vannakkam" ] [ "Telugu", "Subhodayamu" ] [ "Tetum", "Dader diak" ] [ "Thai", "Aroon-Sawass" ] [ "Tibetan", "Nyado delek" ] [ "Tonga", "Mwabuka buti" ] [ "Tswana", "Dumela" ] [ "Twi", "Me ma wo maakye" ] [ "Turkish", "Günaydin" ] [ "Turkmen", "Ertiringiz haiyirli bolsun" ] [ "Ukrainian", "Dobri ranok" ] [ "Urdu", "Subha Ba-khair" ] [ "Uzbek", "Khairli kun" ] [ "Vietnamese", "Xin chao" ] [ "Welsh", "Bore da" ] [ "Xhosa", "Bhota" ] [ "Xitsonga", "Avuxeni" ] [ "Yoruba", "E karo" ] [ "Zulu", "Sawubona" ] [ "!Kung san", "Tuwa" ] [ "Australian", "G'day" ] [ "Klingon", "nuqneH" ] [ "tlhIngan Hol", "nuqneH" ] [ "Vulcan", "Dif-tor heh smusma" ] [ "Romulan", "Brhon mnekha" ] [ "Ferengi", "Welcome to our home. Please place your thumbprint on the legal waivers and deposit your admission fee in the slot by the door. Remember, my house is my house," ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "<NAME>," ] [ "<NAME>", "Let it go," ] [ "<NAME>", "Great <NAME>cott," ] [ "<NAME>", "http://33.media.tumblr.com/d27594fa4e9788bd23c98e1617737527/tumblr_n70xx6I4ZA1s9qnu2o2_500.gif" ] [ "<NAME>", "Hello <NAME>," ] [ "<NAME>", "To infinity and beyond," ] [ "<NAME>", "Thundercats Ho," ] [ "<NAME>", "News team assemble!" ] [ "<NAME>", "Good morning starshine, the earth says hello," ] [ "<NAME>", "Hello, is there anybody in there? Just nod if you can hear me. Is there anyone at home?" ] [ "<NAME>", "Hello! Is it me you're looking for?" ] [ "<NAME>", "Good morning, good morning. Good morning ah" ] [ "<NAME>", "Ollo?" ] [ "<NAME>", "Never gonna give you up, Never gonna let you down, Never gonna run around and desert you, Never gonna make you cry, Never gonna say goodbye, Never gonna tell a lie and hurt you." ] [ "<NAME>", "raaaaaahhgh raaaaaahhgh aaaaahnr" ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "Eat my shorts" ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "Ayyy" ] [ "<NAME>", "yooooooooooooooooooooooooooooooooooooooooooooooo" ] [ "<NAME>", "You must construct additional pylons," ] [ "<NAME>", "Additional supply depots required," ] [ "<NAME>", "Spawn more overlords," ] [ "A Flock of Seagulls", "And I ran, I ran so far away, I just ran, I ran all night and day, I couldn't get away," ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "<NAME>" ] [ "<NAME>", "Heeeere's ..." ] [ "<NAME>", "What'choo talkin' 'bout, " ] [ "<NAME>", "Look! Up in the sky! It's a bird! It's a plane! It's" ] [ "Mission Impossible", "This tape will self-destruct in five seconds" ] [ "<NAME>", "Live long and prosper" ] [ "<NAME>", "Make it so" ] [ "<NAME>", "Na-nu Na-nu" ] [ "<NAME>", "Sniff my pantsu, " ] [ "Bitconnect", "Wassa-wassa-wassa-wassa-wassa-wassa-wassa-wassuuuuup! BitConneeeeeeeeect!" ] [ "<NAME>", "Whatcha gonna do brother, when Hulkamania runs WILD on you?" ] [ "Office Space", "Uh, I just wanted to make sure you knew that we did start at the, um, usual time this morning. Yeah, it isn't a half day or anything like that"] ] class GreetingsRepository GREETINGS = [] constructor: -> for greeting in greetings [lang, greet] = greeting[0..1] GREETINGS[lang.toLowerCase()] = lang: lang, greeting: greet find: (name) -> GREETINGS[name.toLowerCase()] findOrRandom: (robot, name) -> name? && @find(name) || @random(robot) greeting: (name) -> @find(name)?.greeting all: -> GREETINGS names: -> for v of GREETINGS v.lang keys: -> Object.keys(GREETINGS) random: (robot) -> GREETINGS[robot.random @keys()] module.exports = GreetingsRepository
true
# Da Greetings greetings = [ [ "Afrikaans", "PI:NAME:<NAME>END_PI" ] [ "Albanian", "PI:NAME:<NAME>END_PI" ] [ "Amharic", "PI:NAME:<NAME>END_PI" ] [ "Arabic", "Sabah-il-kheir" ] [ "Aramaic", "PI:NAME:<NAME>END_PI" ] [ "Armenian", "Bari luys" ] [ "Assyrian", "KedamtookPI:NAME:<NAME>END_PIhta" ] [ "Azerbaijani", "PI:NAME:<NAME>END_PI" ] [ "Bamougoum", "PI:NAME:<NAME>END_PI" ] [ "Bangla", "Shuvo sokal" ] [ "Basque", "Egun on" ] [ "Belarussian", "DobrPI:NAME:<NAME>END_PI" ] [ "Bemba", "PI:NAME:<NAME>END_PIi" ] [ "Bengali", "Shu-probhaat" ] [ "Bisaya", "PI:NAME:<NAME>END_PIayong PI:NAME:<NAME>END_PI" ] [ "Binary", "011001110110111101101111011001000010000001101101011011110111001001101110011010010110111001100111" ] [ "Bosnian", "Dobro jutro" ] [ "Bulgarian", "Dobro utro" ] [ "Cantonese", "Zou san" ] [ "Catalan", "Bon dia" ] [ "Cebuano", "Maayong buntag!" ] [ "Chichewa", "PI:NAME:<NAME>END_PIadzuka bwanji" ] [ "Chinese", "Zao shang hao" ] [ "Mandarin", "Zao shang hao" ] [ "Cornish", "PI:NAME:<NAME>END_PI" ] [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] [ "Creole", "Bonjou" ] [ "Croatian", "PI:NAME:<NAME>END_PI" ] [ "Czech", "DoPI:NAME:<NAME>END_PI" ] [ "Danish", "God PI:NAME:<NAME>END_PI" ] [ "Dari", "PI:NAME:<NAME>END_PI" ] [ "Divehi", "Baajjaveri hedhuneh" ] [ "Dutch", "Goedemorgen" ] [ "English", "Good morning" ] [ "Esperanto", "Bonan matenon" ] [ "Estonian", "PI:NAME:<NAME>END_PI" ] [ "Etsakor", "Naigbia" ] [ "Fanti", "Me ma wo akye" ] [ "Fijian", "Sa Yadra" ] [ "Filipino", "Magandang umaga po" ] [ "Finnish", "Hyvää huomenta" ] [ "Flanders", "Hey-Diddly-Ho" ] [ "Flemish", "GoPI:NAME:<NAME>END_PIie mPI:NAME:<NAME>END_PIen" ] [ "French", "Bonjour" ] [ "Frisian", "Goeie moarn" ] [ "Galician", "Bos dias" ] [ "Georgian", "PI:NAME:<NAME>END_PI" ] [ "German", "Guten Morgen" ] [ "Greek", "Kali mera" ] [ "Greenlandic", "Iterluarit" ] [ "Gujarati", "Subh Prabhat" ] [ "Hakka", "On zoh" ] [ "Hausa", "Inaa kwana" ] [ "Hawaiian", "Aloha kakahiaka" ] [ "Hebrew", "Boker tov" ] [ "Hexadecimal", "67 6F 6F 64 20 6D 6F 72 6E 69 6E 67" ] [ "Hiligaynon", "Maayong aga" ] [ "Hindi", "Shubh prabhat" ] [ "Hungarian", "Jo reggelt" ] [ "Icelandic", "PI:NAME:<NAME>END_PI" ] [ "Ilocano", "Naimbag nga Aldaw" ] [ "Indonesian", "Selamat pagi" ] [ "Irish", "Dia duit ar maidin" ] [ "Italian", "Buon giorno" ] [ "Japanese", "Ohayo gozaimasu" ] [ "Kannada", "Shubhodaya" ] [ "Kapampangan", "Mayap a abak" ] [ "Kazakh", "PI:NAME:<NAME>END_PI" ] [ "Khmer", "PI:NAME:<NAME>END_PI" ] [ "Kimeru", "Muga rukiiri" ] [ "Kinyarwanda", "Muraho" ] [ "Konkani", "Dev Tuka Boro Dis Divum" ] [ "Korean", "Annyunghaseyo" ] [ "Kurdish Badini", "Spede bash" ] [ "Kurdish Sorani", "Beyani bash" ] [ "Lao", "Sabaidee" ] [ "Latin", "Bonum mane" ] [ "Latvian", "Labrit" ] [ "Lithuanian", "Labas rytas" ] [ "Lozi", "U zuhile" ] [ "Luganda", "Wasuze otyano" ] [ "Luo", "Oyawore" ] [ "Luxembourg", "Gudde moien" ] [ "Macedonian", "Dobro utro" ] [ "Malayalam", "Suprabhatham" ] [ "Malay", "Selamat pagi" ] [ "Maltese", "Għodwa it-tajPI: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", "PI:NAME:<NAME>END_PI" ] [ "Mongolian", "ÖglounPI:NAME:<NAME>END_PI" ] [ "PI:NAME:<NAME>END_PIavajo", "Yá'át'ééh abíní" ] [ "Ndebele", "Livukenjani" ] [ "Nepali", "Subha prabhat" ] [ "Northern Sotho", "Thobela" ] [ "Norwegian", "God morgen" ] [ "OwPI:NAME:<NAME>END_PIbo", "Wa lalapo" ] [ "PasPI:NAME:<NAME>END_PIo", "PI:NAME:<NAME>END_PI" ] [ "Persian", "Subbakhair" ] [ "Pingu", "Noot noot!" ] [ "Pirate", "Avast, ye scurvy dog" ] [ "Polish", "PI:NAME:<NAME>END_PIitaj" ] [ "Polynesian", "Ia ora na" ] [ "Portuguese", "Bom dia" ] [ "Punjabi", "Sat PI:NAME:<NAME>END_PI Akal" ] [ "Rapa Nui", "Iorana" ] [ "Romanian", "Buna dimineata" ] [ "Russian", "Dobroye utro" ] [ "Samoan", "Talofa lava" ] [ "Sanskrit", "Suprabhataha" ] [ "Sardinian", "Bona dia" ] [ "Serbian", "DPI:NAME:<NAME>END_PIro jutro" ] [ "Shona", "Mangwanani" ] [ "Sinhalese", "Suba Udesanak Wewa" ] [ "Slovak", "Dobré ráno" ] [ "Slovenian", "Dobro jutro" ] [ "Somalian", "Subax wanaagsan" ] [ "Southern Sotho", "Dumela" ] [ "Spanish", "Buenos dias" ] [ "Swahili", "Habari za asubuhi" ] [ "Swazi", "Sawubona" ] [ "Swedish", "God morgon" ] [ "Tagalog", "Magandang umaga" ] [ "Taiwanese", "Gau cha" ] [ "Tamil", "Kaalai Vannakkam" ] [ "Telugu", "Subhodayamu" ] [ "Tetum", "Dader diak" ] [ "Thai", "Aroon-Sawass" ] [ "Tibetan", "Nyado delek" ] [ "Tonga", "Mwabuka buti" ] [ "Tswana", "Dumela" ] [ "Twi", "Me ma wo maakye" ] [ "Turkish", "Günaydin" ] [ "Turkmen", "Ertiringiz haiyirli bolsun" ] [ "Ukrainian", "Dobri ranok" ] [ "Urdu", "Subha Ba-khair" ] [ "Uzbek", "Khairli kun" ] [ "Vietnamese", "Xin chao" ] [ "Welsh", "Bore da" ] [ "Xhosa", "Bhota" ] [ "Xitsonga", "Avuxeni" ] [ "Yoruba", "E karo" ] [ "Zulu", "Sawubona" ] [ "!Kung san", "Tuwa" ] [ "Australian", "G'day" ] [ "Klingon", "nuqneH" ] [ "tlhIngan Hol", "nuqneH" ] [ "Vulcan", "Dif-tor heh smusma" ] [ "Romulan", "Brhon mnekha" ] [ "Ferengi", "Welcome to our home. Please place your thumbprint on the legal waivers and deposit your admission fee in the slot by the door. Remember, my house is my house," ] [ "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", "Let it go," ] [ "PI:NAME:<NAME>END_PI", "Great PI:NAME:<NAME>END_PIcott," ] [ "PI:NAME:<NAME>END_PI", "http://33.media.tumblr.com/d27594fa4e9788bd23c98e1617737527/tumblr_n70xx6I4ZA1s9qnu2o2_500.gif" ] [ "PI:NAME:<NAME>END_PI", "Hello PI:NAME:<NAME>END_PI," ] [ "PI:NAME:<NAME>END_PI", "To infinity and beyond," ] [ "PI:NAME:<NAME>END_PI", "Thundercats Ho," ] [ "PI:NAME:<NAME>END_PI", "News team assemble!" ] [ "PI:NAME:<NAME>END_PI", "Good morning starshine, the earth says hello," ] [ "PI:NAME:<NAME>END_PI", "Hello, is there anybody in there? Just nod if you can hear me. Is there anyone at home?" ] [ "PI:NAME:<NAME>END_PI", "Hello! Is it me you're looking for?" ] [ "PI:NAME:<NAME>END_PI", "Good morning, good morning. Good morning ah" ] [ "PI:NAME:<NAME>END_PI", "Ollo?" ] [ "PI:NAME:<NAME>END_PI", "Never gonna give you up, Never gonna let you down, Never gonna run around and desert you, Never gonna make you cry, Never gonna say goodbye, Never gonna tell a lie and hurt you." ] [ "PI:NAME:<NAME>END_PI", "raaaaaahhgh raaaaaahhgh aaaaahnr" ] [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] [ "PI:NAME:<NAME>END_PI", "Eat my shorts" ] [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] [ "PI:NAME:<NAME>END_PI", "Ayyy" ] [ "PI:NAME:<NAME>END_PI", "yooooooooooooooooooooooooooooooooooooooooooooooo" ] [ "PI:NAME:<NAME>END_PI", "You must construct additional pylons," ] [ "PI:NAME:<NAME>END_PI", "Additional supply depots required," ] [ "PI:NAME:<NAME>END_PI", "Spawn more overlords," ] [ "A Flock of Seagulls", "And I ran, I ran so far away, I just ran, I ran all night and day, I couldn't get away," ] [ "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", "Heeeere's ..." ] [ "PI:NAME:<NAME>END_PI", "What'choo talkin' 'bout, " ] [ "PI:NAME:<NAME>END_PI", "Look! Up in the sky! It's a bird! It's a plane! It's" ] [ "Mission Impossible", "This tape will self-destruct in five seconds" ] [ "PI:NAME:<NAME>END_PI", "Live long and prosper" ] [ "PI:NAME:<NAME>END_PI", "Make it so" ] [ "PI:NAME:<NAME>END_PI", "Na-nu Na-nu" ] [ "PI:NAME:<NAME>END_PI", "Sniff my pantsu, " ] [ "Bitconnect", "Wassa-wassa-wassa-wassa-wassa-wassa-wassa-wassuuuuup! BitConneeeeeeeeect!" ] [ "PI:NAME:<NAME>END_PI", "Whatcha gonna do brother, when Hulkamania runs WILD on you?" ] [ "Office Space", "Uh, I just wanted to make sure you knew that we did start at the, um, usual time this morning. Yeah, it isn't a half day or anything like that"] ] class GreetingsRepository GREETINGS = [] constructor: -> for greeting in greetings [lang, greet] = greeting[0..1] GREETINGS[lang.toLowerCase()] = lang: lang, greeting: greet find: (name) -> GREETINGS[name.toLowerCase()] findOrRandom: (robot, name) -> name? && @find(name) || @random(robot) greeting: (name) -> @find(name)?.greeting all: -> GREETINGS names: -> for v of GREETINGS v.lang keys: -> Object.keys(GREETINGS) random: (robot) -> GREETINGS[robot.random @keys()] module.exports = GreetingsRepository
[ { "context": " return arr\n standard = ->\n arr = [\"Tony\", \"Mike\", \"John\", \"Tom\"]\n out = {}\n ", "end": 444, "score": 0.9997937679290771, "start": 440, "tag": "NAME", "value": "Tony" }, { "context": "n arr\n standard = ->\n arr = [\"Ton...
test/bench.coffee
wearefractal/iso
1
Isolate = require '../' Benchmark = require 'benchmark' should = require 'should' async = require 'async' require 'mocha' describe 'Isolate', -> describe 'benchmark', -> it 'should bench mad bonez', (done) -> @timeout '1000000000000' # test functions tiny = -> a = b = 1 return a+b simple = -> arr = [] arr.push "Test" return arr standard = -> arr = ["Tony", "Mike", "John", "Tom"] out = {} arr.forEach (el) -> out[el] = if el[0] is 'T' then "Starts with T" else "Is lame" return out complex = -> out = "" rand = -> (((1 + Math.random()) * 0x10000) | 0).toString 16 out += rand() for num in [0...10000] return out atiny = (cb) -> a = b = 1 cb a+b return asimple = (cb) -> arr = [] arr.push "Test" cb arr return astandard = (cb) -> arr = ["Tony", "Mike", "John", "Tom"] out = {} add = (el, cb) -> out[el] = if el[0] is 'T' then "Starts with T" else "Is lame" cb() async.forEach arr, add, -> cb out return acomplex = (cb) -> out = "" rand = -> (((1 + Math.random()) * 0x10000) | 0).toString 16 add = (el, cb) -> out += rand() cb() async.forEach [0...10000], add, -> cb out return tinyiso = new Isolate tiny simpleiso = new Isolate simple standardiso = new Isolate standard complexiso = new Isolate complex atinyiso = new Isolate atiny asimpleiso = new Isolate asimple astandardiso = new Isolate astandard acomplexiso = new Isolate acomplex suite = new Benchmark.Suite 'Isolate' suite.on "error", (event, bench) -> throw bench.error suite.on "cycle", (event, bench) -> console.log String bench suite.on "complete", (event, bench) -> done() suite.add "tiny", tiny suite.add "simple", simple suite.add "standard", standard suite.add "complex", complex suite.add "async tiny", -> atiny (s) -> suite.add "async simple", -> asimple (s) -> suite.add "async standard", -> astandard (s) -> suite.add "async complex", -> acomplex (s) -> suite.add "Isolate(tiny)", -> tinyiso.run() suite.add "Isolate(simple)", -> simpleiso.run() suite.add "Isolate(standard)", -> standardiso.run() suite.add "Isolate(complex)", -> complexiso.run() suite.add "async Isolate(tiny)", -> atinyiso.run (s) -> suite.add "async Isolate(simple)", -> asimpleiso.run (s) -> suite.add "async Isolate(standard)", -> astandardiso.run (s) -> suite.add "async Isolate(complex)", -> acomplexiso.run (s) -> suite.run async: true, queued: true
66265
Isolate = require '../' Benchmark = require 'benchmark' should = require 'should' async = require 'async' require 'mocha' describe 'Isolate', -> describe 'benchmark', -> it 'should bench mad bonez', (done) -> @timeout '1000000000000' # test functions tiny = -> a = b = 1 return a+b simple = -> arr = [] arr.push "Test" return arr standard = -> arr = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] out = {} arr.forEach (el) -> out[el] = if el[0] is 'T' then "Starts with T" else "Is lame" return out complex = -> out = "" rand = -> (((1 + Math.random()) * 0x10000) | 0).toString 16 out += rand() for num in [0...10000] return out atiny = (cb) -> a = b = 1 cb a+b return asimple = (cb) -> arr = [] arr.push "Test" cb arr return astandard = (cb) -> arr = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] out = {} add = (el, cb) -> out[el] = if el[0] is 'T' then "Starts with T" else "Is lame" cb() async.forEach arr, add, -> cb out return acomplex = (cb) -> out = "" rand = -> (((1 + Math.random()) * 0x10000) | 0).toString 16 add = (el, cb) -> out += rand() cb() async.forEach [0...10000], add, -> cb out return tinyiso = new Isolate tiny simpleiso = new Isolate simple standardiso = new Isolate standard complexiso = new Isolate complex atinyiso = new Isolate atiny asimpleiso = new Isolate asimple astandardiso = new Isolate astandard acomplexiso = new Isolate acomplex suite = new Benchmark.Suite 'Isolate' suite.on "error", (event, bench) -> throw bench.error suite.on "cycle", (event, bench) -> console.log String bench suite.on "complete", (event, bench) -> done() suite.add "tiny", tiny suite.add "simple", simple suite.add "standard", standard suite.add "complex", complex suite.add "async tiny", -> atiny (s) -> suite.add "async simple", -> asimple (s) -> suite.add "async standard", -> astandard (s) -> suite.add "async complex", -> acomplex (s) -> suite.add "Isolate(tiny)", -> tinyiso.run() suite.add "Isolate(simple)", -> simpleiso.run() suite.add "Isolate(standard)", -> standardiso.run() suite.add "Isolate(complex)", -> complexiso.run() suite.add "async Isolate(tiny)", -> atinyiso.run (s) -> suite.add "async Isolate(simple)", -> asimpleiso.run (s) -> suite.add "async Isolate(standard)", -> astandardiso.run (s) -> suite.add "async Isolate(complex)", -> acomplexiso.run (s) -> suite.run async: true, queued: true
true
Isolate = require '../' Benchmark = require 'benchmark' should = require 'should' async = require 'async' require 'mocha' describe 'Isolate', -> describe 'benchmark', -> it 'should bench mad bonez', (done) -> @timeout '1000000000000' # test functions tiny = -> a = b = 1 return a+b simple = -> arr = [] arr.push "Test" return arr standard = -> arr = ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] out = {} arr.forEach (el) -> out[el] = if el[0] is 'T' then "Starts with T" else "Is lame" return out complex = -> out = "" rand = -> (((1 + Math.random()) * 0x10000) | 0).toString 16 out += rand() for num in [0...10000] return out atiny = (cb) -> a = b = 1 cb a+b return asimple = (cb) -> arr = [] arr.push "Test" cb arr return astandard = (cb) -> arr = ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] out = {} add = (el, cb) -> out[el] = if el[0] is 'T' then "Starts with T" else "Is lame" cb() async.forEach arr, add, -> cb out return acomplex = (cb) -> out = "" rand = -> (((1 + Math.random()) * 0x10000) | 0).toString 16 add = (el, cb) -> out += rand() cb() async.forEach [0...10000], add, -> cb out return tinyiso = new Isolate tiny simpleiso = new Isolate simple standardiso = new Isolate standard complexiso = new Isolate complex atinyiso = new Isolate atiny asimpleiso = new Isolate asimple astandardiso = new Isolate astandard acomplexiso = new Isolate acomplex suite = new Benchmark.Suite 'Isolate' suite.on "error", (event, bench) -> throw bench.error suite.on "cycle", (event, bench) -> console.log String bench suite.on "complete", (event, bench) -> done() suite.add "tiny", tiny suite.add "simple", simple suite.add "standard", standard suite.add "complex", complex suite.add "async tiny", -> atiny (s) -> suite.add "async simple", -> asimple (s) -> suite.add "async standard", -> astandard (s) -> suite.add "async complex", -> acomplex (s) -> suite.add "Isolate(tiny)", -> tinyiso.run() suite.add "Isolate(simple)", -> simpleiso.run() suite.add "Isolate(standard)", -> standardiso.run() suite.add "Isolate(complex)", -> complexiso.run() suite.add "async Isolate(tiny)", -> atinyiso.run (s) -> suite.add "async Isolate(simple)", -> asimpleiso.run (s) -> suite.add "async Isolate(standard)", -> astandardiso.run (s) -> suite.add "async Isolate(complex)", -> acomplexiso.run (s) -> suite.run async: true, queued: true
[ { "context": "r\n\t\t@id = 1\n\t\titems = [\n\t\t\tpost_id: 1\n\t\t\tauthor: 'Hoh'\n\t\t\ttext: 'The quick brown'\n\t\t,\n\t\t\tpost_id: 1\n\t", "end": 1390, "score": 0.5361390709877014, "start": 1389, "tag": "NAME", "value": "H" }, { "context": "\n\t\t@id = 1\n\t\titems = [\n\t\t\tp...
example/emodels/index.coffee
codeboost/Skull.io
1
Skull = require '../../lib/skull-server' io = require 'socket.io' _ = require 'underscore' express = require 'express' class MemoryModel extends Skull.Model name: '/untitled' constructor: -> super @id = 0 @items = {} create: (data, callback, socket) -> data.id = @id++ @items[data.id] = data callback? null, data @emit 'create', data, socket update: (data, callback, socket) -> existing = @items[data.id] return callback "item doesn't exist" if not existing @items[data.id] = data callback? null, data @emit 'update', data, socket delete: (data, callback, socket) -> existing = @items[data.id] return callback "item doesn't exist" if not existing delete @items[data.id] callback? null, data @emit 'delete', data, socket read: (filter, callback, socket) -> items = _.toArray @items console.dir items callback null, items class Posts extends MemoryModel name: '/posts' constructor: -> super @id = 1 items = [ id: 1, title: 'One post' text: 'This is the first item' , id: 2, title: 'Second post' text: 'This is the text for second post' , id: 3, title: 'Third post' text: 'This is the text for third post' ] @create(item, null, null) for item in items class Comments extends MemoryModel name: '/post-comments' constructor: -> super @id = 1 items = [ post_id: 1 author: 'Hoh' text: 'The quick brown' , post_id: 1 author: 'Borba' text: 'Krala marla bumu kum' , post_id: 2 author: 'Juck' text: 'Kisi puck, pomada nada' , post_id: 3 author: 'JC' text: 'Musto rusto klomo dum, akaba mara ?' ] @create(item, null, null) for item in items read: (filter, callback, socket) -> console.log 'Comments read. Filter = %j', filter items = _.toArray @items items = _.filter items, (item) => @matchFilter filter, item console.dir items callback null, items class App constructor: (@skullServer) -> @io = @skullServer.io @app = @skullServer.of '/app' @app.addModel new Posts() #Name is taken from ImageModel::name @app.addModel new Comments() app = require('../express-core').init __dirname server = require('http').createServer(app) sio = io.listen server skullApp = new App (new Skull.Server(sio)) port = 4000 server.listen port, -> console.info 'Server started on port ' + port
141489
Skull = require '../../lib/skull-server' io = require 'socket.io' _ = require 'underscore' express = require 'express' class MemoryModel extends Skull.Model name: '/untitled' constructor: -> super @id = 0 @items = {} create: (data, callback, socket) -> data.id = @id++ @items[data.id] = data callback? null, data @emit 'create', data, socket update: (data, callback, socket) -> existing = @items[data.id] return callback "item doesn't exist" if not existing @items[data.id] = data callback? null, data @emit 'update', data, socket delete: (data, callback, socket) -> existing = @items[data.id] return callback "item doesn't exist" if not existing delete @items[data.id] callback? null, data @emit 'delete', data, socket read: (filter, callback, socket) -> items = _.toArray @items console.dir items callback null, items class Posts extends MemoryModel name: '/posts' constructor: -> super @id = 1 items = [ id: 1, title: 'One post' text: 'This is the first item' , id: 2, title: 'Second post' text: 'This is the text for second post' , id: 3, title: 'Third post' text: 'This is the text for third post' ] @create(item, null, null) for item in items class Comments extends MemoryModel name: '/post-comments' constructor: -> super @id = 1 items = [ post_id: 1 author: '<NAME>oh' text: 'The quick brown' , post_id: 1 author: '<NAME>' text: 'Krala marla bumu kum' , post_id: 2 author: 'Juck' text: 'Kisi puck, pomada nada' , post_id: 3 author: 'JC' text: 'Musto rusto klomo dum, akaba mara ?' ] @create(item, null, null) for item in items read: (filter, callback, socket) -> console.log 'Comments read. Filter = %j', filter items = _.toArray @items items = _.filter items, (item) => @matchFilter filter, item console.dir items callback null, items class App constructor: (@skullServer) -> @io = @skullServer.io @app = @skullServer.of '/app' @app.addModel new Posts() #Name is taken from ImageModel::name @app.addModel new Comments() app = require('../express-core').init __dirname server = require('http').createServer(app) sio = io.listen server skullApp = new App (new Skull.Server(sio)) port = 4000 server.listen port, -> console.info 'Server started on port ' + port
true
Skull = require '../../lib/skull-server' io = require 'socket.io' _ = require 'underscore' express = require 'express' class MemoryModel extends Skull.Model name: '/untitled' constructor: -> super @id = 0 @items = {} create: (data, callback, socket) -> data.id = @id++ @items[data.id] = data callback? null, data @emit 'create', data, socket update: (data, callback, socket) -> existing = @items[data.id] return callback "item doesn't exist" if not existing @items[data.id] = data callback? null, data @emit 'update', data, socket delete: (data, callback, socket) -> existing = @items[data.id] return callback "item doesn't exist" if not existing delete @items[data.id] callback? null, data @emit 'delete', data, socket read: (filter, callback, socket) -> items = _.toArray @items console.dir items callback null, items class Posts extends MemoryModel name: '/posts' constructor: -> super @id = 1 items = [ id: 1, title: 'One post' text: 'This is the first item' , id: 2, title: 'Second post' text: 'This is the text for second post' , id: 3, title: 'Third post' text: 'This is the text for third post' ] @create(item, null, null) for item in items class Comments extends MemoryModel name: '/post-comments' constructor: -> super @id = 1 items = [ post_id: 1 author: 'PI:NAME:<NAME>END_PIoh' text: 'The quick brown' , post_id: 1 author: 'PI:NAME:<NAME>END_PI' text: 'Krala marla bumu kum' , post_id: 2 author: 'Juck' text: 'Kisi puck, pomada nada' , post_id: 3 author: 'JC' text: 'Musto rusto klomo dum, akaba mara ?' ] @create(item, null, null) for item in items read: (filter, callback, socket) -> console.log 'Comments read. Filter = %j', filter items = _.toArray @items items = _.filter items, (item) => @matchFilter filter, item console.dir items callback null, items class App constructor: (@skullServer) -> @io = @skullServer.io @app = @skullServer.of '/app' @app.addModel new Posts() #Name is taken from ImageModel::name @app.addModel new Comments() app = require('../express-core').init __dirname server = require('http').createServer(app) sio = io.listen server skullApp = new App (new Skull.Server(sio)) port = 4000 server.listen port, -> console.info 'Server started on port ' + port
[ { "context": "###\n# The MIT License (MIT)\n#\n# Copyright (c) 2016 Thomas Steinholz\n#\n# Permission is hereby granted, free of charge,", "end": 144, "score": 0.9998524785041809, "start": 128, "tag": "NAME", "value": "Thomas Steinholz" } ]
src/stick-rpg.coffee
tsteinholz/StickRPG
3
################################################################################ # The MIT License (MIT) # # Copyright (c) 2016 Thomas Steinholz # # 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. ################################################################################ stage = null queue = null main = -> ############################################################################## # Initailize the Game ############################################################################## stage = new createjs.Stage 'RPG-Canvas' stage.mouseEventEnabled = true # Load Assets manifest = [ "assets/dev/test.jpg", { src:"assets/img/test.jpg", id:"test-screen" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" } ] queue = new createjs.LoadQueue() queue.installPlugin(createjs.Sound) queue.on "complete", handleLoadEvent, @ queue.loadManifest manifest createjs.Ticker.setFPS 30 createjs.Ticker.addEventListener "tick", handleTickEvent handleLoadEvent = -> image = queue.getResult "test-screen" stage.addChild image # TODO : Handle event loading handleTickEvent -> stage.update handleClickEvent = -> # TODO : Handle click event
9686
################################################################################ # The MIT License (MIT) # # Copyright (c) 2016 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ stage = null queue = null main = -> ############################################################################## # Initailize the Game ############################################################################## stage = new createjs.Stage 'RPG-Canvas' stage.mouseEventEnabled = true # Load Assets manifest = [ "assets/dev/test.jpg", { src:"assets/img/test.jpg", id:"test-screen" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" } ] queue = new createjs.LoadQueue() queue.installPlugin(createjs.Sound) queue.on "complete", handleLoadEvent, @ queue.loadManifest manifest createjs.Ticker.setFPS 30 createjs.Ticker.addEventListener "tick", handleTickEvent handleLoadEvent = -> image = queue.getResult "test-screen" stage.addChild image # TODO : Handle event loading handleTickEvent -> stage.update handleClickEvent = -> # TODO : Handle click event
true
################################################################################ # The MIT License (MIT) # # Copyright (c) 2016 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ stage = null queue = null main = -> ############################################################################## # Initailize the Game ############################################################################## stage = new createjs.Stage 'RPG-Canvas' stage.mouseEventEnabled = true # Load Assets manifest = [ "assets/dev/test.jpg", { src:"assets/img/test.jpg", id:"test-screen" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" }, "", { src:"", id:"" } ] queue = new createjs.LoadQueue() queue.installPlugin(createjs.Sound) queue.on "complete", handleLoadEvent, @ queue.loadManifest manifest createjs.Ticker.setFPS 30 createjs.Ticker.addEventListener "tick", handleTickEvent handleLoadEvent = -> image = queue.getResult "test-screen" stage.addChild image # TODO : Handle event loading handleTickEvent -> stage.update handleClickEvent = -> # TODO : Handle click event
[ { "context": " links', (test) -> \n md = \"\"\"\n [Hello][1], [Dave][2]\n\n [1]: http://google.com\n [2]: http://h", "end": 482, "score": 0.9996085166931152, "start": 478, "tag": "NAME", "value": "Dave" }, { "context": "test 'no links', (test) ->\n md = \"\"\"\n Hel...
test/link-number.coffee
evan-dickinson/md4mefi
1
(() -> md4mefi = window.md4mefi QUnit.module("Link number") # Unlike other test suites, we're not checking markdown against compiled HTML. # Instead, we're testing the return value of nextLinkNumber(). QUnit.test 'single link', (test) -> md = """ [Hello][1] [1]: http://google.com """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 2) QUnit.test 'two links', (test) -> md = """ [Hello][1], [Dave][2] [1]: http://google.com [2]: http://hal9000.biz """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 3) QUnit.test 'one text link', (test) -> md = """ I'd like a [good pizza][pizza], please. [pizza]: http://freshslice.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'two text links', (test) -> md = """ I'd like a [good pizza][pizza] and a [stale croissant][tims], please. [pizza]: http://freshslice.ca [tims]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'text and numeric links', (test) -> md = """ I'd like a [good pizza][pizza] and a [stale croissant][1], please. [pizza]: http://freshslice.ca [1]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 2) QUnit.test 'gaps in number sequence', (test) -> md = """ I'd like a [good pizza][4] and a [stale croissant][1], please. [4]: http://freshslice.ca [1]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 5) QUnit.test 'no links', (test) -> md = """ Hello, Dave """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'leading zeroes aren not octal', (test) -> md = """ [Thing one][010] [Thing two][011] [Thing three][012] [010]: http://google.ca [011]: http://google.com [012]: http://google.co.uk """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 13) QUnit.test 'numbers above and below the fold', (test) -> mdA = """ [1]: #one [2]: #two """ mdB = """ [3]: #three """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) QUnit.test 'numbers above the fold only', (test) -> mdA = """ [1]: #one """ mdB = """ blah blah blah """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 2) QUnit.test 'numbers below the fold only', (test) -> mdA = """ blah blah blah """ mdB = """ [1]: #one [2]: #two """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 3) QUnit.test 'no links above or below the fold', (test) -> mdA = """ blah blah blah """ mdB = """ woof woof woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 1) QUnit.test 'text references above the fold, numbers below', (test) -> mdA = """ blah [blah][yadda] blah [yadda]: #yadda """ mdB = """ woof [woof][1] woof [1]: #woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 2) QUnit.test 'number references above the fold, text refs below', (test) -> mdA = """ blah [blah][8] blah [8]: #blah """ mdB = """ woof [woof][] woof [woof]: #woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 9) QUnit.test 'conflicting numeric references - higher number above', (test) -> mdA = """ [blah][1] [blah][2] [blah][3] [1]: #blah1 [2]: #blah2 [3]: #blah3 """ mdB = """ [woof][1] [woof][2] woof [1]: #woof1 [2]: #woof2 """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) QUnit.test 'conflicting numeric references - higher number below', (test) -> mdA = """ [blah][1] [blah][2] blah [1]: #blah1 [2]: #blah2 """ mdB = """ [woof][1] [woof][2] [woof][3] [1]: #woof1 [2]: #woof2 [3]: #woof3 """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) )()
142136
(() -> md4mefi = window.md4mefi QUnit.module("Link number") # Unlike other test suites, we're not checking markdown against compiled HTML. # Instead, we're testing the return value of nextLinkNumber(). QUnit.test 'single link', (test) -> md = """ [Hello][1] [1]: http://google.com """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 2) QUnit.test 'two links', (test) -> md = """ [Hello][1], [<NAME>][2] [1]: http://google.com [2]: http://hal9000.biz """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 3) QUnit.test 'one text link', (test) -> md = """ I'd like a [good pizza][pizza], please. [pizza]: http://freshslice.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'two text links', (test) -> md = """ I'd like a [good pizza][pizza] and a [stale croissant][tims], please. [pizza]: http://freshslice.ca [tims]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'text and numeric links', (test) -> md = """ I'd like a [good pizza][pizza] and a [stale croissant][1], please. [pizza]: http://freshslice.ca [1]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 2) QUnit.test 'gaps in number sequence', (test) -> md = """ I'd like a [good pizza][4] and a [stale croissant][1], please. [4]: http://freshslice.ca [1]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 5) QUnit.test 'no links', (test) -> md = """ Hello, <NAME> """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'leading zeroes aren not octal', (test) -> md = """ [Thing one][010] [Thing two][011] [Thing three][012] [010]: http://google.ca [011]: http://google.com [012]: http://google.co.uk """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 13) QUnit.test 'numbers above and below the fold', (test) -> mdA = """ [1]: #one [2]: #two """ mdB = """ [3]: #three """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) QUnit.test 'numbers above the fold only', (test) -> mdA = """ [1]: #one """ mdB = """ blah blah blah """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 2) QUnit.test 'numbers below the fold only', (test) -> mdA = """ blah blah blah """ mdB = """ [1]: #one [2]: #two """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 3) QUnit.test 'no links above or below the fold', (test) -> mdA = """ blah blah blah """ mdB = """ woof woof woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 1) QUnit.test 'text references above the fold, numbers below', (test) -> mdA = """ blah [blah][yadda] blah [yadda]: #yadda """ mdB = """ woof [woof][1] woof [1]: #woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 2) QUnit.test 'number references above the fold, text refs below', (test) -> mdA = """ blah [blah][8] blah [8]: #blah """ mdB = """ woof [woof][] woof [woof]: #woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 9) QUnit.test 'conflicting numeric references - higher number above', (test) -> mdA = """ [blah][1] [blah][2] [blah][3] [1]: #blah1 [2]: #blah2 [3]: #blah3 """ mdB = """ [woof][1] [woof][2] woof [1]: #woof1 [2]: #woof2 """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) QUnit.test 'conflicting numeric references - higher number below', (test) -> mdA = """ [blah][1] [blah][2] blah [1]: #blah1 [2]: #blah2 """ mdB = """ [woof][1] [woof][2] [woof][3] [1]: #woof1 [2]: #woof2 [3]: #woof3 """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) )()
true
(() -> md4mefi = window.md4mefi QUnit.module("Link number") # Unlike other test suites, we're not checking markdown against compiled HTML. # Instead, we're testing the return value of nextLinkNumber(). QUnit.test 'single link', (test) -> md = """ [Hello][1] [1]: http://google.com """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 2) QUnit.test 'two links', (test) -> md = """ [Hello][1], [PI:NAME:<NAME>END_PI][2] [1]: http://google.com [2]: http://hal9000.biz """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 3) QUnit.test 'one text link', (test) -> md = """ I'd like a [good pizza][pizza], please. [pizza]: http://freshslice.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'two text links', (test) -> md = """ I'd like a [good pizza][pizza] and a [stale croissant][tims], please. [pizza]: http://freshslice.ca [tims]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'text and numeric links', (test) -> md = """ I'd like a [good pizza][pizza] and a [stale croissant][1], please. [pizza]: http://freshslice.ca [1]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 2) QUnit.test 'gaps in number sequence', (test) -> md = """ I'd like a [good pizza][4] and a [stale croissant][1], please. [4]: http://freshslice.ca [1]: http://timhortons.ca """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 5) QUnit.test 'no links', (test) -> md = """ Hello, PI:NAME:<NAME>END_PI """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 1) QUnit.test 'leading zeroes aren not octal', (test) -> md = """ [Thing one][010] [Thing two][011] [Thing three][012] [010]: http://google.ca [011]: http://google.com [012]: http://google.co.uk """ test.expect(1) next = md4mefi.nextLinkNumber(md, null) test.strictEqual(next, 13) QUnit.test 'numbers above and below the fold', (test) -> mdA = """ [1]: #one [2]: #two """ mdB = """ [3]: #three """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) QUnit.test 'numbers above the fold only', (test) -> mdA = """ [1]: #one """ mdB = """ blah blah blah """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 2) QUnit.test 'numbers below the fold only', (test) -> mdA = """ blah blah blah """ mdB = """ [1]: #one [2]: #two """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 3) QUnit.test 'no links above or below the fold', (test) -> mdA = """ blah blah blah """ mdB = """ woof woof woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 1) QUnit.test 'text references above the fold, numbers below', (test) -> mdA = """ blah [blah][yadda] blah [yadda]: #yadda """ mdB = """ woof [woof][1] woof [1]: #woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 2) QUnit.test 'number references above the fold, text refs below', (test) -> mdA = """ blah [blah][8] blah [8]: #blah """ mdB = """ woof [woof][] woof [woof]: #woof """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 9) QUnit.test 'conflicting numeric references - higher number above', (test) -> mdA = """ [blah][1] [blah][2] [blah][3] [1]: #blah1 [2]: #blah2 [3]: #blah3 """ mdB = """ [woof][1] [woof][2] woof [1]: #woof1 [2]: #woof2 """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) QUnit.test 'conflicting numeric references - higher number below', (test) -> mdA = """ [blah][1] [blah][2] blah [1]: #blah1 [2]: #blah2 """ mdB = """ [woof][1] [woof][2] [woof][3] [1]: #woof1 [2]: #woof2 [3]: #woof3 """ test.expect(1) next = md4mefi.nextLinkNumber(mdA, mdB) test.strictEqual(next, 4) )()
[ { "context": " showYAxis: false\n data: [\n key: 'Visit Date'\n values: values\n ]\n ]\n", "end": 15265, "score": 0.6346455812454224, "start": 15260, "tag": "NAME", "value": "Visit" } ]
app/javascripts/timeline.coffee
ohsu-qin/qiprofile
0
define ['angular', 'lodash', 'moment', 'helpers', 'chart', 'session'], (ng, _, moment) -> timeline = ng.module 'qiprofile.timeline', ['qiprofile.helpers', 'qiprofile.chart', 'qiprofile.session'] timeline.factory 'Timeline', ['ObjectHelper', 'Chart', 'Session', (ObjectHelper, Chart, Session) -> ###* * A helper function to calculate the effective treatment dates. * This function returns a [start, end] array, where: * * start is the moment start date integer * * end is the moment end date integer * The default end date is today. * * TODO - depict a treatment with no end date as an arrow. * * @method treatmentSpan * @param treatment the treatment object * @return the [start, end] array ### treatmentSpan = (treatment) -> start = treatment.startDate end = treatment.endDate or moment() [start, end] ###* * Helper function to calculate the earliest and latest session, * encounter and treatment dates. * * @method minMax * @param subject the target subject * @return the [earliest, latest] X axis range ### minMax = (subject) -> values = [] for trt in subject.treatments trtSpan = treatmentSpan(trt) for value in trtSpan values.push(value) for enc in subject.encounters values.push(enc.date) # Return the min and max date. [_.min(values), _.max(values)] ###* * @method xValues * @param subject the target subject * @return the date values to plot ### xValues = (subject) -> # The session dates are displayed as X axis tick marks. sessionDates = (sess.date for sess in subject.sessions) # The starting values are the sorted session dates. values = _.sortBy(sessionDates, (date) -> date.valueOf()) # The [earliest, latest] session, treatment or encounter # date. [low, high] = minMax(subject) # Add the other dates only if they do not coincide with # the session dates. if low.valueOf() != _.first(sessionDates).valueOf() values.unshift(low) if high.valueOf() != _.last(sessionDates).valueOf() values.push(high) # Return the date values. values ###* * Decorates the timeline as follows: * * Add the session hyperlinks, encounter dates and treatment * start-end bars. * * Rotate the date x-axis tick labels * * Note: The session hyperlinks are ui-sref attributes. However, * D3 mutates the DOM after the Angular digest cycle. Consequently, * the callback must call Angular $compile with the current scope * on each new hyperlink.ui-sref directive. * * @method decorate * @param chart the timeline chart element * @param subject the displayed subject * @param scope the (isolated) chart scope containing the options * and data * @param $state the ui-router $state ### decorate: (chart, subject, scope, $state) -> # The min and max X values. The dates are sorted by the # configure method. values = scope.data[0].values low = _.first(values) high = _.last(values) # The treatment bar height, in em units TREATMENT_BAR_HEIGHT = 1 # A treatment is designated by the HTML nabla special character # (the wedge-like math del operator). TREATMENT_SYMBOL = '\u2207' # The Session Detail state. SESSION_DETAIL_STATE = 'quip.collection.subject.session' ###* * Adds the session hyperlinks above the timeline. The template * sets the callback attribute to this function. The new anchor * elements are positioned dy em units above the timeline, * plus a small padding. This allows for displaying the treatment * bars and encounter points between the timeline and the * hyperlinks. * * @method addSessionDetailLinks * @param sessions the subject sessions * @param xAxis the chart SVG X axis D3 selection * @param low the minimum date * @param high the maximum date * @param dy the optional y offset in em units ### addSessionDetailLinks = (sessions, xAxis, low, high, dy=0) -> ###* * Makes a new ui-sref anchor element that hyperlinks to the given * session detail page. * * @method createSessionDetailLink * @param session the hyperlink target session * @param tick the X axis tick mark ### createSessionDetailLink = (session, tick) -> # Make a new SVG text element to hold the session number. text = tick.append('text') # Position the session number a bit to right and above the tick # mark, scooched up by the dy amount. text.attr('dx', '-.2em').attr('dy', "-#{ 0.5 + dy }em") text.style('text-anchor: middle') # The text content is the session number. text.text(session.number) # The Session Detail state parameters. params = project: subject.project collection: subject.collection subject: subject.number session: session.number # The hyperlink click event handler. handler = -> $state.go(SESSION_DETAIL_STATE, params) # Wrap the text element in a hyperlink. Chart.d3Hyperlink(text, handler) # The tick marks. ticks = xAxis.selectAll('.tick') # The session milliseconds. sessionMillis = (session.date.valueOf() for session in sessions) ###* * @method isSessionDate * @param date the date to check * @return whether the date is a session date ### isSessionDate = (date) -> _.includes(sessionMillis, date.valueOf()) # Make the Session Detail page links. # # The odd D3 *each* operator calls this function with # *this* bound to the D3 tick selection and arguments # the element "data", as D3 chooses to call it, and # the iteration number. The element data in this # case is the date. We want the D3 tick selection, # which is given by d3.select(this). # # Note that we can't simply iterate over the ticks in a # for loop, since that is a D3 taboo which results in # garbage. sessionIndex = 0 ticks.each (date, i) -> if isSessionDate(date) tick = d3.select(this) createSessionDetailLink(sessions[sessionIndex], tick) sessionIndex++ ###* * Inserts an SVG bar for each treatment above the timeline. * * @method addTreatmentBars * @param xAxisNode the chart SVG x axis element * @param options the chart options ### addTreatmentBars = (xAxis, low, high) -> # The .nv-background xAxis contained in the X axis parent # spaces the X axis. xAxisNode = xAxis.node() parent = d3.select(xAxisNode.parentNode) background = parent.select('.nv-background') spacer = background.select('rect') axisWidth = spacer.attr('width') # The date offset-to-pixel scaling factor. factor = axisWidth / (high - low) for trt in subject.treatments [start, end] = treatmentSpan(trt) left = (start - low) * factor width = (end - start) * factor # Allow for a 6-pixel minimum width. if not width left = left - 3 width = 6 # Place the new bar rectangle element in the DOM # before the x axis element. bar = parent.insert('svg:rect', -> xAxisNode) # Set the bar dimensions. bar.attr('height', "#{ TREATMENT_BAR_HEIGHT }em") bar.attr('width', width) # Set the bar style. bar.classed("qi-timeline-#{ trt.treatmentType.toLowerCase() }", true) # Position the bar. bar.attr('x', left) bar.attr('y', "-#{ TREATMENT_BAR_HEIGHT }em") ###* * Inserts a marker for each clinical encounter above the * timeline. * * @method addClinicalEncounters * @param element the chart X axis D3 selection * @param low the minimum date * @param high the maximum date ### addClinicalEncounters = (xAxis, low, high) -> # The .nv-background xAxis contained in the X axis parent # spaces the X axis. xAxisNode = xAxis.node() parent = d3.select(xAxisNode.parentNode) background = parent.select('.nv-background') spacer = background.select('rect') axisWidth = spacer.attr('width') # The X axis line element is contained in the axis parent. line = parent.select('.nv-series-0') # Unwrap the DOM element. lineNode = line.node() # The date offset-to-pixel scaling factor. factor = axisWidth / (high - low) # Insert the encounters. for enc in subject.clinicalEncounters date = enc.date # The pixel offset. offset = (date - low) * factor # Place the new text element in the DOM before the # x axis element. Scooch it over 6 pixels to center # the marker. text = parent.insert('svg:text') text.attr('x', Math.floor(offset) - 6) # Set the text style, e.g. .qi-timeline-surgery. text.classed("qi-timeline-#{ enc.title.toLowerCase() }", true) # Set the text content to a marker, specifically the HTML # nabla math special character (the wedge-like del operator). text.text(TREATMENT_SYMBOL) ###* * Adds the treatment and encounter legend directly before the * SVG element. * * @method addLegend * @param svg the SVG D3 selection ### addLegend = (svg) -> addTreatmentLegend = (parent) -> # If there are no treatments, then bail out. trts = subject.treatments return if not trts.length # Place the legend line. p = parent.insert('p', -> svg.node()) p.text('Treatments: ') p.classed({'col-md-offset-5': true, 'font-size: small': true}) # Sort by start date. sorted = _.sortBy(trts, (trt) -> trt.start_date.valueOf()) # The treatment labels. labels = _.uniq(trt.treatment_type for trt in sorted) # The treatment label size. label_lengths = (label.length for label in labels) len = _.max(label_lengths) + 2 for label in labels # Place the new span element. span = p.append('span') # The legend style. span.classed("qi-timeline-#{ label.toLowerCase() }", true) # The span content is the treatment type label. span.text(label) addEncounterLegend = (parent) -> # Bail if no encounters are displayed. encs = subject.clinicalEncounters return if not encs.length # Place the legend line. p = parent.insert('p', -> svg.node()) p.text('Encounters: ') p.classed({'col-md-offset-5': true, 'font-size: small': true}) # Sort by start date. sorted = _.sortBy(encs, (enc) -> enc.date.valueOf()) # The encounter labels. labels = _.uniq(enc.title for enc in sorted) for label in labels # Place the new span element. span = p.append('span') # The legend style. span.classed("qi-timeline-#{ label.toLowerCase() }", true) # The span content is the symbol which designates the encounter # followed by the encounter type. span.text(TREATMENT_SYMBOL + label) # The legend is inserted directly before the svg element. svgNode = svg.node() parent = d3.select(svgNode.parentNode) addTreatmentLegend(parent) addEncounterLegend(parent) # Find the SVG element. svg = d3.select('svg') if not svg? throw new ReferenceError("The svg element was not found.") # The X axis element. xAxis = svg.select('.nv-x') # The session hyperlink vertical offset. if _.some(subject.treatments) or _.some(subject.clinicalEncounters) dy = TREATMENT_BAR_HEIGHT else dy = 0 # Scooch the X axis label up to work around the # nvd3 or d3 bug described in the config rotateLabels # setting below. workAroundAxisLabelBug = (xAxis) -> label = xAxis.select('.nv-axislabel') y = label.attr('y') label.attr('y', y - 10) # The earliest and latest dates. [low, high] = minMax(subject) # Decorate the chart. addTreatmentBars(xAxis, low, high) addClinicalEncounters(xAxis, low, high) addSessionDetailLinks(subject.sessions, xAxis, low, high, dy) addLegend(svg) workAroundAxisLabelBug(xAxis) ###* * @method configure * @param subject the subject to display * @return the nvd3 chart configuration ### configure: (subject) -> # The values to plot. values = xValues(subject) # Return the {options, data} configuration. options: chart: type: 'lineChart' height: 83 # We roll our own legend in the callback. showLegend: false # Note: the trivial X value accessor works around the # following nvd3 bug: # * If there is no x chart accessor option, then the chart # render results in an obscure error in the d3 voronoi # tesselation: # Cannot read property 'x' of null # This bug possibly results from a nvd3 expectation that # if there is a y option then there is also an x option. # The work-around is to supply a trivial x option. # TODO - isolate this bug with a nvd3 test case and report # it to nvd3. x: (date) -> date xAxis: axisLabel: 'Visit Date' showMaxMin: false tickValues: values tickFormat: Chart.formatDate # Note - due to a nvd3 or d3 bug, rotating the labels # forces the axis out of the chart display. Adding a # margin has no effect. The only recourse is to hammer # the DOM afterwards to move the label up. rotateLabels: -30 # Note: a nvd3 bug clobbers the custom tickSize set below. # The work-around is to reduce the height to a just-so # value that loses the tick marks (yuck). Setting the # xAxis height would be an alternative, but this has # no effect, probably due to another nvd3 bug. # TODO - file a nvd3 bug and revisit this in 2017. #tickSize: 4 tooltip: enabled: false xScale: d3.time.scale() # The session dates align on the X axis, # hence the Y value is always zero. y: -> 0 showYAxis: false data: [ key: 'Visit Date' values: values ] ]
46244
define ['angular', 'lodash', 'moment', 'helpers', 'chart', 'session'], (ng, _, moment) -> timeline = ng.module 'qiprofile.timeline', ['qiprofile.helpers', 'qiprofile.chart', 'qiprofile.session'] timeline.factory 'Timeline', ['ObjectHelper', 'Chart', 'Session', (ObjectHelper, Chart, Session) -> ###* * A helper function to calculate the effective treatment dates. * This function returns a [start, end] array, where: * * start is the moment start date integer * * end is the moment end date integer * The default end date is today. * * TODO - depict a treatment with no end date as an arrow. * * @method treatmentSpan * @param treatment the treatment object * @return the [start, end] array ### treatmentSpan = (treatment) -> start = treatment.startDate end = treatment.endDate or moment() [start, end] ###* * Helper function to calculate the earliest and latest session, * encounter and treatment dates. * * @method minMax * @param subject the target subject * @return the [earliest, latest] X axis range ### minMax = (subject) -> values = [] for trt in subject.treatments trtSpan = treatmentSpan(trt) for value in trtSpan values.push(value) for enc in subject.encounters values.push(enc.date) # Return the min and max date. [_.min(values), _.max(values)] ###* * @method xValues * @param subject the target subject * @return the date values to plot ### xValues = (subject) -> # The session dates are displayed as X axis tick marks. sessionDates = (sess.date for sess in subject.sessions) # The starting values are the sorted session dates. values = _.sortBy(sessionDates, (date) -> date.valueOf()) # The [earliest, latest] session, treatment or encounter # date. [low, high] = minMax(subject) # Add the other dates only if they do not coincide with # the session dates. if low.valueOf() != _.first(sessionDates).valueOf() values.unshift(low) if high.valueOf() != _.last(sessionDates).valueOf() values.push(high) # Return the date values. values ###* * Decorates the timeline as follows: * * Add the session hyperlinks, encounter dates and treatment * start-end bars. * * Rotate the date x-axis tick labels * * Note: The session hyperlinks are ui-sref attributes. However, * D3 mutates the DOM after the Angular digest cycle. Consequently, * the callback must call Angular $compile with the current scope * on each new hyperlink.ui-sref directive. * * @method decorate * @param chart the timeline chart element * @param subject the displayed subject * @param scope the (isolated) chart scope containing the options * and data * @param $state the ui-router $state ### decorate: (chart, subject, scope, $state) -> # The min and max X values. The dates are sorted by the # configure method. values = scope.data[0].values low = _.first(values) high = _.last(values) # The treatment bar height, in em units TREATMENT_BAR_HEIGHT = 1 # A treatment is designated by the HTML nabla special character # (the wedge-like math del operator). TREATMENT_SYMBOL = '\u2207' # The Session Detail state. SESSION_DETAIL_STATE = 'quip.collection.subject.session' ###* * Adds the session hyperlinks above the timeline. The template * sets the callback attribute to this function. The new anchor * elements are positioned dy em units above the timeline, * plus a small padding. This allows for displaying the treatment * bars and encounter points between the timeline and the * hyperlinks. * * @method addSessionDetailLinks * @param sessions the subject sessions * @param xAxis the chart SVG X axis D3 selection * @param low the minimum date * @param high the maximum date * @param dy the optional y offset in em units ### addSessionDetailLinks = (sessions, xAxis, low, high, dy=0) -> ###* * Makes a new ui-sref anchor element that hyperlinks to the given * session detail page. * * @method createSessionDetailLink * @param session the hyperlink target session * @param tick the X axis tick mark ### createSessionDetailLink = (session, tick) -> # Make a new SVG text element to hold the session number. text = tick.append('text') # Position the session number a bit to right and above the tick # mark, scooched up by the dy amount. text.attr('dx', '-.2em').attr('dy', "-#{ 0.5 + dy }em") text.style('text-anchor: middle') # The text content is the session number. text.text(session.number) # The Session Detail state parameters. params = project: subject.project collection: subject.collection subject: subject.number session: session.number # The hyperlink click event handler. handler = -> $state.go(SESSION_DETAIL_STATE, params) # Wrap the text element in a hyperlink. Chart.d3Hyperlink(text, handler) # The tick marks. ticks = xAxis.selectAll('.tick') # The session milliseconds. sessionMillis = (session.date.valueOf() for session in sessions) ###* * @method isSessionDate * @param date the date to check * @return whether the date is a session date ### isSessionDate = (date) -> _.includes(sessionMillis, date.valueOf()) # Make the Session Detail page links. # # The odd D3 *each* operator calls this function with # *this* bound to the D3 tick selection and arguments # the element "data", as D3 chooses to call it, and # the iteration number. The element data in this # case is the date. We want the D3 tick selection, # which is given by d3.select(this). # # Note that we can't simply iterate over the ticks in a # for loop, since that is a D3 taboo which results in # garbage. sessionIndex = 0 ticks.each (date, i) -> if isSessionDate(date) tick = d3.select(this) createSessionDetailLink(sessions[sessionIndex], tick) sessionIndex++ ###* * Inserts an SVG bar for each treatment above the timeline. * * @method addTreatmentBars * @param xAxisNode the chart SVG x axis element * @param options the chart options ### addTreatmentBars = (xAxis, low, high) -> # The .nv-background xAxis contained in the X axis parent # spaces the X axis. xAxisNode = xAxis.node() parent = d3.select(xAxisNode.parentNode) background = parent.select('.nv-background') spacer = background.select('rect') axisWidth = spacer.attr('width') # The date offset-to-pixel scaling factor. factor = axisWidth / (high - low) for trt in subject.treatments [start, end] = treatmentSpan(trt) left = (start - low) * factor width = (end - start) * factor # Allow for a 6-pixel minimum width. if not width left = left - 3 width = 6 # Place the new bar rectangle element in the DOM # before the x axis element. bar = parent.insert('svg:rect', -> xAxisNode) # Set the bar dimensions. bar.attr('height', "#{ TREATMENT_BAR_HEIGHT }em") bar.attr('width', width) # Set the bar style. bar.classed("qi-timeline-#{ trt.treatmentType.toLowerCase() }", true) # Position the bar. bar.attr('x', left) bar.attr('y', "-#{ TREATMENT_BAR_HEIGHT }em") ###* * Inserts a marker for each clinical encounter above the * timeline. * * @method addClinicalEncounters * @param element the chart X axis D3 selection * @param low the minimum date * @param high the maximum date ### addClinicalEncounters = (xAxis, low, high) -> # The .nv-background xAxis contained in the X axis parent # spaces the X axis. xAxisNode = xAxis.node() parent = d3.select(xAxisNode.parentNode) background = parent.select('.nv-background') spacer = background.select('rect') axisWidth = spacer.attr('width') # The X axis line element is contained in the axis parent. line = parent.select('.nv-series-0') # Unwrap the DOM element. lineNode = line.node() # The date offset-to-pixel scaling factor. factor = axisWidth / (high - low) # Insert the encounters. for enc in subject.clinicalEncounters date = enc.date # The pixel offset. offset = (date - low) * factor # Place the new text element in the DOM before the # x axis element. Scooch it over 6 pixels to center # the marker. text = parent.insert('svg:text') text.attr('x', Math.floor(offset) - 6) # Set the text style, e.g. .qi-timeline-surgery. text.classed("qi-timeline-#{ enc.title.toLowerCase() }", true) # Set the text content to a marker, specifically the HTML # nabla math special character (the wedge-like del operator). text.text(TREATMENT_SYMBOL) ###* * Adds the treatment and encounter legend directly before the * SVG element. * * @method addLegend * @param svg the SVG D3 selection ### addLegend = (svg) -> addTreatmentLegend = (parent) -> # If there are no treatments, then bail out. trts = subject.treatments return if not trts.length # Place the legend line. p = parent.insert('p', -> svg.node()) p.text('Treatments: ') p.classed({'col-md-offset-5': true, 'font-size: small': true}) # Sort by start date. sorted = _.sortBy(trts, (trt) -> trt.start_date.valueOf()) # The treatment labels. labels = _.uniq(trt.treatment_type for trt in sorted) # The treatment label size. label_lengths = (label.length for label in labels) len = _.max(label_lengths) + 2 for label in labels # Place the new span element. span = p.append('span') # The legend style. span.classed("qi-timeline-#{ label.toLowerCase() }", true) # The span content is the treatment type label. span.text(label) addEncounterLegend = (parent) -> # Bail if no encounters are displayed. encs = subject.clinicalEncounters return if not encs.length # Place the legend line. p = parent.insert('p', -> svg.node()) p.text('Encounters: ') p.classed({'col-md-offset-5': true, 'font-size: small': true}) # Sort by start date. sorted = _.sortBy(encs, (enc) -> enc.date.valueOf()) # The encounter labels. labels = _.uniq(enc.title for enc in sorted) for label in labels # Place the new span element. span = p.append('span') # The legend style. span.classed("qi-timeline-#{ label.toLowerCase() }", true) # The span content is the symbol which designates the encounter # followed by the encounter type. span.text(TREATMENT_SYMBOL + label) # The legend is inserted directly before the svg element. svgNode = svg.node() parent = d3.select(svgNode.parentNode) addTreatmentLegend(parent) addEncounterLegend(parent) # Find the SVG element. svg = d3.select('svg') if not svg? throw new ReferenceError("The svg element was not found.") # The X axis element. xAxis = svg.select('.nv-x') # The session hyperlink vertical offset. if _.some(subject.treatments) or _.some(subject.clinicalEncounters) dy = TREATMENT_BAR_HEIGHT else dy = 0 # Scooch the X axis label up to work around the # nvd3 or d3 bug described in the config rotateLabels # setting below. workAroundAxisLabelBug = (xAxis) -> label = xAxis.select('.nv-axislabel') y = label.attr('y') label.attr('y', y - 10) # The earliest and latest dates. [low, high] = minMax(subject) # Decorate the chart. addTreatmentBars(xAxis, low, high) addClinicalEncounters(xAxis, low, high) addSessionDetailLinks(subject.sessions, xAxis, low, high, dy) addLegend(svg) workAroundAxisLabelBug(xAxis) ###* * @method configure * @param subject the subject to display * @return the nvd3 chart configuration ### configure: (subject) -> # The values to plot. values = xValues(subject) # Return the {options, data} configuration. options: chart: type: 'lineChart' height: 83 # We roll our own legend in the callback. showLegend: false # Note: the trivial X value accessor works around the # following nvd3 bug: # * If there is no x chart accessor option, then the chart # render results in an obscure error in the d3 voronoi # tesselation: # Cannot read property 'x' of null # This bug possibly results from a nvd3 expectation that # if there is a y option then there is also an x option. # The work-around is to supply a trivial x option. # TODO - isolate this bug with a nvd3 test case and report # it to nvd3. x: (date) -> date xAxis: axisLabel: 'Visit Date' showMaxMin: false tickValues: values tickFormat: Chart.formatDate # Note - due to a nvd3 or d3 bug, rotating the labels # forces the axis out of the chart display. Adding a # margin has no effect. The only recourse is to hammer # the DOM afterwards to move the label up. rotateLabels: -30 # Note: a nvd3 bug clobbers the custom tickSize set below. # The work-around is to reduce the height to a just-so # value that loses the tick marks (yuck). Setting the # xAxis height would be an alternative, but this has # no effect, probably due to another nvd3 bug. # TODO - file a nvd3 bug and revisit this in 2017. #tickSize: 4 tooltip: enabled: false xScale: d3.time.scale() # The session dates align on the X axis, # hence the Y value is always zero. y: -> 0 showYAxis: false data: [ key: '<NAME> Date' values: values ] ]
true
define ['angular', 'lodash', 'moment', 'helpers', 'chart', 'session'], (ng, _, moment) -> timeline = ng.module 'qiprofile.timeline', ['qiprofile.helpers', 'qiprofile.chart', 'qiprofile.session'] timeline.factory 'Timeline', ['ObjectHelper', 'Chart', 'Session', (ObjectHelper, Chart, Session) -> ###* * A helper function to calculate the effective treatment dates. * This function returns a [start, end] array, where: * * start is the moment start date integer * * end is the moment end date integer * The default end date is today. * * TODO - depict a treatment with no end date as an arrow. * * @method treatmentSpan * @param treatment the treatment object * @return the [start, end] array ### treatmentSpan = (treatment) -> start = treatment.startDate end = treatment.endDate or moment() [start, end] ###* * Helper function to calculate the earliest and latest session, * encounter and treatment dates. * * @method minMax * @param subject the target subject * @return the [earliest, latest] X axis range ### minMax = (subject) -> values = [] for trt in subject.treatments trtSpan = treatmentSpan(trt) for value in trtSpan values.push(value) for enc in subject.encounters values.push(enc.date) # Return the min and max date. [_.min(values), _.max(values)] ###* * @method xValues * @param subject the target subject * @return the date values to plot ### xValues = (subject) -> # The session dates are displayed as X axis tick marks. sessionDates = (sess.date for sess in subject.sessions) # The starting values are the sorted session dates. values = _.sortBy(sessionDates, (date) -> date.valueOf()) # The [earliest, latest] session, treatment or encounter # date. [low, high] = minMax(subject) # Add the other dates only if they do not coincide with # the session dates. if low.valueOf() != _.first(sessionDates).valueOf() values.unshift(low) if high.valueOf() != _.last(sessionDates).valueOf() values.push(high) # Return the date values. values ###* * Decorates the timeline as follows: * * Add the session hyperlinks, encounter dates and treatment * start-end bars. * * Rotate the date x-axis tick labels * * Note: The session hyperlinks are ui-sref attributes. However, * D3 mutates the DOM after the Angular digest cycle. Consequently, * the callback must call Angular $compile with the current scope * on each new hyperlink.ui-sref directive. * * @method decorate * @param chart the timeline chart element * @param subject the displayed subject * @param scope the (isolated) chart scope containing the options * and data * @param $state the ui-router $state ### decorate: (chart, subject, scope, $state) -> # The min and max X values. The dates are sorted by the # configure method. values = scope.data[0].values low = _.first(values) high = _.last(values) # The treatment bar height, in em units TREATMENT_BAR_HEIGHT = 1 # A treatment is designated by the HTML nabla special character # (the wedge-like math del operator). TREATMENT_SYMBOL = '\u2207' # The Session Detail state. SESSION_DETAIL_STATE = 'quip.collection.subject.session' ###* * Adds the session hyperlinks above the timeline. The template * sets the callback attribute to this function. The new anchor * elements are positioned dy em units above the timeline, * plus a small padding. This allows for displaying the treatment * bars and encounter points between the timeline and the * hyperlinks. * * @method addSessionDetailLinks * @param sessions the subject sessions * @param xAxis the chart SVG X axis D3 selection * @param low the minimum date * @param high the maximum date * @param dy the optional y offset in em units ### addSessionDetailLinks = (sessions, xAxis, low, high, dy=0) -> ###* * Makes a new ui-sref anchor element that hyperlinks to the given * session detail page. * * @method createSessionDetailLink * @param session the hyperlink target session * @param tick the X axis tick mark ### createSessionDetailLink = (session, tick) -> # Make a new SVG text element to hold the session number. text = tick.append('text') # Position the session number a bit to right and above the tick # mark, scooched up by the dy amount. text.attr('dx', '-.2em').attr('dy', "-#{ 0.5 + dy }em") text.style('text-anchor: middle') # The text content is the session number. text.text(session.number) # The Session Detail state parameters. params = project: subject.project collection: subject.collection subject: subject.number session: session.number # The hyperlink click event handler. handler = -> $state.go(SESSION_DETAIL_STATE, params) # Wrap the text element in a hyperlink. Chart.d3Hyperlink(text, handler) # The tick marks. ticks = xAxis.selectAll('.tick') # The session milliseconds. sessionMillis = (session.date.valueOf() for session in sessions) ###* * @method isSessionDate * @param date the date to check * @return whether the date is a session date ### isSessionDate = (date) -> _.includes(sessionMillis, date.valueOf()) # Make the Session Detail page links. # # The odd D3 *each* operator calls this function with # *this* bound to the D3 tick selection and arguments # the element "data", as D3 chooses to call it, and # the iteration number. The element data in this # case is the date. We want the D3 tick selection, # which is given by d3.select(this). # # Note that we can't simply iterate over the ticks in a # for loop, since that is a D3 taboo which results in # garbage. sessionIndex = 0 ticks.each (date, i) -> if isSessionDate(date) tick = d3.select(this) createSessionDetailLink(sessions[sessionIndex], tick) sessionIndex++ ###* * Inserts an SVG bar for each treatment above the timeline. * * @method addTreatmentBars * @param xAxisNode the chart SVG x axis element * @param options the chart options ### addTreatmentBars = (xAxis, low, high) -> # The .nv-background xAxis contained in the X axis parent # spaces the X axis. xAxisNode = xAxis.node() parent = d3.select(xAxisNode.parentNode) background = parent.select('.nv-background') spacer = background.select('rect') axisWidth = spacer.attr('width') # The date offset-to-pixel scaling factor. factor = axisWidth / (high - low) for trt in subject.treatments [start, end] = treatmentSpan(trt) left = (start - low) * factor width = (end - start) * factor # Allow for a 6-pixel minimum width. if not width left = left - 3 width = 6 # Place the new bar rectangle element in the DOM # before the x axis element. bar = parent.insert('svg:rect', -> xAxisNode) # Set the bar dimensions. bar.attr('height', "#{ TREATMENT_BAR_HEIGHT }em") bar.attr('width', width) # Set the bar style. bar.classed("qi-timeline-#{ trt.treatmentType.toLowerCase() }", true) # Position the bar. bar.attr('x', left) bar.attr('y', "-#{ TREATMENT_BAR_HEIGHT }em") ###* * Inserts a marker for each clinical encounter above the * timeline. * * @method addClinicalEncounters * @param element the chart X axis D3 selection * @param low the minimum date * @param high the maximum date ### addClinicalEncounters = (xAxis, low, high) -> # The .nv-background xAxis contained in the X axis parent # spaces the X axis. xAxisNode = xAxis.node() parent = d3.select(xAxisNode.parentNode) background = parent.select('.nv-background') spacer = background.select('rect') axisWidth = spacer.attr('width') # The X axis line element is contained in the axis parent. line = parent.select('.nv-series-0') # Unwrap the DOM element. lineNode = line.node() # The date offset-to-pixel scaling factor. factor = axisWidth / (high - low) # Insert the encounters. for enc in subject.clinicalEncounters date = enc.date # The pixel offset. offset = (date - low) * factor # Place the new text element in the DOM before the # x axis element. Scooch it over 6 pixels to center # the marker. text = parent.insert('svg:text') text.attr('x', Math.floor(offset) - 6) # Set the text style, e.g. .qi-timeline-surgery. text.classed("qi-timeline-#{ enc.title.toLowerCase() }", true) # Set the text content to a marker, specifically the HTML # nabla math special character (the wedge-like del operator). text.text(TREATMENT_SYMBOL) ###* * Adds the treatment and encounter legend directly before the * SVG element. * * @method addLegend * @param svg the SVG D3 selection ### addLegend = (svg) -> addTreatmentLegend = (parent) -> # If there are no treatments, then bail out. trts = subject.treatments return if not trts.length # Place the legend line. p = parent.insert('p', -> svg.node()) p.text('Treatments: ') p.classed({'col-md-offset-5': true, 'font-size: small': true}) # Sort by start date. sorted = _.sortBy(trts, (trt) -> trt.start_date.valueOf()) # The treatment labels. labels = _.uniq(trt.treatment_type for trt in sorted) # The treatment label size. label_lengths = (label.length for label in labels) len = _.max(label_lengths) + 2 for label in labels # Place the new span element. span = p.append('span') # The legend style. span.classed("qi-timeline-#{ label.toLowerCase() }", true) # The span content is the treatment type label. span.text(label) addEncounterLegend = (parent) -> # Bail if no encounters are displayed. encs = subject.clinicalEncounters return if not encs.length # Place the legend line. p = parent.insert('p', -> svg.node()) p.text('Encounters: ') p.classed({'col-md-offset-5': true, 'font-size: small': true}) # Sort by start date. sorted = _.sortBy(encs, (enc) -> enc.date.valueOf()) # The encounter labels. labels = _.uniq(enc.title for enc in sorted) for label in labels # Place the new span element. span = p.append('span') # The legend style. span.classed("qi-timeline-#{ label.toLowerCase() }", true) # The span content is the symbol which designates the encounter # followed by the encounter type. span.text(TREATMENT_SYMBOL + label) # The legend is inserted directly before the svg element. svgNode = svg.node() parent = d3.select(svgNode.parentNode) addTreatmentLegend(parent) addEncounterLegend(parent) # Find the SVG element. svg = d3.select('svg') if not svg? throw new ReferenceError("The svg element was not found.") # The X axis element. xAxis = svg.select('.nv-x') # The session hyperlink vertical offset. if _.some(subject.treatments) or _.some(subject.clinicalEncounters) dy = TREATMENT_BAR_HEIGHT else dy = 0 # Scooch the X axis label up to work around the # nvd3 or d3 bug described in the config rotateLabels # setting below. workAroundAxisLabelBug = (xAxis) -> label = xAxis.select('.nv-axislabel') y = label.attr('y') label.attr('y', y - 10) # The earliest and latest dates. [low, high] = minMax(subject) # Decorate the chart. addTreatmentBars(xAxis, low, high) addClinicalEncounters(xAxis, low, high) addSessionDetailLinks(subject.sessions, xAxis, low, high, dy) addLegend(svg) workAroundAxisLabelBug(xAxis) ###* * @method configure * @param subject the subject to display * @return the nvd3 chart configuration ### configure: (subject) -> # The values to plot. values = xValues(subject) # Return the {options, data} configuration. options: chart: type: 'lineChart' height: 83 # We roll our own legend in the callback. showLegend: false # Note: the trivial X value accessor works around the # following nvd3 bug: # * If there is no x chart accessor option, then the chart # render results in an obscure error in the d3 voronoi # tesselation: # Cannot read property 'x' of null # This bug possibly results from a nvd3 expectation that # if there is a y option then there is also an x option. # The work-around is to supply a trivial x option. # TODO - isolate this bug with a nvd3 test case and report # it to nvd3. x: (date) -> date xAxis: axisLabel: 'Visit Date' showMaxMin: false tickValues: values tickFormat: Chart.formatDate # Note - due to a nvd3 or d3 bug, rotating the labels # forces the axis out of the chart display. Adding a # margin has no effect. The only recourse is to hammer # the DOM afterwards to move the label up. rotateLabels: -30 # Note: a nvd3 bug clobbers the custom tickSize set below. # The work-around is to reduce the height to a just-so # value that loses the tick marks (yuck). Setting the # xAxis height would be an alternative, but this has # no effect, probably due to another nvd3 bug. # TODO - file a nvd3 bug and revisit this in 2017. #tickSize: 4 tooltip: enabled: false xScale: d3.time.scale() # The session dates align on the X axis, # hence the Y value is always zero. y: -> 0 showYAxis: false data: [ key: 'PI:NAME:<NAME>END_PI Date' values: values ] ]
[ { "context": "quires cluster\n@requires os\n@requires path\n@author Isaac Johnston <isaac.johnston@joukou.com>\n@author Ben Brabant <", "end": 829, "score": 0.9998883008956909, "start": 815, "tag": "NAME", "value": "Isaac Johnston" }, { "context": "equires os\n@requires path\n@author...
src/cluster.coffee
joukou/joukou-api
0
"use strict" ###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ###* Launches a cluster of Joukou API processes to take advantage of multi-core systems and restarting failed worker processes for reliability. @module joukou-api/cluster @requires lodash @requires cluster @requires os @requires path @author Isaac Johnston <isaac.johnston@joukou.com> @author Ben Brabant <ben.brabant@joukou.com> ### _ = require( 'lodash' ) cluster = require( 'cluster' ) { cpus } = require( 'os' ) path = require( 'path' ) log = require( './log/LoggerFactory' ).getLogger( name: 'cluster' ) if cluster.isMaster # If this is the master process # Fork a new worker process per CPU core _.times( cpus().length, -> cluster.fork() ) # Fork a new worker process on worker death cluster.on( 'exit', ( worker, code, signal ) -> log.warn( 'joukou-api worker process %s died (%s / %s).' + 'Restarting...', worker.process.pid, code, signal ) cluster.fork() ) else # Otherwise if this is the child process require( './server' )
85171
"use strict" ###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ###* Launches a cluster of Joukou API processes to take advantage of multi-core systems and restarting failed worker processes for reliability. @module joukou-api/cluster @requires lodash @requires cluster @requires os @requires path @author <NAME> <<EMAIL>> @author <NAME> <<EMAIL>> ### _ = require( 'lodash' ) cluster = require( 'cluster' ) { cpus } = require( 'os' ) path = require( 'path' ) log = require( './log/LoggerFactory' ).getLogger( name: 'cluster' ) if cluster.isMaster # If this is the master process # Fork a new worker process per CPU core _.times( cpus().length, -> cluster.fork() ) # Fork a new worker process on worker death cluster.on( 'exit', ( worker, code, signal ) -> log.warn( 'joukou-api worker process %s died (%s / %s).' + 'Restarting...', worker.process.pid, code, signal ) cluster.fork() ) else # Otherwise if this is the child process require( './server' )
true
"use strict" ###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ###* Launches a cluster of Joukou API processes to take advantage of multi-core systems and restarting failed worker processes for reliability. @module joukou-api/cluster @requires lodash @requires cluster @requires os @requires path @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### _ = require( 'lodash' ) cluster = require( 'cluster' ) { cpus } = require( 'os' ) path = require( 'path' ) log = require( './log/LoggerFactory' ).getLogger( name: 'cluster' ) if cluster.isMaster # If this is the master process # Fork a new worker process per CPU core _.times( cpus().length, -> cluster.fork() ) # Fork a new worker process on worker death cluster.on( 'exit', ( worker, code, signal ) -> log.warn( 'joukou-api worker process %s died (%s / %s).' + 'Restarting...', worker.process.pid, code, signal ) cluster.fork() ) else # Otherwise if this is the child process require( './server' )
[ { "context": "tionsheet_cb\n\n\n # $scope.stores = [\n # name: \"Wegmans\"\n # desc: \"Wegmans, bla, bla\"\n # tags: [\"ab", "end": 2447, "score": 0.9929483532905579, "start": 2440, "tag": "NAME", "value": "Wegmans" } ]
mobile/www/js/controllers/store_picker.coffee
1egoman/bag-node
0
angular.module 'bag.controllers.stores_picker', [] .controller 'StorePickerCtrl', ( $scope socket user $ionicActionSheet ) -> socket.emit "store:index" socket.on "store:index:callback", (payload) -> $scope.stores = payload.data # sort stores in such a way so "my stores" are at the top $scope.sort_stores payload.data user.then (user) -> $scope.user = user # sort stores into "my stores" and "other stores" $scope.sort_stores = (stores) -> $scope.my_stores = _.compact stores.map (s) -> s._id in $scope.user.stores and s $scope.other_stores = _.compact stores.map (s) -> s._id not in $scope.user.stores and s # send server the updated values socket.emit "user:updatestores", user: $scope.user._id stores: $scope.user.stores # using the specified user, add the store $scope.toggle_store_in_user = (item, user=$scope.user) -> if item._id not in user.stores user.stores.push item._id else user.stores = _.without user.stores, item._id # regenerate stores $scope.sort_stores $scope.stores # item detail "popup" from the bottom of the screen $scope.item_details = (item) -> actionsheet_cb = (index) -> switch index # toggle wether store is in the list of "my stores" when 0 $scope.toggle_store_in_user item # open store website when 1 ref = window.open item.website, '_system', 'location=yes' return true # prefer the native action sheet. if window.plugins?.actionsheet window.plugins.actionsheet.show buttonLabels: [ item._id not in $scope.user.stores and 'Add to My Stores' or 'Remove from My Stores' "Go to store website" ], title: "Modify store", addCancelButtonWithLabel: "Cancel", androidEnableCancelButton: true, winphoneEnableCancelButton: true , (index) -> actionsheet_cb index-1 $scope.$apply() # but fallback onto ionic's else hideSheet = $ionicActionSheet.show buttons: [ text: item._id not in $scope.user.stores and 'Add to My Stores' or 'Remove from My Stores' , text: 'Go to store website' ], titleText: 'Modify Store', cancelText: 'Cancel', cancel: -> hideSheet() buttonClicked: actionsheet_cb # $scope.stores = [ # name: "Wegmans" # desc: "Wegmans, bla, bla" # tags: ["abc", "def", "ghi"] # website: "http://blablabla.com" # image: "http://therochesterian.com/wp-content/uploads/2011/12/wegmansbrownlogonew20brown2008.jpg" # ]
216716
angular.module 'bag.controllers.stores_picker', [] .controller 'StorePickerCtrl', ( $scope socket user $ionicActionSheet ) -> socket.emit "store:index" socket.on "store:index:callback", (payload) -> $scope.stores = payload.data # sort stores in such a way so "my stores" are at the top $scope.sort_stores payload.data user.then (user) -> $scope.user = user # sort stores into "my stores" and "other stores" $scope.sort_stores = (stores) -> $scope.my_stores = _.compact stores.map (s) -> s._id in $scope.user.stores and s $scope.other_stores = _.compact stores.map (s) -> s._id not in $scope.user.stores and s # send server the updated values socket.emit "user:updatestores", user: $scope.user._id stores: $scope.user.stores # using the specified user, add the store $scope.toggle_store_in_user = (item, user=$scope.user) -> if item._id not in user.stores user.stores.push item._id else user.stores = _.without user.stores, item._id # regenerate stores $scope.sort_stores $scope.stores # item detail "popup" from the bottom of the screen $scope.item_details = (item) -> actionsheet_cb = (index) -> switch index # toggle wether store is in the list of "my stores" when 0 $scope.toggle_store_in_user item # open store website when 1 ref = window.open item.website, '_system', 'location=yes' return true # prefer the native action sheet. if window.plugins?.actionsheet window.plugins.actionsheet.show buttonLabels: [ item._id not in $scope.user.stores and 'Add to My Stores' or 'Remove from My Stores' "Go to store website" ], title: "Modify store", addCancelButtonWithLabel: "Cancel", androidEnableCancelButton: true, winphoneEnableCancelButton: true , (index) -> actionsheet_cb index-1 $scope.$apply() # but fallback onto ionic's else hideSheet = $ionicActionSheet.show buttons: [ text: item._id not in $scope.user.stores and 'Add to My Stores' or 'Remove from My Stores' , text: 'Go to store website' ], titleText: 'Modify Store', cancelText: 'Cancel', cancel: -> hideSheet() buttonClicked: actionsheet_cb # $scope.stores = [ # name: "<NAME>" # desc: "Wegmans, bla, bla" # tags: ["abc", "def", "ghi"] # website: "http://blablabla.com" # image: "http://therochesterian.com/wp-content/uploads/2011/12/wegmansbrownlogonew20brown2008.jpg" # ]
true
angular.module 'bag.controllers.stores_picker', [] .controller 'StorePickerCtrl', ( $scope socket user $ionicActionSheet ) -> socket.emit "store:index" socket.on "store:index:callback", (payload) -> $scope.stores = payload.data # sort stores in such a way so "my stores" are at the top $scope.sort_stores payload.data user.then (user) -> $scope.user = user # sort stores into "my stores" and "other stores" $scope.sort_stores = (stores) -> $scope.my_stores = _.compact stores.map (s) -> s._id in $scope.user.stores and s $scope.other_stores = _.compact stores.map (s) -> s._id not in $scope.user.stores and s # send server the updated values socket.emit "user:updatestores", user: $scope.user._id stores: $scope.user.stores # using the specified user, add the store $scope.toggle_store_in_user = (item, user=$scope.user) -> if item._id not in user.stores user.stores.push item._id else user.stores = _.without user.stores, item._id # regenerate stores $scope.sort_stores $scope.stores # item detail "popup" from the bottom of the screen $scope.item_details = (item) -> actionsheet_cb = (index) -> switch index # toggle wether store is in the list of "my stores" when 0 $scope.toggle_store_in_user item # open store website when 1 ref = window.open item.website, '_system', 'location=yes' return true # prefer the native action sheet. if window.plugins?.actionsheet window.plugins.actionsheet.show buttonLabels: [ item._id not in $scope.user.stores and 'Add to My Stores' or 'Remove from My Stores' "Go to store website" ], title: "Modify store", addCancelButtonWithLabel: "Cancel", androidEnableCancelButton: true, winphoneEnableCancelButton: true , (index) -> actionsheet_cb index-1 $scope.$apply() # but fallback onto ionic's else hideSheet = $ionicActionSheet.show buttons: [ text: item._id not in $scope.user.stores and 'Add to My Stores' or 'Remove from My Stores' , text: 'Go to store website' ], titleText: 'Modify Store', cancelText: 'Cancel', cancel: -> hideSheet() buttonClicked: actionsheet_cb # $scope.stores = [ # name: "PI:NAME:<NAME>END_PI" # desc: "Wegmans, bla, bla" # tags: ["abc", "def", "ghi"] # website: "http://blablabla.com" # image: "http://therochesterian.com/wp-content/uploads/2011/12/wegmansbrownlogonew20brown2008.jpg" # ]
[ { "context": ")\n\napp = koa()\n\napp.keys = [OBI_SESSION_SECRET ? 'ObiIsAwesomelyInteligent']\n\napp\n .use require('koa-cors')()\n .use logger", "end": 238, "score": 0.998873233795166, "start": 214, "tag": "KEY", "value": "ObiIsAwesomelyInteligent" } ]
src/app.coffee
burtonjc/obi
0
koa = require 'koa' router = require('koa-router')() logger = require 'koa-bunyan-logger' bunyanLogentries = require 'bunyan-logentries' require('./routes')(router) app = koa() app.keys = [OBI_SESSION_SECRET ? 'ObiIsAwesomelyInteligent'] app .use require('koa-cors')() .use logger name: 'obi-server' level: process.env.LOG_LEVEL || 'debug' streams: [ level: 'info' stream: bunyanLogentries.createStream token: process.env.OBI_LOGENTRIES_TOKEN type: 'raw' , level: 'info', stream: process.stdout ] .use logger.requestIdContext() .use logger.timeContext() .use logger.requestLogger() .use require('koa-bodyparser')() .use router.routes() .use router.allowedMethods() module.exports = app
33320
koa = require 'koa' router = require('koa-router')() logger = require 'koa-bunyan-logger' bunyanLogentries = require 'bunyan-logentries' require('./routes')(router) app = koa() app.keys = [OBI_SESSION_SECRET ? '<KEY>'] app .use require('koa-cors')() .use logger name: 'obi-server' level: process.env.LOG_LEVEL || 'debug' streams: [ level: 'info' stream: bunyanLogentries.createStream token: process.env.OBI_LOGENTRIES_TOKEN type: 'raw' , level: 'info', stream: process.stdout ] .use logger.requestIdContext() .use logger.timeContext() .use logger.requestLogger() .use require('koa-bodyparser')() .use router.routes() .use router.allowedMethods() module.exports = app
true
koa = require 'koa' router = require('koa-router')() logger = require 'koa-bunyan-logger' bunyanLogentries = require 'bunyan-logentries' require('./routes')(router) app = koa() app.keys = [OBI_SESSION_SECRET ? 'PI:KEY:<KEY>END_PI'] app .use require('koa-cors')() .use logger name: 'obi-server' level: process.env.LOG_LEVEL || 'debug' streams: [ level: 'info' stream: bunyanLogentries.createStream token: process.env.OBI_LOGENTRIES_TOKEN type: 'raw' , level: 'info', stream: process.stdout ] .use logger.requestIdContext() .use logger.timeContext() .use logger.requestLogger() .use require('koa-bodyparser')() .use router.routes() .use router.allowedMethods() module.exports = app
[ { "context": "\", ->\n people = [\n {\n name: 'Bob'\n ageYears: 20\n }\n {\n ", "end": 898, "score": 0.9998268485069275, "start": 895, "tag": "NAME", "value": "Bob" }, { "context": "ageYears: 20\n }\n {\n name: 'G...
src/utils/sort/spec.coffee
p-koscielniak/hexagonjs
61
import { state, sort, sortBy, compare, compareNullsLast, localeCompare } from 'utils/sort' export default () -> describe 'hx-sort tests', -> runWithoutCollator = (tests) -> -> originalCollator = Intl?.Collator beforeEach -> if originalCollator? then Intl.Collator = undefined delete state.collator afterEach -> if originalCollator? then Intl.Collator = originalCollator delete state.collator tests() describe "sort", -> it "should work", -> a = [3, 1, 2] b = sort a b.should.eql([1, 2, 3]) c = ['c', 'a', 'b'] d = sort c d.should.eql(['a', 'b', 'c']) it "should not modify the original array", -> a = [3, 2, 1] b = sort a a[0].should.equal(3) b[0].should.equal(1) describe "sortBy", -> people = [ { name: 'Bob' ageYears: 20 } { name: 'Ganesh' ageYears: 19 } { name: 'Kate' ageYears: 39 } { name: 'Lazlo' ageYears: 18 } ] it "should not modify the original array", -> peopleCopy = [people...] peopleCopySorted = sortBy peopleCopy, (x) -> x.ageYears peopleCopy[0].name.should.equal('Bob') peopleCopySorted[0].name.should.equal('Lazlo') it "should work", -> byName = sortBy people, (x) -> x.name byAge = sortBy people, (x) -> x.ageYears byName.map((x) -> x.name).should.eql(['Bob', 'Ganesh', 'Kate', 'Lazlo']) byAge.map((x) -> x.name).should.eql(['Lazlo', 'Ganesh', 'Bob', 'Kate']) compareTests = -> it 'Strings should return the right value', -> compare('a', 'b').should.equal(-1) compare('b', 'a').should.equal(1) compare('a', 'a').should.equal(0) it 'undefined should be treated as its string representation', -> compare(undefined, 't').should.equal(1) compare('t', undefined).should.equal(-1) compare(undefined, 'v').should.equal(-1) compare('v', undefined).should.equal(1) compare(undefined, null).should.equal(1) compare(null, undefined).should.equal(-1) compare(undefined, undefined).should.equal(0) it 'null should be treated as its string representation', -> compare(null, 'a').should.equal(1) compare('a', null).should.equal(-1) compare(null, 'z').should.equal(-1) compare('z', null).should.equal(1) compare(null, null).should.equal(0) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(compare).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['c', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(compare).should .eql(['1', '2', 'a', 'aa', 'b', 'c', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(compare).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(compareNullsLast).should .eql(['10', '20', '25', '42', '100', null, null, undefined, undefined]) it 'Arrays of strings with undefined values should sort undefined to the end', -> array = ['b', undefined, null, 'z', undefined, 'a', null, 'p'] array.sort(compare).should.eql(['a', 'b', null, null, 'p', 'z', undefined, undefined]) it 'Numbers should return the right value', -> compare(1, 2).should.equal(-1) compare(2, 1).should.equal(1) compare(1, 1).should.equal(0) compare(1, undefined).should.equal(-1) compare(undefined, 1).should.equal(1) compare(1, null).should.equal(-1) compare(null, 1).should.equal(1) compare(0, null).should.equal(-1) compare(null, 0).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(compare).should.eql([1, 2, 10, 20, 100, 200]) array = [100, null, 200, undefined, 1, null, 20, undefined, 2, 10] array.sort(compare).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined, undefined]) describe 'using standard compare potentially with Intl.Collator. ', compareTests describe 'using standard compare without Intl.Collator', runWithoutCollator(compareTests) compareNullsLastTests = -> it 'Strings should return the right value', -> compareNullsLast('a', 'b').should.equal(-1) compareNullsLast('b', 'a').should.equal(1) compareNullsLast('a', 'a').should.equal(0) it 'undefined should always be sorted to the end', -> compareNullsLast(undefined, 'a').should.equal(1) compareNullsLast('a', undefined).should.equal(-1) compareNullsLast(undefined, 'z').should.equal(1) compareNullsLast('z', undefined).should.equal(-1) compareNullsLast(undefined, null).should.equal(1) compareNullsLast(null, undefined).should.equal(-1) compareNullsLast(undefined, undefined).should.equal(0) it 'null should be sorted after any defined value', -> compareNullsLast(null, 'a').should.equal(1) compareNullsLast('a', null).should.equal(-1) compareNullsLast(null, 'z').should.equal(1) compareNullsLast('z', null).should.equal(-1) compareNullsLast(null, null).should.equal(0) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(compareNullsLast).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['z', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(compareNullsLast).should .eql(['1', '2', 'a', 'aa', 'b', 'z', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(compareNullsLast).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(compareNullsLast).should .eql(['10', '20', '25', '42', '100', null, null, undefined , undefined]) it 'Arrays of strings with undefined values should sort null and undefined to the end', -> array = ['b', undefined, null, 'z', undefined, 'a', null, 'p'] array.sort(compareNullsLast).should.eql(['a', 'b', 'p', 'z', null, null, undefined, undefined]) it 'Numbers should return the right value', -> compareNullsLast(1, 2).should.equal(-1) compareNullsLast(2, 1).should.equal(1) compareNullsLast(1, 1).should.equal(0) compareNullsLast(1, undefined).should.equal(-1) compareNullsLast(undefined, 1).should.equal(1) compareNullsLast(1, null).should.equal(-1) compareNullsLast(null, 1).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(compareNullsLast).should.eql([1, 2, 10, 20, 100, 200]) array = [100, null, 200, undefined, 1, null, 20, undefined, 2, 10] array.sort(compareNullsLast).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined, undefined]) describe 'using compareNullsLast potentially with Intl.Collator. ', compareNullsLastTests describe 'using compareNullsLast without Intl.Collator. ', runWithoutCollator(compareNullsLastTests) localeCompareTests = -> supportsOptions = -> try 'a'.localeCompare('b', 'i') catch e e is 'RangeError' false it 'Strings should return the right value', -> localeCompare()('a', 'b').should.equal(-1) localeCompare()('b', 'a').should.equal(1) localeCompare()('a', 'a').should.equal(0) it 'should fail when using undefined or null', -> localeCompare()('a', undefined).should.equal(-1) localeCompare()(undefined, 'a').should.equal(1) localeCompare()('z', undefined).should.equal(1) localeCompare()(undefined, 'z').should.equal(-1) localeCompare()('a', null).should.equal(-1) localeCompare()(null, 'a').should.equal(1) localeCompare()('z', null).should.equal(1) localeCompare()(null, 'z').should.equal(-1) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(localeCompare()).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['25', '10', '20', '42', '100'] array.sort(localeCompare()).should.eql(['10', '20', '25', '42', '100']) it 'Numbers should return the right value', -> localeCompare()(1, 2).should.equal(-1) localeCompare()(2, 1).should.equal(1) localeCompare()(1, 1).should.equal(0) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(localeCompare()).should.eql([1, 2, 10, 20, 100, 200]) it 'Array with localised characters should return the right value', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['é', 'e', 'z', 'è', 'a', 'ä'] array.sort(localeCompare()).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) if supportsOptions() array.sort(localeCompare('sv')).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) array.sort(localeCompare('de')).should.eql(['a', 'e', 'é', 'è', 'z', 'ä']) describe 'using localeCompare potentially with Intl.Collator. ', localeCompareTests describe 'using localeCompare without Intl.Collator. ', runWithoutCollator(localeCompareTests) localeCompareTests = -> supportsOptions = -> try 'a'.localeCompare('b', {nullsLast: true}) catch e e is 'RangeError' false it 'Strings should return the right value', -> localeCompare(undefined, {nullsLast: true})('a', 'b').should.equal(-1) localeCompare(undefined, {nullsLast: true})('b', 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('a', 'a').should.equal(0) localeCompare(undefined, {nullsLast: true})('a', undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('z', undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 'z').should.equal(1) localeCompare(undefined, {nullsLast: true})('a', null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('z', null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 'z').should.equal(1) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['z', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(localeCompare(undefined, {nullsLast: true})).should .eql(['1', '2', 'a', 'aa', 'b', 'z', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(localeCompare(undefined, {nullsLast: true})).should .eql(['10', '20', '25', '42', '100', null, null, undefined , undefined]) it 'Numbers should return the right value', -> localeCompare(undefined, {nullsLast: true})(1, 2).should.equal(-1) localeCompare(undefined, {nullsLast: true})(2, 1).should.equal(1) localeCompare(undefined, {nullsLast: true})(1, 1).should.equal(0) localeCompare(undefined, {nullsLast: true})(1, undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 1).should.equal(1) localeCompare(undefined, {nullsLast: true})(1, null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 1).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, null, 200, undefined, 1, null, 20, 2, 10] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined]) it 'Array with localised characters should return the right value', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['e', 'z', 'è', 'a', 'é', 'ä'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) if supportsOptions() array.sort(localeCompare('sv', {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) array.sort(localeCompare('de', {nullsLast: true})).should.eql(['a', 'e', 'é', 'è', 'z', 'ä']) it 'Arrays with localised characters and undefined values should sort null and undefined to the end', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['é', null, 'e', undefined, 'z', null, 'è', undefined, 'a', 'ä'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z', null, null, undefined, undefined]) if supportsOptions() array.sort(localeCompare('sv', {nullsLast: true})).should .eql(['a', 'ä', 'e', 'é', 'è', 'z', null, null, undefined, undefined]) array.sort(localeCompare('de', {nullsLast: true})).should .eql(['a', 'e', 'é', 'è', 'z', 'ä', null, null, undefined, undefined]) describe 'using localeCompare potentially with Intl.Collator. ', localeCompareTests describe 'using localeCompare without Intl.Collator. ', runWithoutCollator(localeCompareTests)
135422
import { state, sort, sortBy, compare, compareNullsLast, localeCompare } from 'utils/sort' export default () -> describe 'hx-sort tests', -> runWithoutCollator = (tests) -> -> originalCollator = Intl?.Collator beforeEach -> if originalCollator? then Intl.Collator = undefined delete state.collator afterEach -> if originalCollator? then Intl.Collator = originalCollator delete state.collator tests() describe "sort", -> it "should work", -> a = [3, 1, 2] b = sort a b.should.eql([1, 2, 3]) c = ['c', 'a', 'b'] d = sort c d.should.eql(['a', 'b', 'c']) it "should not modify the original array", -> a = [3, 2, 1] b = sort a a[0].should.equal(3) b[0].should.equal(1) describe "sortBy", -> people = [ { name: '<NAME>' ageYears: 20 } { name: '<NAME>' ageYears: 19 } { name: '<NAME>' ageYears: 39 } { name: '<NAME>' ageYears: 18 } ] it "should not modify the original array", -> peopleCopy = [people...] peopleCopySorted = sortBy peopleCopy, (x) -> x.ageYears peopleCopy[0].name.should.equal('<NAME>') peopleCopySorted[0].name.should.equal('<NAME>') it "should work", -> byName = sortBy people, (x) -> x.name byAge = sortBy people, (x) -> x.ageYears byName.map((x) -> x.name).should.eql(['<NAME>', '<NAME>', '<NAME>', '<NAME>']) byAge.map((x) -> x.name).should.eql(['<NAME>', '<NAME>', '<NAME>', '<NAME>']) compareTests = -> it 'Strings should return the right value', -> compare('a', 'b').should.equal(-1) compare('b', 'a').should.equal(1) compare('a', 'a').should.equal(0) it 'undefined should be treated as its string representation', -> compare(undefined, 't').should.equal(1) compare('t', undefined).should.equal(-1) compare(undefined, 'v').should.equal(-1) compare('v', undefined).should.equal(1) compare(undefined, null).should.equal(1) compare(null, undefined).should.equal(-1) compare(undefined, undefined).should.equal(0) it 'null should be treated as its string representation', -> compare(null, 'a').should.equal(1) compare('a', null).should.equal(-1) compare(null, 'z').should.equal(-1) compare('z', null).should.equal(1) compare(null, null).should.equal(0) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(compare).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['c', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(compare).should .eql(['1', '2', 'a', 'aa', 'b', 'c', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(compare).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(compareNullsLast).should .eql(['10', '20', '25', '42', '100', null, null, undefined, undefined]) it 'Arrays of strings with undefined values should sort undefined to the end', -> array = ['b', undefined, null, 'z', undefined, 'a', null, 'p'] array.sort(compare).should.eql(['a', 'b', null, null, 'p', 'z', undefined, undefined]) it 'Numbers should return the right value', -> compare(1, 2).should.equal(-1) compare(2, 1).should.equal(1) compare(1, 1).should.equal(0) compare(1, undefined).should.equal(-1) compare(undefined, 1).should.equal(1) compare(1, null).should.equal(-1) compare(null, 1).should.equal(1) compare(0, null).should.equal(-1) compare(null, 0).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(compare).should.eql([1, 2, 10, 20, 100, 200]) array = [100, null, 200, undefined, 1, null, 20, undefined, 2, 10] array.sort(compare).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined, undefined]) describe 'using standard compare potentially with Intl.Collator. ', compareTests describe 'using standard compare without Intl.Collator', runWithoutCollator(compareTests) compareNullsLastTests = -> it 'Strings should return the right value', -> compareNullsLast('a', 'b').should.equal(-1) compareNullsLast('b', 'a').should.equal(1) compareNullsLast('a', 'a').should.equal(0) it 'undefined should always be sorted to the end', -> compareNullsLast(undefined, 'a').should.equal(1) compareNullsLast('a', undefined).should.equal(-1) compareNullsLast(undefined, 'z').should.equal(1) compareNullsLast('z', undefined).should.equal(-1) compareNullsLast(undefined, null).should.equal(1) compareNullsLast(null, undefined).should.equal(-1) compareNullsLast(undefined, undefined).should.equal(0) it 'null should be sorted after any defined value', -> compareNullsLast(null, 'a').should.equal(1) compareNullsLast('a', null).should.equal(-1) compareNullsLast(null, 'z').should.equal(1) compareNullsLast('z', null).should.equal(-1) compareNullsLast(null, null).should.equal(0) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(compareNullsLast).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['z', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(compareNullsLast).should .eql(['1', '2', 'a', 'aa', 'b', 'z', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(compareNullsLast).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(compareNullsLast).should .eql(['10', '20', '25', '42', '100', null, null, undefined , undefined]) it 'Arrays of strings with undefined values should sort null and undefined to the end', -> array = ['b', undefined, null, 'z', undefined, 'a', null, 'p'] array.sort(compareNullsLast).should.eql(['a', 'b', 'p', 'z', null, null, undefined, undefined]) it 'Numbers should return the right value', -> compareNullsLast(1, 2).should.equal(-1) compareNullsLast(2, 1).should.equal(1) compareNullsLast(1, 1).should.equal(0) compareNullsLast(1, undefined).should.equal(-1) compareNullsLast(undefined, 1).should.equal(1) compareNullsLast(1, null).should.equal(-1) compareNullsLast(null, 1).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(compareNullsLast).should.eql([1, 2, 10, 20, 100, 200]) array = [100, null, 200, undefined, 1, null, 20, undefined, 2, 10] array.sort(compareNullsLast).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined, undefined]) describe 'using compareNullsLast potentially with Intl.Collator. ', compareNullsLastTests describe 'using compareNullsLast without Intl.Collator. ', runWithoutCollator(compareNullsLastTests) localeCompareTests = -> supportsOptions = -> try 'a'.localeCompare('b', 'i') catch e e is 'RangeError' false it 'Strings should return the right value', -> localeCompare()('a', 'b').should.equal(-1) localeCompare()('b', 'a').should.equal(1) localeCompare()('a', 'a').should.equal(0) it 'should fail when using undefined or null', -> localeCompare()('a', undefined).should.equal(-1) localeCompare()(undefined, 'a').should.equal(1) localeCompare()('z', undefined).should.equal(1) localeCompare()(undefined, 'z').should.equal(-1) localeCompare()('a', null).should.equal(-1) localeCompare()(null, 'a').should.equal(1) localeCompare()('z', null).should.equal(1) localeCompare()(null, 'z').should.equal(-1) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(localeCompare()).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['25', '10', '20', '42', '100'] array.sort(localeCompare()).should.eql(['10', '20', '25', '42', '100']) it 'Numbers should return the right value', -> localeCompare()(1, 2).should.equal(-1) localeCompare()(2, 1).should.equal(1) localeCompare()(1, 1).should.equal(0) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(localeCompare()).should.eql([1, 2, 10, 20, 100, 200]) it 'Array with localised characters should return the right value', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['é', 'e', 'z', 'è', 'a', 'ä'] array.sort(localeCompare()).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) if supportsOptions() array.sort(localeCompare('sv')).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) array.sort(localeCompare('de')).should.eql(['a', 'e', 'é', 'è', 'z', 'ä']) describe 'using localeCompare potentially with Intl.Collator. ', localeCompareTests describe 'using localeCompare without Intl.Collator. ', runWithoutCollator(localeCompareTests) localeCompareTests = -> supportsOptions = -> try 'a'.localeCompare('b', {nullsLast: true}) catch e e is 'RangeError' false it 'Strings should return the right value', -> localeCompare(undefined, {nullsLast: true})('a', 'b').should.equal(-1) localeCompare(undefined, {nullsLast: true})('b', 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('a', 'a').should.equal(0) localeCompare(undefined, {nullsLast: true})('a', undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('z', undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 'z').should.equal(1) localeCompare(undefined, {nullsLast: true})('a', null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('z', null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 'z').should.equal(1) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['z', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(localeCompare(undefined, {nullsLast: true})).should .eql(['1', '2', 'a', 'aa', 'b', 'z', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(localeCompare(undefined, {nullsLast: true})).should .eql(['10', '20', '25', '42', '100', null, null, undefined , undefined]) it 'Numbers should return the right value', -> localeCompare(undefined, {nullsLast: true})(1, 2).should.equal(-1) localeCompare(undefined, {nullsLast: true})(2, 1).should.equal(1) localeCompare(undefined, {nullsLast: true})(1, 1).should.equal(0) localeCompare(undefined, {nullsLast: true})(1, undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 1).should.equal(1) localeCompare(undefined, {nullsLast: true})(1, null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 1).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, null, 200, undefined, 1, null, 20, 2, 10] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined]) it 'Array with localised characters should return the right value', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['e', 'z', 'è', 'a', 'é', 'ä'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) if supportsOptions() array.sort(localeCompare('sv', {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) array.sort(localeCompare('de', {nullsLast: true})).should.eql(['a', 'e', 'é', 'è', 'z', 'ä']) it 'Arrays with localised characters and undefined values should sort null and undefined to the end', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['é', null, 'e', undefined, 'z', null, 'è', undefined, 'a', 'ä'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z', null, null, undefined, undefined]) if supportsOptions() array.sort(localeCompare('sv', {nullsLast: true})).should .eql(['a', 'ä', 'e', 'é', 'è', 'z', null, null, undefined, undefined]) array.sort(localeCompare('de', {nullsLast: true})).should .eql(['a', 'e', 'é', 'è', 'z', 'ä', null, null, undefined, undefined]) describe 'using localeCompare potentially with Intl.Collator. ', localeCompareTests describe 'using localeCompare without Intl.Collator. ', runWithoutCollator(localeCompareTests)
true
import { state, sort, sortBy, compare, compareNullsLast, localeCompare } from 'utils/sort' export default () -> describe 'hx-sort tests', -> runWithoutCollator = (tests) -> -> originalCollator = Intl?.Collator beforeEach -> if originalCollator? then Intl.Collator = undefined delete state.collator afterEach -> if originalCollator? then Intl.Collator = originalCollator delete state.collator tests() describe "sort", -> it "should work", -> a = [3, 1, 2] b = sort a b.should.eql([1, 2, 3]) c = ['c', 'a', 'b'] d = sort c d.should.eql(['a', 'b', 'c']) it "should not modify the original array", -> a = [3, 2, 1] b = sort a a[0].should.equal(3) b[0].should.equal(1) describe "sortBy", -> people = [ { name: 'PI:NAME:<NAME>END_PI' ageYears: 20 } { name: 'PI:NAME:<NAME>END_PI' ageYears: 19 } { name: 'PI:NAME:<NAME>END_PI' ageYears: 39 } { name: 'PI:NAME:<NAME>END_PI' ageYears: 18 } ] it "should not modify the original array", -> peopleCopy = [people...] peopleCopySorted = sortBy peopleCopy, (x) -> x.ageYears peopleCopy[0].name.should.equal('PI:NAME:<NAME>END_PI') peopleCopySorted[0].name.should.equal('PI:NAME:<NAME>END_PI') it "should work", -> byName = sortBy people, (x) -> x.name byAge = sortBy people, (x) -> x.ageYears byName.map((x) -> x.name).should.eql(['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']) byAge.map((x) -> x.name).should.eql(['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']) compareTests = -> it 'Strings should return the right value', -> compare('a', 'b').should.equal(-1) compare('b', 'a').should.equal(1) compare('a', 'a').should.equal(0) it 'undefined should be treated as its string representation', -> compare(undefined, 't').should.equal(1) compare('t', undefined).should.equal(-1) compare(undefined, 'v').should.equal(-1) compare('v', undefined).should.equal(1) compare(undefined, null).should.equal(1) compare(null, undefined).should.equal(-1) compare(undefined, undefined).should.equal(0) it 'null should be treated as its string representation', -> compare(null, 'a').should.equal(1) compare('a', null).should.equal(-1) compare(null, 'z').should.equal(-1) compare('z', null).should.equal(1) compare(null, null).should.equal(0) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(compare).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['c', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(compare).should .eql(['1', '2', 'a', 'aa', 'b', 'c', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(compare).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(compareNullsLast).should .eql(['10', '20', '25', '42', '100', null, null, undefined, undefined]) it 'Arrays of strings with undefined values should sort undefined to the end', -> array = ['b', undefined, null, 'z', undefined, 'a', null, 'p'] array.sort(compare).should.eql(['a', 'b', null, null, 'p', 'z', undefined, undefined]) it 'Numbers should return the right value', -> compare(1, 2).should.equal(-1) compare(2, 1).should.equal(1) compare(1, 1).should.equal(0) compare(1, undefined).should.equal(-1) compare(undefined, 1).should.equal(1) compare(1, null).should.equal(-1) compare(null, 1).should.equal(1) compare(0, null).should.equal(-1) compare(null, 0).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(compare).should.eql([1, 2, 10, 20, 100, 200]) array = [100, null, 200, undefined, 1, null, 20, undefined, 2, 10] array.sort(compare).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined, undefined]) describe 'using standard compare potentially with Intl.Collator. ', compareTests describe 'using standard compare without Intl.Collator', runWithoutCollator(compareTests) compareNullsLastTests = -> it 'Strings should return the right value', -> compareNullsLast('a', 'b').should.equal(-1) compareNullsLast('b', 'a').should.equal(1) compareNullsLast('a', 'a').should.equal(0) it 'undefined should always be sorted to the end', -> compareNullsLast(undefined, 'a').should.equal(1) compareNullsLast('a', undefined).should.equal(-1) compareNullsLast(undefined, 'z').should.equal(1) compareNullsLast('z', undefined).should.equal(-1) compareNullsLast(undefined, null).should.equal(1) compareNullsLast(null, undefined).should.equal(-1) compareNullsLast(undefined, undefined).should.equal(0) it 'null should be sorted after any defined value', -> compareNullsLast(null, 'a').should.equal(1) compareNullsLast('a', null).should.equal(-1) compareNullsLast(null, 'z').should.equal(1) compareNullsLast('z', null).should.equal(-1) compareNullsLast(null, null).should.equal(0) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(compareNullsLast).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['z', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(compareNullsLast).should .eql(['1', '2', 'a', 'aa', 'b', 'z', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(compareNullsLast).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(compareNullsLast).should .eql(['10', '20', '25', '42', '100', null, null, undefined , undefined]) it 'Arrays of strings with undefined values should sort null and undefined to the end', -> array = ['b', undefined, null, 'z', undefined, 'a', null, 'p'] array.sort(compareNullsLast).should.eql(['a', 'b', 'p', 'z', null, null, undefined, undefined]) it 'Numbers should return the right value', -> compareNullsLast(1, 2).should.equal(-1) compareNullsLast(2, 1).should.equal(1) compareNullsLast(1, 1).should.equal(0) compareNullsLast(1, undefined).should.equal(-1) compareNullsLast(undefined, 1).should.equal(1) compareNullsLast(1, null).should.equal(-1) compareNullsLast(null, 1).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(compareNullsLast).should.eql([1, 2, 10, 20, 100, 200]) array = [100, null, 200, undefined, 1, null, 20, undefined, 2, 10] array.sort(compareNullsLast).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined, undefined]) describe 'using compareNullsLast potentially with Intl.Collator. ', compareNullsLastTests describe 'using compareNullsLast without Intl.Collator. ', runWithoutCollator(compareNullsLastTests) localeCompareTests = -> supportsOptions = -> try 'a'.localeCompare('b', 'i') catch e e is 'RangeError' false it 'Strings should return the right value', -> localeCompare()('a', 'b').should.equal(-1) localeCompare()('b', 'a').should.equal(1) localeCompare()('a', 'a').should.equal(0) it 'should fail when using undefined or null', -> localeCompare()('a', undefined).should.equal(-1) localeCompare()(undefined, 'a').should.equal(1) localeCompare()('z', undefined).should.equal(1) localeCompare()(undefined, 'z').should.equal(-1) localeCompare()('a', null).should.equal(-1) localeCompare()(null, 'a').should.equal(1) localeCompare()('z', null).should.equal(1) localeCompare()(null, 'z').should.equal(-1) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(localeCompare()).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['25', '10', '20', '42', '100'] array.sort(localeCompare()).should.eql(['10', '20', '25', '42', '100']) it 'Numbers should return the right value', -> localeCompare()(1, 2).should.equal(-1) localeCompare()(2, 1).should.equal(1) localeCompare()(1, 1).should.equal(0) it 'Arrays of numbers should return the right value', -> array = [100, 200, 1, 20, 2, 10] array.sort(localeCompare()).should.eql([1, 2, 10, 20, 100, 200]) it 'Array with localised characters should return the right value', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['é', 'e', 'z', 'è', 'a', 'ä'] array.sort(localeCompare()).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) if supportsOptions() array.sort(localeCompare('sv')).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) array.sort(localeCompare('de')).should.eql(['a', 'e', 'é', 'è', 'z', 'ä']) describe 'using localeCompare potentially with Intl.Collator. ', localeCompareTests describe 'using localeCompare without Intl.Collator. ', runWithoutCollator(localeCompareTests) localeCompareTests = -> supportsOptions = -> try 'a'.localeCompare('b', {nullsLast: true}) catch e e is 'RangeError' false it 'Strings should return the right value', -> localeCompare(undefined, {nullsLast: true})('a', 'b').should.equal(-1) localeCompare(undefined, {nullsLast: true})('b', 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('a', 'a').should.equal(0) localeCompare(undefined, {nullsLast: true})('a', undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('z', undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 'z').should.equal(1) localeCompare(undefined, {nullsLast: true})('a', null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 'a').should.equal(1) localeCompare(undefined, {nullsLast: true})('z', null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 'z').should.equal(1) it 'Arrays should return the right value', -> array = ['c', 'a', 'b', 'aa', 'ab', 'ac', '1', '2'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['1', '2', 'a', 'aa', 'ab', 'ac', 'b', 'c']) array = ['z', null, 'a', undefined, 'b', null, 'aa', undefined, '1', '2'] array.sort(localeCompare(undefined, {nullsLast: true})).should .eql(['1', '2', 'a', 'aa', 'b', 'z', null, null, undefined, undefined]) array = ['25', '10', '20', '42', '100'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['10', '20', '25', '42', '100']) array = ['25', null, '10', undefined, '20', null, '42', undefined, '100'] array.sort(localeCompare(undefined, {nullsLast: true})).should .eql(['10', '20', '25', '42', '100', null, null, undefined , undefined]) it 'Numbers should return the right value', -> localeCompare(undefined, {nullsLast: true})(1, 2).should.equal(-1) localeCompare(undefined, {nullsLast: true})(2, 1).should.equal(1) localeCompare(undefined, {nullsLast: true})(1, 1).should.equal(0) localeCompare(undefined, {nullsLast: true})(1, undefined).should.equal(-1) localeCompare(undefined, {nullsLast: true})(undefined, 1).should.equal(1) localeCompare(undefined, {nullsLast: true})(1, null).should.equal(-1) localeCompare(undefined, {nullsLast: true})(null, 1).should.equal(1) it 'Arrays of numbers should return the right value', -> array = [100, null, 200, undefined, 1, null, 20, 2, 10] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql([1, 2, 10, 20, 100, 200, null, null, undefined]) it 'Array with localised characters should return the right value', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['e', 'z', 'è', 'a', 'é', 'ä'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) if supportsOptions() array.sort(localeCompare('sv', {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z']) array.sort(localeCompare('de', {nullsLast: true})).should.eql(['a', 'e', 'é', 'è', 'z', 'ä']) it 'Arrays with localised characters and undefined values should sort null and undefined to the end', -> if navigator.userAgent.indexOf 'Phantom' > -1 true.should.equal(true) else array = ['é', null, 'e', undefined, 'z', null, 'è', undefined, 'a', 'ä'] array.sort(localeCompare(undefined, {nullsLast: true})).should.eql(['a', 'ä', 'e', 'é', 'è', 'z', null, null, undefined, undefined]) if supportsOptions() array.sort(localeCompare('sv', {nullsLast: true})).should .eql(['a', 'ä', 'e', 'é', 'è', 'z', null, null, undefined, undefined]) array.sort(localeCompare('de', {nullsLast: true})).should .eql(['a', 'e', 'é', 'è', 'z', 'ä', null, null, undefined, undefined]) describe 'using localeCompare potentially with Intl.Collator. ', localeCompareTests describe 'using localeCompare without Intl.Collator. ', runWithoutCollator(localeCompareTests)
[ { "context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio", "end": 30, "score": 0.9998748898506165, "start": 17, "tag": "NAME", "value": "Joshua Carver" } ]
src/coffeescript/charts/point.coffee
jcarver989/raphy-charts
5
# Copyright 2012 Joshua Carver # # 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. class Point constructor: (x, @y, @options = {}) -> if @is_date(x) @x = x.getTime() @is_date_type = true else @x = x return is_date: (potential_date) -> Object.prototype.toString.call(potential_date) == '[object Date]' exports.Point = Point
81125
# Copyright 2012 <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. class Point constructor: (x, @y, @options = {}) -> if @is_date(x) @x = x.getTime() @is_date_type = true else @x = x return is_date: (potential_date) -> Object.prototype.toString.call(potential_date) == '[object Date]' exports.Point = Point
true
# Copyright 2012 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. class Point constructor: (x, @y, @options = {}) -> if @is_date(x) @x = x.getTime() @is_date_type = true else @x = x return is_date: (potential_date) -> Object.prototype.toString.call(potential_date) == '[object Date]' exports.Point = Point
[ { "context": "terValue, 'i')\n\n cities: ->\n [\n { name: 'Wrocław', description: 'Beautiful city' }\n { name: '", "end": 479, "score": 0.9914813041687012, "start": 472, "tag": "NAME", "value": "Wrocław" }, { "context": "', description: 'Beautiful city' }\n { name:...
src/scripts/hello_world.cjsx
methyl/react-typeahead-example
0
TypeAheadInput = require './type_ahead_input' module.exports = React.createClass displayName: 'HelloWorld' getInitialState: -> filterValue: '' render: -> <div> <TypeAheadInput items={@filteredCities()} onChange={@handleChange} /> </div> handleChange: (props) -> @setState filterValue: props.name filteredCities: -> @cities().filter (city) => city.name.match RegExp(@state.filterValue, 'i') cities: -> [ { name: 'Wrocław', description: 'Beautiful city' } { name: 'Warszawa', description: 'Ugly city' } ]
11624
TypeAheadInput = require './type_ahead_input' module.exports = React.createClass displayName: 'HelloWorld' getInitialState: -> filterValue: '' render: -> <div> <TypeAheadInput items={@filteredCities()} onChange={@handleChange} /> </div> handleChange: (props) -> @setState filterValue: props.name filteredCities: -> @cities().filter (city) => city.name.match RegExp(@state.filterValue, 'i') cities: -> [ { name: '<NAME>', description: 'Beautiful city' } { name: '<NAME>', description: 'Ugly city' } ]
true
TypeAheadInput = require './type_ahead_input' module.exports = React.createClass displayName: 'HelloWorld' getInitialState: -> filterValue: '' render: -> <div> <TypeAheadInput items={@filteredCities()} onChange={@handleChange} /> </div> handleChange: (props) -> @setState filterValue: props.name filteredCities: -> @cities().filter (city) => city.name.match RegExp(@state.filterValue, 'i') cities: -> [ { name: 'PI:NAME:<NAME>END_PI', description: 'Beautiful city' } { name: 'PI:NAME:<NAME>END_PI', description: 'Ugly city' } ]
[ { "context": "# MIT License\n\n# Copyright (c) 2020 Jean-Jacques François Reibel\n\n# Permission is hereby granted, free of charge, ", "end": 64, "score": 0.9998165965080261, "start": 36, "tag": "NAME", "value": "Jean-Jacques François Reibel" } ]
car.coffee
JJFReibel/ObjectOrientedCoffeeScript
0
# MIT License # Copyright (c) 2020 Jean-Jacques François Reibel # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class Car constructor: (@wheels, @doors, @cylinders) -> addWheels: (wheelsToAdd) -> @wheels = @wheels + wheelsToAdd addDoors: (doorsToAdd) -> @doors = @doors + doorsToAdd addCylinders: (cylindersToAdd) -> @cylinders = @cylinders + cylindersToAdd deleteWheels: (wheelsToRemove) -> @wheels = @wheels - wheelsToRemove deleteDoors: (doorsToRemove) -> @doors = @doors - doorsToRemove deleteCylinders: (cylindersToRemove) -> @cylinders = @cylinders - cylindersToRemove displayProperties: -> console.log "Wheel check: " + subaru.wheels console.log "Door check: " + subaru.doors console.log "Cylinder check: " + subaru.cylinders + "\n" # Creating car console.log "\nCreating car." subaru = new Car 4, 4, 4 subaru.displayProperties() # Adding wheel directly to car object console.log "Adding wheel directly to car object." subaru.wheels = 5 subaru.displayProperties() # Deleting wheel using object method console.log "Deleting wheel using object method." subaru.deleteWheels(1) subaru.displayProperties()
20798
# MIT License # Copyright (c) 2020 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class Car constructor: (@wheels, @doors, @cylinders) -> addWheels: (wheelsToAdd) -> @wheels = @wheels + wheelsToAdd addDoors: (doorsToAdd) -> @doors = @doors + doorsToAdd addCylinders: (cylindersToAdd) -> @cylinders = @cylinders + cylindersToAdd deleteWheels: (wheelsToRemove) -> @wheels = @wheels - wheelsToRemove deleteDoors: (doorsToRemove) -> @doors = @doors - doorsToRemove deleteCylinders: (cylindersToRemove) -> @cylinders = @cylinders - cylindersToRemove displayProperties: -> console.log "Wheel check: " + subaru.wheels console.log "Door check: " + subaru.doors console.log "Cylinder check: " + subaru.cylinders + "\n" # Creating car console.log "\nCreating car." subaru = new Car 4, 4, 4 subaru.displayProperties() # Adding wheel directly to car object console.log "Adding wheel directly to car object." subaru.wheels = 5 subaru.displayProperties() # Deleting wheel using object method console.log "Deleting wheel using object method." subaru.deleteWheels(1) subaru.displayProperties()
true
# MIT License # Copyright (c) 2020 PI:NAME:<NAME>END_PI # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class Car constructor: (@wheels, @doors, @cylinders) -> addWheels: (wheelsToAdd) -> @wheels = @wheels + wheelsToAdd addDoors: (doorsToAdd) -> @doors = @doors + doorsToAdd addCylinders: (cylindersToAdd) -> @cylinders = @cylinders + cylindersToAdd deleteWheels: (wheelsToRemove) -> @wheels = @wheels - wheelsToRemove deleteDoors: (doorsToRemove) -> @doors = @doors - doorsToRemove deleteCylinders: (cylindersToRemove) -> @cylinders = @cylinders - cylindersToRemove displayProperties: -> console.log "Wheel check: " + subaru.wheels console.log "Door check: " + subaru.doors console.log "Cylinder check: " + subaru.cylinders + "\n" # Creating car console.log "\nCreating car." subaru = new Car 4, 4, 4 subaru.displayProperties() # Adding wheel directly to car object console.log "Adding wheel directly to car object." subaru.wheels = 5 subaru.displayProperties() # Deleting wheel using object method console.log "Deleting wheel using object method." subaru.deleteWheels(1) subaru.displayProperties()
[ { "context": " item.message\n Media\n key: \"#{item._id}-media\"\n media: item.media\n", "end": 3838, "score": 0.8204559683799744, "start": 3829, "tag": "KEY", "value": "id}-media" } ]
src/components/streamItem.coffee
brianshaler/kerplunk-stream
0
_ = require 'lodash' React = require 'react' ReactiveData = require 'reactive-data' Avatar = require './avatar' # Media = require './streamMedia' StreamItemControls = require './streamItemControls' {DOM} = React linkUrls = (message) -> maxLength = 34 matches = message.match /https?:\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|]/gi if matches for url in matches # Keep the matched URL to use in href, but create a truncated version to display shorter = url shorter = shorter.replace /^http:\/\//, "" shorter = shorter.replace /^https:\/\//, "" shorter = shorter.replace /^www\./, "" if shorter.length > maxLength shorter = shorter.substring(0, maxLength-4) + "..." # Replace instance of matched URL with HTML message = message.replace url, "<a href='#{url}' title='#{url}' class='truncate-link'>#{shorter}</a>" message # Turn hashtags into links linkHashtags = (message) -> hashPattern = /(^|\s)#([-A-Za-z0-9_]+)(\b)/gi message.replace hashPattern, "$1<a href='/topic/bytext/$2'>#$2</a>$3" # Turn @names into links linkScreenNames = (message) -> atPattern = /(^|\s|[^a-zA-Z0-9_\-+])@([-A-Za-z0-9_]+)(\b|\s|[^a-zA-Z0-9]|$)/gi message.replace atPattern, "$1<a href='/identity/byusername/$2'>@$2</a>$3" module.exports = React.createFactory React.createClass getInitialState: -> # console.log 'initial props on streamItem', @props itemId = String @props.item?._id ? @props.itemId if @props.item?._id @props.Repository.update @props.item._id, @props.item item = @props.item else item = @props.Repository.getLatest itemId expanded: null item: item componentDidMount: -> @item = ReactiveData.Item key: @props.itemId ? @state.item?._id Repository: @props.Repository @item.listen @, 'item' componentWillUnmount: -> @item.unlisten @ parseMessage: (message) -> return 'WAT.' unless message? linkUrls linkHashtags linkScreenNames message onExpand: (e) -> console.log 'onExpand' e.preventDefault() @setState expanded: true onCollapse: (e) -> e.preventDefault() @setState expanded: false render: -> unless @state.item?._id console.log 'cannot show item yet', @state.item return DOM.div null, 'loading ' + @props.itemId unless @state.item?._id expanded = if @state.expanded? @state.expanded else if @state.item?.attributes?.score? and @props.threshold? @state.item.attributes.score >= @props.threshold else true item = @state.item ? {} identity = item?.identity ? {} Media = @props.getComponent 'kerplunk-stream:streamMedia' DOM.div className: "media stream-item #{if expanded then 'expanded' else 'collapsed'}" onClick: (@onExpand unless expanded) , StreamItemControls _.extend {}, @props, item: item onExpand: @onExpand onCollapse: @onCollapse DOM.div className: 'bd' , Avatar identity: item.identity sourceIcon: @props.globals.public.activityItem.icons?[item.platform] DOM.span className: 'stream-item-author' , DOM.a href: "/admin/identity/view/#{identity._id}" , if identity.fullName and identity.fullName != '' identity.fullName else identity.nickName if identity.fullName and identity.fullName != '' and identity.fullName.toLowerCase().replace(/\s/g,'') != identity.nickName.toLowerCase().replace(/\s/g,'') " (#{identity.nickName})" DOM.p className: 'stream-item-text' dangerouslySetInnerHTML: __html: @parseMessage item.message Media key: "#{item._id}-media" media: item.media
99695
_ = require 'lodash' React = require 'react' ReactiveData = require 'reactive-data' Avatar = require './avatar' # Media = require './streamMedia' StreamItemControls = require './streamItemControls' {DOM} = React linkUrls = (message) -> maxLength = 34 matches = message.match /https?:\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|]/gi if matches for url in matches # Keep the matched URL to use in href, but create a truncated version to display shorter = url shorter = shorter.replace /^http:\/\//, "" shorter = shorter.replace /^https:\/\//, "" shorter = shorter.replace /^www\./, "" if shorter.length > maxLength shorter = shorter.substring(0, maxLength-4) + "..." # Replace instance of matched URL with HTML message = message.replace url, "<a href='#{url}' title='#{url}' class='truncate-link'>#{shorter}</a>" message # Turn hashtags into links linkHashtags = (message) -> hashPattern = /(^|\s)#([-A-Za-z0-9_]+)(\b)/gi message.replace hashPattern, "$1<a href='/topic/bytext/$2'>#$2</a>$3" # Turn @names into links linkScreenNames = (message) -> atPattern = /(^|\s|[^a-zA-Z0-9_\-+])@([-A-Za-z0-9_]+)(\b|\s|[^a-zA-Z0-9]|$)/gi message.replace atPattern, "$1<a href='/identity/byusername/$2'>@$2</a>$3" module.exports = React.createFactory React.createClass getInitialState: -> # console.log 'initial props on streamItem', @props itemId = String @props.item?._id ? @props.itemId if @props.item?._id @props.Repository.update @props.item._id, @props.item item = @props.item else item = @props.Repository.getLatest itemId expanded: null item: item componentDidMount: -> @item = ReactiveData.Item key: @props.itemId ? @state.item?._id Repository: @props.Repository @item.listen @, 'item' componentWillUnmount: -> @item.unlisten @ parseMessage: (message) -> return 'WAT.' unless message? linkUrls linkHashtags linkScreenNames message onExpand: (e) -> console.log 'onExpand' e.preventDefault() @setState expanded: true onCollapse: (e) -> e.preventDefault() @setState expanded: false render: -> unless @state.item?._id console.log 'cannot show item yet', @state.item return DOM.div null, 'loading ' + @props.itemId unless @state.item?._id expanded = if @state.expanded? @state.expanded else if @state.item?.attributes?.score? and @props.threshold? @state.item.attributes.score >= @props.threshold else true item = @state.item ? {} identity = item?.identity ? {} Media = @props.getComponent 'kerplunk-stream:streamMedia' DOM.div className: "media stream-item #{if expanded then 'expanded' else 'collapsed'}" onClick: (@onExpand unless expanded) , StreamItemControls _.extend {}, @props, item: item onExpand: @onExpand onCollapse: @onCollapse DOM.div className: 'bd' , Avatar identity: item.identity sourceIcon: @props.globals.public.activityItem.icons?[item.platform] DOM.span className: 'stream-item-author' , DOM.a href: "/admin/identity/view/#{identity._id}" , if identity.fullName and identity.fullName != '' identity.fullName else identity.nickName if identity.fullName and identity.fullName != '' and identity.fullName.toLowerCase().replace(/\s/g,'') != identity.nickName.toLowerCase().replace(/\s/g,'') " (#{identity.nickName})" DOM.p className: 'stream-item-text' dangerouslySetInnerHTML: __html: @parseMessage item.message Media key: "#{item._<KEY>" media: item.media
true
_ = require 'lodash' React = require 'react' ReactiveData = require 'reactive-data' Avatar = require './avatar' # Media = require './streamMedia' StreamItemControls = require './streamItemControls' {DOM} = React linkUrls = (message) -> maxLength = 34 matches = message.match /https?:\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|]/gi if matches for url in matches # Keep the matched URL to use in href, but create a truncated version to display shorter = url shorter = shorter.replace /^http:\/\//, "" shorter = shorter.replace /^https:\/\//, "" shorter = shorter.replace /^www\./, "" if shorter.length > maxLength shorter = shorter.substring(0, maxLength-4) + "..." # Replace instance of matched URL with HTML message = message.replace url, "<a href='#{url}' title='#{url}' class='truncate-link'>#{shorter}</a>" message # Turn hashtags into links linkHashtags = (message) -> hashPattern = /(^|\s)#([-A-Za-z0-9_]+)(\b)/gi message.replace hashPattern, "$1<a href='/topic/bytext/$2'>#$2</a>$3" # Turn @names into links linkScreenNames = (message) -> atPattern = /(^|\s|[^a-zA-Z0-9_\-+])@([-A-Za-z0-9_]+)(\b|\s|[^a-zA-Z0-9]|$)/gi message.replace atPattern, "$1<a href='/identity/byusername/$2'>@$2</a>$3" module.exports = React.createFactory React.createClass getInitialState: -> # console.log 'initial props on streamItem', @props itemId = String @props.item?._id ? @props.itemId if @props.item?._id @props.Repository.update @props.item._id, @props.item item = @props.item else item = @props.Repository.getLatest itemId expanded: null item: item componentDidMount: -> @item = ReactiveData.Item key: @props.itemId ? @state.item?._id Repository: @props.Repository @item.listen @, 'item' componentWillUnmount: -> @item.unlisten @ parseMessage: (message) -> return 'WAT.' unless message? linkUrls linkHashtags linkScreenNames message onExpand: (e) -> console.log 'onExpand' e.preventDefault() @setState expanded: true onCollapse: (e) -> e.preventDefault() @setState expanded: false render: -> unless @state.item?._id console.log 'cannot show item yet', @state.item return DOM.div null, 'loading ' + @props.itemId unless @state.item?._id expanded = if @state.expanded? @state.expanded else if @state.item?.attributes?.score? and @props.threshold? @state.item.attributes.score >= @props.threshold else true item = @state.item ? {} identity = item?.identity ? {} Media = @props.getComponent 'kerplunk-stream:streamMedia' DOM.div className: "media stream-item #{if expanded then 'expanded' else 'collapsed'}" onClick: (@onExpand unless expanded) , StreamItemControls _.extend {}, @props, item: item onExpand: @onExpand onCollapse: @onCollapse DOM.div className: 'bd' , Avatar identity: item.identity sourceIcon: @props.globals.public.activityItem.icons?[item.platform] DOM.span className: 'stream-item-author' , DOM.a href: "/admin/identity/view/#{identity._id}" , if identity.fullName and identity.fullName != '' identity.fullName else identity.nickName if identity.fullName and identity.fullName != '' and identity.fullName.toLowerCase().replace(/\s/g,'') != identity.nickName.toLowerCase().replace(/\s/g,'') " (#{identity.nickName})" DOM.p className: 'stream-item-text' dangerouslySetInnerHTML: __html: @parseMessage item.message Media key: "#{item._PI:KEY:<KEY>END_PI" media: item.media
[ { "context": "ror \"callback required!\" unless callback\n key = \"#{dbName}.#{cName}\"\n @collectionsCache ?= {}\n unless @collectio", "end": 1163, "score": 0.9778253436088562, "start": 1143, "tag": "KEY", "value": "\"#{dbName}.#{cName}\"" } ]
lib/connection.coffee
adambadawy/mongo-lite
6
NDriver = require 'mongodb' Driver = require './driver' helper = require './helper' _ = require 'underscore' class Driver.Connection # Connect to mongo. constructor: (@options) -> @nServer = new NDriver.Server(@options.host, @options.port, @options.options) db: (name, options = {}) -> new Driver.Db name, @, options getNativeDb: (name, options, callback, next) -> throw new Error "callback required!" unless callback @dbsCache ?= {} unless @dbsCache[name] tmp = new NDriver.Db name, @nServer, options tmp.open (err, nDb) => return callback err if err if @options.username nDb.authenticate @options.username, @options.password, (err, result) => return callback err if err return callback new Error "invalid username or password!" unless result @dbsCache[name] = nDb next nDb else @dbsCache[name] = nDb next nDb else next @dbsCache[name] getNativeCollection: (dbName, dbOptions, cName, cOptions, callback, next) -> throw new Error "callback required!" unless callback key = "#{dbName}.#{cName}" @collectionsCache ?= {} unless @collectionsCache[key] @getNativeDb dbName, dbOptions, callback, (nDb) => nDb.collection cName, cOptions, (err, nCollection) => return callback err if err @collectionsCache[key] = nCollection next nCollection else next @collectionsCache[key]
92318
NDriver = require 'mongodb' Driver = require './driver' helper = require './helper' _ = require 'underscore' class Driver.Connection # Connect to mongo. constructor: (@options) -> @nServer = new NDriver.Server(@options.host, @options.port, @options.options) db: (name, options = {}) -> new Driver.Db name, @, options getNativeDb: (name, options, callback, next) -> throw new Error "callback required!" unless callback @dbsCache ?= {} unless @dbsCache[name] tmp = new NDriver.Db name, @nServer, options tmp.open (err, nDb) => return callback err if err if @options.username nDb.authenticate @options.username, @options.password, (err, result) => return callback err if err return callback new Error "invalid username or password!" unless result @dbsCache[name] = nDb next nDb else @dbsCache[name] = nDb next nDb else next @dbsCache[name] getNativeCollection: (dbName, dbOptions, cName, cOptions, callback, next) -> throw new Error "callback required!" unless callback key = <KEY> @collectionsCache ?= {} unless @collectionsCache[key] @getNativeDb dbName, dbOptions, callback, (nDb) => nDb.collection cName, cOptions, (err, nCollection) => return callback err if err @collectionsCache[key] = nCollection next nCollection else next @collectionsCache[key]
true
NDriver = require 'mongodb' Driver = require './driver' helper = require './helper' _ = require 'underscore' class Driver.Connection # Connect to mongo. constructor: (@options) -> @nServer = new NDriver.Server(@options.host, @options.port, @options.options) db: (name, options = {}) -> new Driver.Db name, @, options getNativeDb: (name, options, callback, next) -> throw new Error "callback required!" unless callback @dbsCache ?= {} unless @dbsCache[name] tmp = new NDriver.Db name, @nServer, options tmp.open (err, nDb) => return callback err if err if @options.username nDb.authenticate @options.username, @options.password, (err, result) => return callback err if err return callback new Error "invalid username or password!" unless result @dbsCache[name] = nDb next nDb else @dbsCache[name] = nDb next nDb else next @dbsCache[name] getNativeCollection: (dbName, dbOptions, cName, cOptions, callback, next) -> throw new Error "callback required!" unless callback key = PI:KEY:<KEY>END_PI @collectionsCache ?= {} unless @collectionsCache[key] @getNativeDb dbName, dbOptions, callback, (nDb) => nDb.collection cName, cOptions, (err, nCollection) => return callback err if err @collectionsCache[key] = nCollection next nCollection else next @collectionsCache[key]
[ { "context": "####\n@send_mail = (to, subject, text) ->\n\tfrom = \"no-reply@mooqita.org\"\n\n\tMeteor.defer () ->\n\t\tlog_event \"Sending mail\",", "end": 625, "score": 0.999484658241272, "start": 605, "tag": "EMAIL", "value": "no-reply@mooqita.org" } ]
server/logic/mail.coffee
MooqitaSFH/worklearn
0
############################################### @send_message_mail = (user, subject, body) -> msg = "@send_message_mail trying to send mail message" log_event msg, event_mail, event_info to = get_user_mail(user) profile = get_profile user if not profile send_mail to, subject, body return #cycle = profile.notification_cycle #last = profile.last_notification #now = new Date() #dif = now - last #if cycle > dif # return if profile.mail_notifications == "yes" send_mail to, subject, body ############################################### @send_mail = (to, subject, text) -> from = "no-reply@mooqita.org" Meteor.defer () -> log_event "Sending mail", event_mail, event_info #TODO: stack trace try Email.send {to, from, subject, text} msg = "Mail send to (" + to + ") : " + subject log_event msg, event_mail, event_info #TODO: stack trace catch error log_event error, event_mail, event_err #TODO: stack trace
212616
############################################### @send_message_mail = (user, subject, body) -> msg = "@send_message_mail trying to send mail message" log_event msg, event_mail, event_info to = get_user_mail(user) profile = get_profile user if not profile send_mail to, subject, body return #cycle = profile.notification_cycle #last = profile.last_notification #now = new Date() #dif = now - last #if cycle > dif # return if profile.mail_notifications == "yes" send_mail to, subject, body ############################################### @send_mail = (to, subject, text) -> from = "<EMAIL>" Meteor.defer () -> log_event "Sending mail", event_mail, event_info #TODO: stack trace try Email.send {to, from, subject, text} msg = "Mail send to (" + to + ") : " + subject log_event msg, event_mail, event_info #TODO: stack trace catch error log_event error, event_mail, event_err #TODO: stack trace
true
############################################### @send_message_mail = (user, subject, body) -> msg = "@send_message_mail trying to send mail message" log_event msg, event_mail, event_info to = get_user_mail(user) profile = get_profile user if not profile send_mail to, subject, body return #cycle = profile.notification_cycle #last = profile.last_notification #now = new Date() #dif = now - last #if cycle > dif # return if profile.mail_notifications == "yes" send_mail to, subject, body ############################################### @send_mail = (to, subject, text) -> from = "PI:EMAIL:<EMAIL>END_PI" Meteor.defer () -> log_event "Sending mail", event_mail, event_info #TODO: stack trace try Email.send {to, from, subject, text} msg = "Mail send to (" + to + ") : " + subject log_event msg, event_mail, event_info #TODO: stack trace catch error log_event error, event_mail, event_err #TODO: stack trace
[ { "context": ": \"users\"\n defaults:\n admin: false\n name: \"Anonymous\"\n class: \"Decker\"\n level: \"A\"\n disabled:", "end": 155, "score": 0.7235009670257568, "start": 146, "tag": "NAME", "value": "Anonymous" } ]
assets/javascripts/models/user.coffee
woochi/cyberia
0
Backbone = require("backbone") class User extends Backbone.Model idAttribute: "_id" backend: "users" defaults: admin: false name: "Anonymous" class: "Decker" level: "A" disabled: false isAdmin: -> @get("admin") module.exports = User
196844
Backbone = require("backbone") class User extends Backbone.Model idAttribute: "_id" backend: "users" defaults: admin: false name: "<NAME>" class: "Decker" level: "A" disabled: false isAdmin: -> @get("admin") module.exports = User
true
Backbone = require("backbone") class User extends Backbone.Model idAttribute: "_id" backend: "users" defaults: admin: false name: "PI:NAME:<NAME>END_PI" class: "Decker" level: "A" disabled: false isAdmin: -> @get("admin") module.exports = User
[ { "context": "Handler\", ->\n\n\tbeforeEach ->\n\n\t\t@user =\n\t\t\temail:\"bob@bob.com\"\n\t\t@UserModel = \n\t\t\tfindById:sinon.stub().callsAr", "end": 371, "score": 0.9999194145202637, "start": 360, "tag": "EMAIL", "value": "bob@bob.com" } ]
test/UnitTests/coffee/Collaborators/CollaboratorsHandlerTests.coffee
ukasiu/web-sharelatex
0
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Collaborators/CollaboratorsHandler" expect = require("chai").expect describe "CollaboratorsHandler", -> beforeEach -> @user = email:"bob@bob.com" @UserModel = findById:sinon.stub().callsArgWith(1, null, @user) update: sinon.stub() @settings = {} @ProjectModel = update: sinon.stub().callsArgWith(1) @CollaboratorHandler = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> err:-> '../../models/User': User:@UserModel "../../models/Project": Project:@ProjectModel @project_id = "123l2j13lkj" @user_id = "132kj1lk2j" describe "changeUsersPrivilegeLevel", -> it "should call removeUserFromProject then addUserToProject", (done)-> @CollaboratorHandler.removeUserFromProject = sinon.stub().callsArgWith(2) @CollaboratorHandler.addUserToProject = sinon.stub().callsArgWith(3) newPrivalageLevel = "readAndWrite" @CollaboratorHandler.changeUsersPrivilegeLevel @project_id, @user_id, newPrivalageLevel, => @CollaboratorHandler.removeUserFromProject.calledWith(@project_id, @user_id).should.equal true @CollaboratorHandler.addUserToProject.calledWith(@project_id, @user_id, newPrivalageLevel) done() describe "removeUserFromProject", -> beforeEach -> @ProjectModel.update.callsArgWith(2) it "should remove the user from mongo", (done)-> @CollaboratorHandler.removeUserFromProject @project_id, @user_id, => update = @ProjectModel.update.args[0][1] assert.deepEqual update, "$pull":{collaberator_refs:@user_id, readOnly_refs:@user_id} done()
147042
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Collaborators/CollaboratorsHandler" expect = require("chai").expect describe "CollaboratorsHandler", -> beforeEach -> @user = email:"<EMAIL>" @UserModel = findById:sinon.stub().callsArgWith(1, null, @user) update: sinon.stub() @settings = {} @ProjectModel = update: sinon.stub().callsArgWith(1) @CollaboratorHandler = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> err:-> '../../models/User': User:@UserModel "../../models/Project": Project:@ProjectModel @project_id = "123l2j13lkj" @user_id = "132kj1lk2j" describe "changeUsersPrivilegeLevel", -> it "should call removeUserFromProject then addUserToProject", (done)-> @CollaboratorHandler.removeUserFromProject = sinon.stub().callsArgWith(2) @CollaboratorHandler.addUserToProject = sinon.stub().callsArgWith(3) newPrivalageLevel = "readAndWrite" @CollaboratorHandler.changeUsersPrivilegeLevel @project_id, @user_id, newPrivalageLevel, => @CollaboratorHandler.removeUserFromProject.calledWith(@project_id, @user_id).should.equal true @CollaboratorHandler.addUserToProject.calledWith(@project_id, @user_id, newPrivalageLevel) done() describe "removeUserFromProject", -> beforeEach -> @ProjectModel.update.callsArgWith(2) it "should remove the user from mongo", (done)-> @CollaboratorHandler.removeUserFromProject @project_id, @user_id, => update = @ProjectModel.update.args[0][1] assert.deepEqual update, "$pull":{collaberator_refs:@user_id, readOnly_refs:@user_id} done()
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Collaborators/CollaboratorsHandler" expect = require("chai").expect describe "CollaboratorsHandler", -> beforeEach -> @user = email:"PI:EMAIL:<EMAIL>END_PI" @UserModel = findById:sinon.stub().callsArgWith(1, null, @user) update: sinon.stub() @settings = {} @ProjectModel = update: sinon.stub().callsArgWith(1) @CollaboratorHandler = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> err:-> '../../models/User': User:@UserModel "../../models/Project": Project:@ProjectModel @project_id = "123l2j13lkj" @user_id = "132kj1lk2j" describe "changeUsersPrivilegeLevel", -> it "should call removeUserFromProject then addUserToProject", (done)-> @CollaboratorHandler.removeUserFromProject = sinon.stub().callsArgWith(2) @CollaboratorHandler.addUserToProject = sinon.stub().callsArgWith(3) newPrivalageLevel = "readAndWrite" @CollaboratorHandler.changeUsersPrivilegeLevel @project_id, @user_id, newPrivalageLevel, => @CollaboratorHandler.removeUserFromProject.calledWith(@project_id, @user_id).should.equal true @CollaboratorHandler.addUserToProject.calledWith(@project_id, @user_id, newPrivalageLevel) done() describe "removeUserFromProject", -> beforeEach -> @ProjectModel.update.callsArgWith(2) it "should remove the user from mongo", (done)-> @CollaboratorHandler.removeUserFromProject @project_id, @user_id, => update = @ProjectModel.update.args[0][1] assert.deepEqual update, "$pull":{collaberator_refs:@user_id, readOnly_refs:@user_id} done()
[ { "context": "# Copyright (c) 2012 Mattes Groeger\n#\n# Permission is hereby granted, free of charge,", "end": 35, "score": 0.9998828172683716, "start": 21, "tag": "NAME", "value": "Mattes Groeger" } ]
src/links.coffee
MattesGroeger/chrome-open-links
14
# Copyright (c) 2012 Mattes Groeger # # 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. LINK_WARNING_AMOUNT = 20 LINK_PREVIEW_THRESHOLD = 10 FILTERS = { all: ".*", image: "\.(jpg|jepg|png|gif|svg)$", video: "\.(mov|qt|swf|flv|mpg|mpe|mpeg|mp2v|m2v|m2s|avi|asf|asx|wmv|wma|wmx|rm|ra|ram|rmvb|mp4|3g2|3gp|ogm|mkv)$", audio: "\.(mp3|m4a|mpa|ra|wav|wma|aif|iff|mid)$" } @links = [] @linksForFilter = {} @previewAmount = 0 @previewLinks = {} createContextMenu = -> chrome.contextMenus.create({contexts:["all"], id:"parent", title:chrome.i18n.getMessage("menu_main")}) chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"all", title:chrome.i18n.getMessage("menu_sub_all")}) chrome.contextMenus.create({contexts:["all"], parentId:"parent", type:"separator"}) for own key, value of FILTERS when key != "all" chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:key, title:chrome.i18n.getMessage("menu_sub_#{key}")}) updateContextMenus() onMessageHandler = (request, sender, sendResponse) -> if request.type == "verifySelection" @links = filterLinks(FILTERS["all"], request.links) updateContextMenus() updateContextMenus = -> renderPreviewContextMenus() for own key, value of FILTERS @linksForFilter[key] = filterLinks(value, @links) updateContextMenu(key) renderPreviewContextMenus = -> clearPreviewContextMenus() @previewAmount = Math.min(@links.length, LINK_PREVIEW_THRESHOLD) if @previewAmount > 0 chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"preview_separator", type:"separator"}) for i in [0...@previewAmount] @previewLinks["preview#{i}"] = @links[i] chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"preview#{i}", title:@links[i]}) clearPreviewContextMenus = -> if @previewAmount > 0 chrome.contextMenus.remove("preview_separator") for i in [0...@previewAmount] chrome.contextMenus.remove("preview#{i}") @previewAmount = 0 @previewLinks = {} filterLinks = (filter, links) -> link for link in links when link.match(new RegExp(filter, "i")) updateContextMenu = (id) -> links = @linksForFilter[id] title = chrome.i18n.getMessage("menu_sub_#{id}", [links.length]) chrome.contextMenus.update(id, {title:title, enabled:links.length > 0}) onClickHandler = (info, tab) -> previewLink = @previewLinks[info.menuItemId] if previewLink openLink(previewLink, tab) else links = @linksForFilter[info.menuItemId] if links.length <= LINK_WARNING_AMOUNT or confirm(chrome.i18n.getMessage("selection_alert_tooManyLinks", [links.length])) for link in links.reverse() openLink(link, tab) openLink = (url, currentTab) -> chrome.tabs.create({url:url,index:currentTab.index+1}) createContextMenu() chrome.extension.onMessage.addListener(onMessageHandler) chrome.contextMenus.onClicked.addListener(onClickHandler)
146726
# Copyright (c) 2012 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. LINK_WARNING_AMOUNT = 20 LINK_PREVIEW_THRESHOLD = 10 FILTERS = { all: ".*", image: "\.(jpg|jepg|png|gif|svg)$", video: "\.(mov|qt|swf|flv|mpg|mpe|mpeg|mp2v|m2v|m2s|avi|asf|asx|wmv|wma|wmx|rm|ra|ram|rmvb|mp4|3g2|3gp|ogm|mkv)$", audio: "\.(mp3|m4a|mpa|ra|wav|wma|aif|iff|mid)$" } @links = [] @linksForFilter = {} @previewAmount = 0 @previewLinks = {} createContextMenu = -> chrome.contextMenus.create({contexts:["all"], id:"parent", title:chrome.i18n.getMessage("menu_main")}) chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"all", title:chrome.i18n.getMessage("menu_sub_all")}) chrome.contextMenus.create({contexts:["all"], parentId:"parent", type:"separator"}) for own key, value of FILTERS when key != "all" chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:key, title:chrome.i18n.getMessage("menu_sub_#{key}")}) updateContextMenus() onMessageHandler = (request, sender, sendResponse) -> if request.type == "verifySelection" @links = filterLinks(FILTERS["all"], request.links) updateContextMenus() updateContextMenus = -> renderPreviewContextMenus() for own key, value of FILTERS @linksForFilter[key] = filterLinks(value, @links) updateContextMenu(key) renderPreviewContextMenus = -> clearPreviewContextMenus() @previewAmount = Math.min(@links.length, LINK_PREVIEW_THRESHOLD) if @previewAmount > 0 chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"preview_separator", type:"separator"}) for i in [0...@previewAmount] @previewLinks["preview#{i}"] = @links[i] chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"preview#{i}", title:@links[i]}) clearPreviewContextMenus = -> if @previewAmount > 0 chrome.contextMenus.remove("preview_separator") for i in [0...@previewAmount] chrome.contextMenus.remove("preview#{i}") @previewAmount = 0 @previewLinks = {} filterLinks = (filter, links) -> link for link in links when link.match(new RegExp(filter, "i")) updateContextMenu = (id) -> links = @linksForFilter[id] title = chrome.i18n.getMessage("menu_sub_#{id}", [links.length]) chrome.contextMenus.update(id, {title:title, enabled:links.length > 0}) onClickHandler = (info, tab) -> previewLink = @previewLinks[info.menuItemId] if previewLink openLink(previewLink, tab) else links = @linksForFilter[info.menuItemId] if links.length <= LINK_WARNING_AMOUNT or confirm(chrome.i18n.getMessage("selection_alert_tooManyLinks", [links.length])) for link in links.reverse() openLink(link, tab) openLink = (url, currentTab) -> chrome.tabs.create({url:url,index:currentTab.index+1}) createContextMenu() chrome.extension.onMessage.addListener(onMessageHandler) chrome.contextMenus.onClicked.addListener(onClickHandler)
true
# Copyright (c) 2012 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. LINK_WARNING_AMOUNT = 20 LINK_PREVIEW_THRESHOLD = 10 FILTERS = { all: ".*", image: "\.(jpg|jepg|png|gif|svg)$", video: "\.(mov|qt|swf|flv|mpg|mpe|mpeg|mp2v|m2v|m2s|avi|asf|asx|wmv|wma|wmx|rm|ra|ram|rmvb|mp4|3g2|3gp|ogm|mkv)$", audio: "\.(mp3|m4a|mpa|ra|wav|wma|aif|iff|mid)$" } @links = [] @linksForFilter = {} @previewAmount = 0 @previewLinks = {} createContextMenu = -> chrome.contextMenus.create({contexts:["all"], id:"parent", title:chrome.i18n.getMessage("menu_main")}) chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"all", title:chrome.i18n.getMessage("menu_sub_all")}) chrome.contextMenus.create({contexts:["all"], parentId:"parent", type:"separator"}) for own key, value of FILTERS when key != "all" chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:key, title:chrome.i18n.getMessage("menu_sub_#{key}")}) updateContextMenus() onMessageHandler = (request, sender, sendResponse) -> if request.type == "verifySelection" @links = filterLinks(FILTERS["all"], request.links) updateContextMenus() updateContextMenus = -> renderPreviewContextMenus() for own key, value of FILTERS @linksForFilter[key] = filterLinks(value, @links) updateContextMenu(key) renderPreviewContextMenus = -> clearPreviewContextMenus() @previewAmount = Math.min(@links.length, LINK_PREVIEW_THRESHOLD) if @previewAmount > 0 chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"preview_separator", type:"separator"}) for i in [0...@previewAmount] @previewLinks["preview#{i}"] = @links[i] chrome.contextMenus.create({contexts:["all"], parentId:"parent", id:"preview#{i}", title:@links[i]}) clearPreviewContextMenus = -> if @previewAmount > 0 chrome.contextMenus.remove("preview_separator") for i in [0...@previewAmount] chrome.contextMenus.remove("preview#{i}") @previewAmount = 0 @previewLinks = {} filterLinks = (filter, links) -> link for link in links when link.match(new RegExp(filter, "i")) updateContextMenu = (id) -> links = @linksForFilter[id] title = chrome.i18n.getMessage("menu_sub_#{id}", [links.length]) chrome.contextMenus.update(id, {title:title, enabled:links.length > 0}) onClickHandler = (info, tab) -> previewLink = @previewLinks[info.menuItemId] if previewLink openLink(previewLink, tab) else links = @linksForFilter[info.menuItemId] if links.length <= LINK_WARNING_AMOUNT or confirm(chrome.i18n.getMessage("selection_alert_tooManyLinks", [links.length])) for link in links.reverse() openLink(link, tab) openLink = (url, currentTab) -> chrome.tabs.create({url:url,index:currentTab.index+1}) createContextMenu() chrome.extension.onMessage.addListener(onMessageHandler) chrome.contextMenus.onClicked.addListener(onClickHandler)
[ { "context": "lter_\n\n persons = [\n age: 20\n name: '1'\n ,\n age: 15\n name: '2'\n ,\n ", "end": 227, "score": 0.9769272804260254, "start": 226, "tag": "NAME", "value": "1" }, { "context": "\n name: '1'\n ,\n age: 15\n name: '2'\...
src/filter/appSpec.coffee
boiawang/angular-tutorial
1
describe 'filter', () -> orderAgeFilter = null persons = null beforeEach module('app.filter') beforeEach inject (_orderAgeFilter_) -> orderAgeFilter = _orderAgeFilter_ persons = [ age: 20 name: '1' , age: 15 name: '2' , age: 26 name: '3' ] it 'should order by age', () -> expect(orderAgeFilter(persons)[0].age).toBe(15) expect(orderAgeFilter(persons)[1].age).toBe(20) expect(orderAgeFilter(persons)[2].age).toBe(26)
140837
describe 'filter', () -> orderAgeFilter = null persons = null beforeEach module('app.filter') beforeEach inject (_orderAgeFilter_) -> orderAgeFilter = _orderAgeFilter_ persons = [ age: 20 name: '<NAME>' , age: 15 name: '<NAME>' , age: 26 name: '<NAME>' ] it 'should order by age', () -> expect(orderAgeFilter(persons)[0].age).toBe(15) expect(orderAgeFilter(persons)[1].age).toBe(20) expect(orderAgeFilter(persons)[2].age).toBe(26)
true
describe 'filter', () -> orderAgeFilter = null persons = null beforeEach module('app.filter') beforeEach inject (_orderAgeFilter_) -> orderAgeFilter = _orderAgeFilter_ persons = [ age: 20 name: 'PI:NAME:<NAME>END_PI' , age: 15 name: 'PI:NAME:<NAME>END_PI' , age: 26 name: 'PI:NAME:<NAME>END_PI' ] it 'should order by age', () -> expect(orderAgeFilter(persons)[0].age).toBe(15) expect(orderAgeFilter(persons)[1].age).toBe(20) expect(orderAgeFilter(persons)[2].age).toBe(26)
[ { "context": "Country 2: Diddy Kong's Quest\"]\n\t\tform:\n\t\t\tname: \"King K. Rool\"\n\t\t\temail: \"king@example.com\"\n\t\t\tnames:\n\t\t\t\tjapan", "end": 340, "score": 0.9998990297317505, "start": 328, "tag": "NAME", "value": "King K. Rool" }, { "context": "uest\"]\n\t\tform:\...
tests/unit/utils/analytics-logger-test.coffee
dk-dev/balanced-dashboard
169
`import AnalyticsLogger from "balanced-dashboard/utils/analytics_logger";` module('balanced-dashboard/utils/analytics_logger') test "#flattenEventData", -> data = AnalyticsLogger.flattenEventData( serie: "Donkey Kong Country" games: ["Donkey Kong Country", "Donkey Kong Country 2: Diddy Kong's Quest"] form: name: "King K. Rool" email: "king@example.com" names: japan: "Kingu Kururu" french: "Roi K. Rool" dutch: "Koning Wreed" german: "King Kroko" ) deepEqual(data, "serie": "Donkey Kong Country" "games.0": "Donkey Kong Country" "games.1": "Donkey Kong Country 2: Diddy Kong's Quest" "form.name": "King K. Rool" "form.email": "king@example.com" "form.names.japan": "Kingu Kururu" "form.names.french": "Roi K. Rool" "form.names.dutch": "Koning Wreed" "form.names.german": "King Kroko" )
31156
`import AnalyticsLogger from "balanced-dashboard/utils/analytics_logger";` module('balanced-dashboard/utils/analytics_logger') test "#flattenEventData", -> data = AnalyticsLogger.flattenEventData( serie: "Donkey Kong Country" games: ["Donkey Kong Country", "Donkey Kong Country 2: Diddy Kong's Quest"] form: name: "<NAME>" email: "<EMAIL>" names: japan: "<NAME>" french: "<NAME>" dutch: "<NAME>" german: "<NAME>" ) deepEqual(data, "serie": "Donkey Kong Country" "games.0": "Donkey Kong Country" "games.1": "Donkey Kong Country 2: Diddy Kong's Quest" "form.name": "<NAME>" "form.email": "<EMAIL>" "form.names.japan": "<NAME>" "form.names.french": "<NAME>" "form.names.dutch": "<NAME>" "form.names.german": "<NAME>" )
true
`import AnalyticsLogger from "balanced-dashboard/utils/analytics_logger";` module('balanced-dashboard/utils/analytics_logger') test "#flattenEventData", -> data = AnalyticsLogger.flattenEventData( serie: "Donkey Kong Country" games: ["Donkey Kong Country", "Donkey Kong Country 2: Diddy Kong's Quest"] form: name: "PI:NAME:<NAME>END_PI" email: "PI:EMAIL:<EMAIL>END_PI" names: japan: "PI:NAME:<NAME>END_PI" french: "PI:NAME:<NAME>END_PI" dutch: "PI:NAME:<NAME>END_PI" german: "PI:NAME:<NAME>END_PI" ) deepEqual(data, "serie": "Donkey Kong Country" "games.0": "Donkey Kong Country" "games.1": "Donkey Kong Country 2: Diddy Kong's Quest" "form.name": "PI:NAME:<NAME>END_PI" "form.email": "PI:EMAIL:<EMAIL>END_PI" "form.names.japan": "PI:NAME:<NAME>END_PI" "form.names.french": "PI:NAME:<NAME>END_PI" "form.names.dutch": "PI:NAME:<NAME>END_PI" "form.names.german": "PI:NAME:<NAME>END_PI" )
[ { "context": "#{fileName}\"\n s3Context.assetCount += 1\n s3Key = \"#{s3Context.baseLocation}/#{language}/#{fileName}\"\n validateS3PathName(s3Key)\n md5 = md5File.sync(", "end": 3257, "score": 0.8614034652709961, "start": 3206, "tag": "KEY", "value": "\"#{s3Context.baseLocation}/#{langu...
packages/litexa-deploy-aws/src/utils/s3Utils.coffee
fboerncke/litexa
1
### # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ### path = require 'path' fs = require 'fs' md5File = require 'md5-file' mime = require 'mime' validateS3BucketName = (bucketName) -> safeNameRegex = /(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)/g unless bucketName.match safeNameRegex throw new Error "S3 bucket name '#{bucketName}' does not follow the rules for bucket naming in https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html. Please rename your bucket in the Litexa config to follow these guidelines and try again." validateS3PathName = (str) -> unsafeCharacterRegex = /[^0-9a-zA-Z\_\-\.\/]/g if str.match unsafeCharacterRegex throw new Error "S3 upload failed, disallowed name: `#{str}`" prepareBucket = ({ s3Context, skillContext, logger }) -> skillContext.S3.listBuckets({}).promise() .then (data) -> for bucket in data.Buckets if bucket.Name == s3Context.bucketName logger.log "found S3 bucket #{s3Context.bucketName}" return Promise.resolve() skillContext.S3.createBucket({}).promise() .then (info) -> logger.log "created S3 bucket #{s3Context.bucketName}" return Promise.resolve() collectUploadInfo = ({ s3Context, skillContext, logger, md5Override }) -> md5File = md5Override ? md5File logger.log "scanning assets, preparing hashes" s3Context.assetCount = 0 s3Context.deployedIconAssets = {} languageInfo = skillContext.skill.projectInfo.languages findAndRegisterFilesToUpload { s3Context, languageInfo, logger } if s3Context.deployedIconAssets? skillContext.artifacts.save 'deployedIconAssets', s3Context.deployedIconAssets # Clean up deprecated artifact key, to declutter old artifacts files. # @TODO: This can eventually be removed. skillContext.artifacts.delete 'required-assets' logger.log "scanned #{s3Context.assetCount} assets in project" findAndRegisterFilesToUpload = ({ s3Context, languageInfo, logger }) -> assetTypes = [ 'assets', 'convertedAssets'] for language, languageSummary of languageInfo for assetKey in assetTypes assets = languageSummary[assetKey] return unless assets? for fileName in assets.files fileDir = assets.root registerFileForUpload { s3Context, fileDir, fileName, language } unless language == 'default' defaultAssets = languageInfo.default[assetKey] # If we find default assets that aren't overridden in this language, # upload duplicates of the default files to this language. for fileName in defaultAssets.files unless assets.files.includes(fileName) fileDir = defaultAssets.root registerFileForUpload { s3Context, fileDir, fileName, language } registerFileForUpload = ({ s3Context, fileDir, fileName, language }) -> sourceFilePath = "#{fileDir}/#{fileName}" s3Context.assetCount += 1 s3Key = "#{s3Context.baseLocation}/#{language}/#{fileName}" validateS3PathName(s3Key) md5 = md5File.sync(sourceFilePath) s3Context.assets[s3Key] = { name: fileName sourceFilename: sourceFilePath md5: md5 md5Brief: md5.slice(md5.length - 8) needsUpload: true } # If we're deploying icon asset files, track them so we can use them if the user doesn't # specify their own icon URIs in the manifest. iconFileNames = [ 'icon-108.png', 'icon-512.png' ] if iconFileNames.includes(fileName) s3Context.deployedIconAssets[language] = s3Context.deployedIconAssets[language] ? {} s3Context.deployedIconAssets[language][fileName] = { url: "#{s3Context.RESTRoot}/#{s3Key}" md5: md5 } listBucketAndUploadAssets = ({ s3Context, skillContext, logger, startToken }) -> # Start by listing all the objects in the bucket so we get their MD5 hashes. # Note: Since we might have to page, this function is recursive. params = { Prefix: s3Context.baseLocation ContinuationToken: startToken ? undefined MaxKeys: 1000 } rangeStart = s3Context.listPage * params.MaxKeys range = "[#{rangeStart}-#{rangeStart + params.MaxKeys}]" logger.log "fetching S3 object metadata #{range}" s3Context.listPage += 1 skillContext.S3.listObjectsV2(params).promise() .then (data) -> # Now we can compare each file to upload against existing uploads, to avoid spending time on # redundant uploads. for obj in data.Contents continue unless obj.Key of s3Context.assets info = s3Context.assets[obj.Key] info.s3MD5 = JSON.parse obj.ETag info.needsUpload = info.s3MD5 != info.md5 # If we've paged, then also add the next page step. if data.IsTruncated startToken = data.NextContinuationToken listBucketAndUploadAssets { s3Context, skillContext, logger, startToken } else uploadAssets { s3Context, skillContext, logger } uploadAssets = ({ s3Context, skillContext, logger }) -> # collect the final work list s3Context.uploads = [] for key, info of s3Context.assets if info.needsUpload info.key = key s3Context.uploads.push info else logger.verbose "skipping #{info.name} [#{info.md5Brief}]" logger.log "#{s3Context.uploads.length} assets need uploading" uploadBatch { s3Context, skillContext, logger } uploadBatch = ({ s3Context, skillContext, logger }) -> # Upload in batches to limit connection and open file handles, and get a better idea of progress. # This function recurs until we're done. if s3Context.uploads.length == 0 return endUploadAssets { s3Context, skillContext, logger } uploadPromises = [] maxUploads = 5 for i in [0...maxUploads] break if s3Context.uploads.length == 0 job = s3Context.uploads.shift() params = { Key: job.key Body: fs.createReadStream job.sourceFilename ACL: "public-read" ContentType: mime.getType job.sourceFilename } logger.log "uploading #{job.name} -> #{job.key} [#{job.md5Brief}]" uploadPromises.push skillContext.S3.upload(params).promise() logger.log "#{s3Context.uploads.length} assets remaining in queue" startTime = new Date Promise.all(uploadPromises).then -> logger.log "segment uploaded in #{(new Date) - startTime}ms" uploadBatch { s3Context, skillContext, logger } endUploadAssets = ({ s3Context, skillContext, logger }) -> deltaTime = (new Date()) - skillContext.assetDeploymentStart logger.log "asset deployment complete in #{deltaTime}ms" Promise.resolve() module.exports = { collectUploadInfo listBucketAndUploadAssets prepareBucket validateS3BucketName validateS3PathName }
219001
### # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ### path = require 'path' fs = require 'fs' md5File = require 'md5-file' mime = require 'mime' validateS3BucketName = (bucketName) -> safeNameRegex = /(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)/g unless bucketName.match safeNameRegex throw new Error "S3 bucket name '#{bucketName}' does not follow the rules for bucket naming in https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html. Please rename your bucket in the Litexa config to follow these guidelines and try again." validateS3PathName = (str) -> unsafeCharacterRegex = /[^0-9a-zA-Z\_\-\.\/]/g if str.match unsafeCharacterRegex throw new Error "S3 upload failed, disallowed name: `#{str}`" prepareBucket = ({ s3Context, skillContext, logger }) -> skillContext.S3.listBuckets({}).promise() .then (data) -> for bucket in data.Buckets if bucket.Name == s3Context.bucketName logger.log "found S3 bucket #{s3Context.bucketName}" return Promise.resolve() skillContext.S3.createBucket({}).promise() .then (info) -> logger.log "created S3 bucket #{s3Context.bucketName}" return Promise.resolve() collectUploadInfo = ({ s3Context, skillContext, logger, md5Override }) -> md5File = md5Override ? md5File logger.log "scanning assets, preparing hashes" s3Context.assetCount = 0 s3Context.deployedIconAssets = {} languageInfo = skillContext.skill.projectInfo.languages findAndRegisterFilesToUpload { s3Context, languageInfo, logger } if s3Context.deployedIconAssets? skillContext.artifacts.save 'deployedIconAssets', s3Context.deployedIconAssets # Clean up deprecated artifact key, to declutter old artifacts files. # @TODO: This can eventually be removed. skillContext.artifacts.delete 'required-assets' logger.log "scanned #{s3Context.assetCount} assets in project" findAndRegisterFilesToUpload = ({ s3Context, languageInfo, logger }) -> assetTypes = [ 'assets', 'convertedAssets'] for language, languageSummary of languageInfo for assetKey in assetTypes assets = languageSummary[assetKey] return unless assets? for fileName in assets.files fileDir = assets.root registerFileForUpload { s3Context, fileDir, fileName, language } unless language == 'default' defaultAssets = languageInfo.default[assetKey] # If we find default assets that aren't overridden in this language, # upload duplicates of the default files to this language. for fileName in defaultAssets.files unless assets.files.includes(fileName) fileDir = defaultAssets.root registerFileForUpload { s3Context, fileDir, fileName, language } registerFileForUpload = ({ s3Context, fileDir, fileName, language }) -> sourceFilePath = "#{fileDir}/#{fileName}" s3Context.assetCount += 1 s3Key = <KEY> validateS3PathName(s3Key) md5 = md5File.sync(sourceFilePath) s3Context.assets[s3Key] = { name: fileName sourceFilename: sourceFilePath md5: md5 md5Brief: md5.slice(md5.length - 8) needsUpload: true } # If we're deploying icon asset files, track them so we can use them if the user doesn't # specify their own icon URIs in the manifest. iconFileNames = [ 'icon-108.png', 'icon-512.png' ] if iconFileNames.includes(fileName) s3Context.deployedIconAssets[language] = s3Context.deployedIconAssets[language] ? {} s3Context.deployedIconAssets[language][fileName] = { url: "#{s3Context.RESTRoot}/#{s3Key}" md5: md5 } listBucketAndUploadAssets = ({ s3Context, skillContext, logger, startToken }) -> # Start by listing all the objects in the bucket so we get their MD5 hashes. # Note: Since we might have to page, this function is recursive. params = { Prefix: s3Context.baseLocation ContinuationToken: startToken ? undefined MaxKeys: 1000 } rangeStart = s3Context.listPage * params.MaxKeys range = "[#{rangeStart}-#{rangeStart + params.MaxKeys}]" logger.log "fetching S3 object metadata #{range}" s3Context.listPage += 1 skillContext.S3.listObjectsV2(params).promise() .then (data) -> # Now we can compare each file to upload against existing uploads, to avoid spending time on # redundant uploads. for obj in data.Contents continue unless obj.Key of s3Context.assets info = s3Context.assets[obj.Key] info.s3MD5 = JSON.parse obj.ETag info.needsUpload = info.s3MD5 != info.md5 # If we've paged, then also add the next page step. if data.IsTruncated startToken = data.NextContinuationToken listBucketAndUploadAssets { s3Context, skillContext, logger, startToken } else uploadAssets { s3Context, skillContext, logger } uploadAssets = ({ s3Context, skillContext, logger }) -> # collect the final work list s3Context.uploads = [] for key, info of s3Context.assets if info.needsUpload info.key = key s3Context.uploads.push info else logger.verbose "skipping #{info.name} [#{info.md5Brief}]" logger.log "#{s3Context.uploads.length} assets need uploading" uploadBatch { s3Context, skillContext, logger } uploadBatch = ({ s3Context, skillContext, logger }) -> # Upload in batches to limit connection and open file handles, and get a better idea of progress. # This function recurs until we're done. if s3Context.uploads.length == 0 return endUploadAssets { s3Context, skillContext, logger } uploadPromises = [] maxUploads = 5 for i in [0...maxUploads] break if s3Context.uploads.length == 0 job = s3Context.uploads.shift() params = { Key: job.key Body: fs.createReadStream job.sourceFilename ACL: "public-read" ContentType: mime.getType job.sourceFilename } logger.log "uploading #{job.name} -> #{job.key} [#{job.md5Brief}]" uploadPromises.push skillContext.S3.upload(params).promise() logger.log "#{s3Context.uploads.length} assets remaining in queue" startTime = new Date Promise.all(uploadPromises).then -> logger.log "segment uploaded in #{(new Date) - startTime}ms" uploadBatch { s3Context, skillContext, logger } endUploadAssets = ({ s3Context, skillContext, logger }) -> deltaTime = (new Date()) - skillContext.assetDeploymentStart logger.log "asset deployment complete in #{deltaTime}ms" Promise.resolve() module.exports = { collectUploadInfo listBucketAndUploadAssets prepareBucket validateS3BucketName validateS3PathName }
true
### # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ### path = require 'path' fs = require 'fs' md5File = require 'md5-file' mime = require 'mime' validateS3BucketName = (bucketName) -> safeNameRegex = /(?=^.{3,63}$)(?!^(\d+\.)+\d+$)(^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$)/g unless bucketName.match safeNameRegex throw new Error "S3 bucket name '#{bucketName}' does not follow the rules for bucket naming in https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html. Please rename your bucket in the Litexa config to follow these guidelines and try again." validateS3PathName = (str) -> unsafeCharacterRegex = /[^0-9a-zA-Z\_\-\.\/]/g if str.match unsafeCharacterRegex throw new Error "S3 upload failed, disallowed name: `#{str}`" prepareBucket = ({ s3Context, skillContext, logger }) -> skillContext.S3.listBuckets({}).promise() .then (data) -> for bucket in data.Buckets if bucket.Name == s3Context.bucketName logger.log "found S3 bucket #{s3Context.bucketName}" return Promise.resolve() skillContext.S3.createBucket({}).promise() .then (info) -> logger.log "created S3 bucket #{s3Context.bucketName}" return Promise.resolve() collectUploadInfo = ({ s3Context, skillContext, logger, md5Override }) -> md5File = md5Override ? md5File logger.log "scanning assets, preparing hashes" s3Context.assetCount = 0 s3Context.deployedIconAssets = {} languageInfo = skillContext.skill.projectInfo.languages findAndRegisterFilesToUpload { s3Context, languageInfo, logger } if s3Context.deployedIconAssets? skillContext.artifacts.save 'deployedIconAssets', s3Context.deployedIconAssets # Clean up deprecated artifact key, to declutter old artifacts files. # @TODO: This can eventually be removed. skillContext.artifacts.delete 'required-assets' logger.log "scanned #{s3Context.assetCount} assets in project" findAndRegisterFilesToUpload = ({ s3Context, languageInfo, logger }) -> assetTypes = [ 'assets', 'convertedAssets'] for language, languageSummary of languageInfo for assetKey in assetTypes assets = languageSummary[assetKey] return unless assets? for fileName in assets.files fileDir = assets.root registerFileForUpload { s3Context, fileDir, fileName, language } unless language == 'default' defaultAssets = languageInfo.default[assetKey] # If we find default assets that aren't overridden in this language, # upload duplicates of the default files to this language. for fileName in defaultAssets.files unless assets.files.includes(fileName) fileDir = defaultAssets.root registerFileForUpload { s3Context, fileDir, fileName, language } registerFileForUpload = ({ s3Context, fileDir, fileName, language }) -> sourceFilePath = "#{fileDir}/#{fileName}" s3Context.assetCount += 1 s3Key = PI:KEY:<KEY>END_PI validateS3PathName(s3Key) md5 = md5File.sync(sourceFilePath) s3Context.assets[s3Key] = { name: fileName sourceFilename: sourceFilePath md5: md5 md5Brief: md5.slice(md5.length - 8) needsUpload: true } # If we're deploying icon asset files, track them so we can use them if the user doesn't # specify their own icon URIs in the manifest. iconFileNames = [ 'icon-108.png', 'icon-512.png' ] if iconFileNames.includes(fileName) s3Context.deployedIconAssets[language] = s3Context.deployedIconAssets[language] ? {} s3Context.deployedIconAssets[language][fileName] = { url: "#{s3Context.RESTRoot}/#{s3Key}" md5: md5 } listBucketAndUploadAssets = ({ s3Context, skillContext, logger, startToken }) -> # Start by listing all the objects in the bucket so we get their MD5 hashes. # Note: Since we might have to page, this function is recursive. params = { Prefix: s3Context.baseLocation ContinuationToken: startToken ? undefined MaxKeys: 1000 } rangeStart = s3Context.listPage * params.MaxKeys range = "[#{rangeStart}-#{rangeStart + params.MaxKeys}]" logger.log "fetching S3 object metadata #{range}" s3Context.listPage += 1 skillContext.S3.listObjectsV2(params).promise() .then (data) -> # Now we can compare each file to upload against existing uploads, to avoid spending time on # redundant uploads. for obj in data.Contents continue unless obj.Key of s3Context.assets info = s3Context.assets[obj.Key] info.s3MD5 = JSON.parse obj.ETag info.needsUpload = info.s3MD5 != info.md5 # If we've paged, then also add the next page step. if data.IsTruncated startToken = data.NextContinuationToken listBucketAndUploadAssets { s3Context, skillContext, logger, startToken } else uploadAssets { s3Context, skillContext, logger } uploadAssets = ({ s3Context, skillContext, logger }) -> # collect the final work list s3Context.uploads = [] for key, info of s3Context.assets if info.needsUpload info.key = key s3Context.uploads.push info else logger.verbose "skipping #{info.name} [#{info.md5Brief}]" logger.log "#{s3Context.uploads.length} assets need uploading" uploadBatch { s3Context, skillContext, logger } uploadBatch = ({ s3Context, skillContext, logger }) -> # Upload in batches to limit connection and open file handles, and get a better idea of progress. # This function recurs until we're done. if s3Context.uploads.length == 0 return endUploadAssets { s3Context, skillContext, logger } uploadPromises = [] maxUploads = 5 for i in [0...maxUploads] break if s3Context.uploads.length == 0 job = s3Context.uploads.shift() params = { Key: job.key Body: fs.createReadStream job.sourceFilename ACL: "public-read" ContentType: mime.getType job.sourceFilename } logger.log "uploading #{job.name} -> #{job.key} [#{job.md5Brief}]" uploadPromises.push skillContext.S3.upload(params).promise() logger.log "#{s3Context.uploads.length} assets remaining in queue" startTime = new Date Promise.all(uploadPromises).then -> logger.log "segment uploaded in #{(new Date) - startTime}ms" uploadBatch { s3Context, skillContext, logger } endUploadAssets = ({ s3Context, skillContext, logger }) -> deltaTime = (new Date()) - skillContext.assetDeploymentStart logger.log "asset deployment complete in #{deltaTime}ms" Promise.resolve() module.exports = { collectUploadInfo listBucketAndUploadAssets prepareBucket validateS3BucketName validateS3PathName }
[ { "context": "pe codo\n\t\t\tdir: 'target/coffeedoc/main'\n\t\t\tname: 'Kermit(main)'\n\t\t\ttitle: 'Kermit(main)'\n\t\t\treadme: 'do", "end": 359, "score": 0.6704367399215698, "start": 356, "tag": "NAME", "value": "Ker" }, { "context": "pipe codo\n\t\tdir: 'target/coffeedoc/test'\n\...
build/build.doc.coffee
open-medicine-initiative/webcherries
6
gulp = require 'gulp' codo = require 'gulp-codo' ghPages = require 'gulp-gh-pages' clean = require 'gulp-clean' gulp.task 'doc:clean', -> gulp.src [ 'target/coffeedoc' ], read : false .pipe clean force : true gencodo = () -> gulp.src ['src/**/*.coffee', '!src/**/*.spec*.coffee'], read: false .pipe codo dir: 'target/coffeedoc/main' name: 'Kermit(main)' title: 'Kermit(main)' readme: 'doc/main.intro.md' verbose : true extra: ['LICENSE.md'] gencodo.description = 'Generate main coffee documentation' gencodo_test = () -> gulp.src ['./src/**/*spec*.coffee'], read: false .pipe codo dir: 'target/coffeedoc/test' name: 'Kermit(test)' title: 'Kermit(test)' readme: 'doc/test.intro.md' extra: ['LICENSE.md'] gencodo_test.description = 'Generate documentation of test classes' docsToGhPages = () -> gulp.src './target/site/**/*' .pipe ghPages() docsToGhPages.description = "Publishes the coffeedoc documentation to " # Register tasks with gulp gulp.task 'doc:coffee', gencodo gulp.task 'doc:coffee:test', gencodo_test gulp.task 'doc:deploy', docsToGhPages gulp.task 'doc:assemble', gulp.series 'doc:clean', gulp.parallel( "doc:coffee",'doc:coffee:test'), -> input = ["./target/coffeedoc/**/*", './doc/index.html'] gulp.src input .pipe gulp.dest './target/site' gulp.task 'doc:all', gulp.series 'doc:assemble', 'doc:deploy'
115818
gulp = require 'gulp' codo = require 'gulp-codo' ghPages = require 'gulp-gh-pages' clean = require 'gulp-clean' gulp.task 'doc:clean', -> gulp.src [ 'target/coffeedoc' ], read : false .pipe clean force : true gencodo = () -> gulp.src ['src/**/*.coffee', '!src/**/*.spec*.coffee'], read: false .pipe codo dir: 'target/coffeedoc/main' name: '<NAME>mit(main)' title: 'Kermit(main)' readme: 'doc/main.intro.md' verbose : true extra: ['LICENSE.md'] gencodo.description = 'Generate main coffee documentation' gencodo_test = () -> gulp.src ['./src/**/*spec*.coffee'], read: false .pipe codo dir: 'target/coffeedoc/test' name: '<NAME>mit(test)' title: 'Kermit(test)' readme: 'doc/test.intro.md' extra: ['LICENSE.md'] gencodo_test.description = 'Generate documentation of test classes' docsToGhPages = () -> gulp.src './target/site/**/*' .pipe ghPages() docsToGhPages.description = "Publishes the coffeedoc documentation to " # Register tasks with gulp gulp.task 'doc:coffee', gencodo gulp.task 'doc:coffee:test', gencodo_test gulp.task 'doc:deploy', docsToGhPages gulp.task 'doc:assemble', gulp.series 'doc:clean', gulp.parallel( "doc:coffee",'doc:coffee:test'), -> input = ["./target/coffeedoc/**/*", './doc/index.html'] gulp.src input .pipe gulp.dest './target/site' gulp.task 'doc:all', gulp.series 'doc:assemble', 'doc:deploy'
true
gulp = require 'gulp' codo = require 'gulp-codo' ghPages = require 'gulp-gh-pages' clean = require 'gulp-clean' gulp.task 'doc:clean', -> gulp.src [ 'target/coffeedoc' ], read : false .pipe clean force : true gencodo = () -> gulp.src ['src/**/*.coffee', '!src/**/*.spec*.coffee'], read: false .pipe codo dir: 'target/coffeedoc/main' name: 'PI:NAME:<NAME>END_PImit(main)' title: 'Kermit(main)' readme: 'doc/main.intro.md' verbose : true extra: ['LICENSE.md'] gencodo.description = 'Generate main coffee documentation' gencodo_test = () -> gulp.src ['./src/**/*spec*.coffee'], read: false .pipe codo dir: 'target/coffeedoc/test' name: 'PI:NAME:<NAME>END_PImit(test)' title: 'Kermit(test)' readme: 'doc/test.intro.md' extra: ['LICENSE.md'] gencodo_test.description = 'Generate documentation of test classes' docsToGhPages = () -> gulp.src './target/site/**/*' .pipe ghPages() docsToGhPages.description = "Publishes the coffeedoc documentation to " # Register tasks with gulp gulp.task 'doc:coffee', gencodo gulp.task 'doc:coffee:test', gencodo_test gulp.task 'doc:deploy', docsToGhPages gulp.task 'doc:assemble', gulp.series 'doc:clean', gulp.parallel( "doc:coffee",'doc:coffee:test'), -> input = ["./target/coffeedoc/**/*", './doc/index.html'] gulp.src input .pipe gulp.dest './target/site' gulp.task 'doc:all', gulp.series 'doc:assemble', 'doc:deploy'
[ { "context": "md5=EFFAC31057A9E5489C9069845DDF22DD\n * [GitHub - Shivanandroy/Study-Materials](https://github.com/Shivanandroy/", "end": 1385, "score": 0.9989942312240601, "start": 1373, "tag": "USERNAME", "value": "Shivanandroy" }, { "context": " Shivanandroy/Study-Materials](https...
notes/2adbfca2-7135-47dc-b71b-baac8ed6aac9.cson
wikiGrandfleet/gravRepo
0
createdAt: "2018-07-24T02:07:09.556Z" updatedAt: "2018-11-13T04:17:36.933Z" type: "MARKDOWN_NOTE" folder: "fb2abb5723b1e45552eb" title: "Reading List for 2018" content: ''' ### Reading List for 2018 #### Blockchain !!! caution list ENGR 003 - [x] Internet of Things A to Z: Technologies and Applications - [x] Solidity Programming Essentials - [x] Solidity book for developers - [x] Games for Ethereum - [x] Hyperledger Composer Book - [ ] golang - [x] Matlab stuff, deep learning - [ ] Google tensorflow examples learning course. - [ ] Understanding Machine Learning from concepts to tech stack (use BOostote Notes method) !!! AI - [ ] Pratical cloud approach dump cloud to bitbucket after. #### Other !!! danger books - [ ] SelfStudy/Internet of Things A to Z/internet-things-technologies-applications !!! ## Books to download !!! error Libgen books. * http://libgen.io/search.php?req=solidity&open=0&res=25&view=simple&phrase=1&column=def * http://libgen.io/search.php?req=machine+learning&open=0&res=25&view=simple&phrase=1&column=def * http://libgen.io/search.php?&req=data+mining&phrase=1&view=simple&column=def&sort=year&sortmode=DESC * http://libgen.io/book/index.php?md5=6FF9CD52DAA815A8CBE453444EC01C64 * http://libgen.io/book/index.php?md5=EFFAC31057A9E5489C9069845DDF22DD * [GitHub - Shivanandroy/Study-Materials](https://github.com/Shivanandroy/Study-Materials) !!! ### Summarize Links !!! danger Blockchain Notes add to notes Add to lwarp notes lol. - [x] [Web3 Design Principles – beltran – Medium](https://medium.com/@lyricalpolymath/web3-design-principles-f21db2f240c1) - [x] [Selecting the best Machine Learning algorithm for your regression problem](https://towardsdatascience.com/selecting-the-best-machine-learning-algorithm-for-your-regression-problem-20c330bad4ef) - [x] [Understanding Web 3 — A User Controlled Internet – The Coinbase Blog](https://blog.coinbase.com/understanding-web-3-a-user-controlled-internet-a39c21cf83f3) - [x] [How to Audit a Smart Contract (Blockgeeks Guide)](http://blockgeeks.acemlnb.com/lt.php?s=47e9a25245c7c2f7e31b1d3108b56620&i=693A730A6A69207) - [ ] ERC 998 standard - [ ] [Ethereum — Vyper Development Using Truffle – John Grant – Medium](https://medium.com/@johngrant/ethereum-vyper-development-using-truffle-73781c4d81d5) Might try a few of that - [ ] [ERC-721 metadata standards and IPFS – Blockchain Manchester – Medium](https://medium.com/blockchain-manchester/erc-721-metadata-standards-and-ipfs-94b01fea2a89) - [ ] [IPFS and Ethereum ERC721 token Helps Claiming Ownership of Digital Art](https://medium.com/coinmonks/ipfs-and-ethereum-erc721-token-helps-claiming-ownership-of-digital-art-2fe463244382) - [ ] [Program the Blockchain | Implementing Harberger Tax Deeds](https://programtheblockchain.com/posts/2018/09/19/implementing-harberger-tax-deeds/) - [x] [your-word/contracts at master · aviaryan/your-word · GitHub](https://github.com/aviaryan/your-word/tree/master/contracts) - [x] [Receive Ether* for quality answers – Patryk Adaś – Medium](https://medium.com/@patrykadas/receive-ether-for-quality-answers-50179c30ce28) !!! !!! hint AI Notes Add to lwarp AI Notes - [x] <https://hackernoon.com/the-simplest-explanation-of-machine-learning-youll-ever-read-bebc0700047c> - [ ] Finish C:\\Users\\wu\\Downloads\\University Fun\\Self Study\\Machine Learning\\GoogleCLoud !!! ''' tags: [] isStarred: false isTrashed: false
104160
createdAt: "2018-07-24T02:07:09.556Z" updatedAt: "2018-11-13T04:17:36.933Z" type: "MARKDOWN_NOTE" folder: "fb2abb5723b1e45552eb" title: "Reading List for 2018" content: ''' ### Reading List for 2018 #### Blockchain !!! caution list ENGR 003 - [x] Internet of Things A to Z: Technologies and Applications - [x] Solidity Programming Essentials - [x] Solidity book for developers - [x] Games for Ethereum - [x] Hyperledger Composer Book - [ ] golang - [x] Matlab stuff, deep learning - [ ] Google tensorflow examples learning course. - [ ] Understanding Machine Learning from concepts to tech stack (use BOostote Notes method) !!! AI - [ ] Pratical cloud approach dump cloud to bitbucket after. #### Other !!! danger books - [ ] SelfStudy/Internet of Things A to Z/internet-things-technologies-applications !!! ## Books to download !!! error Libgen books. * http://libgen.io/search.php?req=solidity&open=0&res=25&view=simple&phrase=1&column=def * http://libgen.io/search.php?req=machine+learning&open=0&res=25&view=simple&phrase=1&column=def * http://libgen.io/search.php?&req=data+mining&phrase=1&view=simple&column=def&sort=year&sortmode=DESC * http://libgen.io/book/index.php?md5=6FF9CD52DAA815A8CBE453444EC01C64 * http://libgen.io/book/index.php?md5=EFFAC31057A9E5489C9069845DDF22DD * [GitHub - Shivanandroy/Study-Materials](https://github.com/Shivanandroy/Study-Materials) !!! ### Summarize Links !!! danger Blockchain Notes add to notes Add to lwarp notes lol. - [x] [Web3 Design Principles – beltran – Medium](https://medium.com/@lyricalpolymath/web3-design-principles-f21db2f240c1) - [x] [Selecting the best Machine Learning algorithm for your regression problem](https://towardsdatascience.com/selecting-the-best-machine-learning-algorithm-for-your-regression-problem-20c330bad4ef) - [x] [Understanding Web 3 — A User Controlled Internet – The Coinbase Blog](https://blog.coinbase.com/understanding-web-3-a-user-controlled-internet-a39c21cf83f3) - [x] [How to Audit a Smart Contract (Blockgeeks Guide)](http://blockgeeks.acemlnb.com/lt.php?s=47e9a25245c7c2f7e31b1d3108b56620&i=693A730A6A69207) - [ ] ERC 998 standard - [ ] [Ethereum — Vyper Development Using Truffle – <NAME> – Medium](https://medium.com/@johngrant/ethereum-vyper-development-using-truffle-73781c4d81d5) Might try a few of that - [ ] [ERC-721 metadata standards and IPFS – Blockchain Manchester – Medium](https://medium.com/blockchain-manchester/erc-721-metadata-standards-and-ipfs-94b01fea2a89) - [ ] [IPFS and Ethereum ERC721 token Helps Claiming Ownership of Digital Art](https://medium.com/coinmonks/ipfs-and-ethereum-erc721-token-helps-claiming-ownership-of-digital-art-2fe463244382) - [ ] [Program the Blockchain | Implementing Harberger Tax Deeds](https://programtheblockchain.com/posts/2018/09/19/implementing-harberger-tax-deeds/) - [x] [your-word/contracts at master · aviaryan/your-word · GitHub](https://github.com/aviaryan/your-word/tree/master/contracts) - [x] [Receive Ether* for quality answers – <NAME> – Medium](https://medium.com/@patrykadas/receive-ether-for-quality-answers-50179c30ce28) !!! !!! hint AI Notes Add to lwarp AI Notes - [x] <https://hackernoon.com/the-simplest-explanation-of-machine-learning-youll-ever-read-bebc0700047c> - [ ] Finish C:\\Users\\wu\\Downloads\\University Fun\\Self Study\\Machine Learning\\GoogleCLoud !!! ''' tags: [] isStarred: false isTrashed: false
true
createdAt: "2018-07-24T02:07:09.556Z" updatedAt: "2018-11-13T04:17:36.933Z" type: "MARKDOWN_NOTE" folder: "fb2abb5723b1e45552eb" title: "Reading List for 2018" content: ''' ### Reading List for 2018 #### Blockchain !!! caution list ENGR 003 - [x] Internet of Things A to Z: Technologies and Applications - [x] Solidity Programming Essentials - [x] Solidity book for developers - [x] Games for Ethereum - [x] Hyperledger Composer Book - [ ] golang - [x] Matlab stuff, deep learning - [ ] Google tensorflow examples learning course. - [ ] Understanding Machine Learning from concepts to tech stack (use BOostote Notes method) !!! AI - [ ] Pratical cloud approach dump cloud to bitbucket after. #### Other !!! danger books - [ ] SelfStudy/Internet of Things A to Z/internet-things-technologies-applications !!! ## Books to download !!! error Libgen books. * http://libgen.io/search.php?req=solidity&open=0&res=25&view=simple&phrase=1&column=def * http://libgen.io/search.php?req=machine+learning&open=0&res=25&view=simple&phrase=1&column=def * http://libgen.io/search.php?&req=data+mining&phrase=1&view=simple&column=def&sort=year&sortmode=DESC * http://libgen.io/book/index.php?md5=6FF9CD52DAA815A8CBE453444EC01C64 * http://libgen.io/book/index.php?md5=EFFAC31057A9E5489C9069845DDF22DD * [GitHub - Shivanandroy/Study-Materials](https://github.com/Shivanandroy/Study-Materials) !!! ### Summarize Links !!! danger Blockchain Notes add to notes Add to lwarp notes lol. - [x] [Web3 Design Principles – beltran – Medium](https://medium.com/@lyricalpolymath/web3-design-principles-f21db2f240c1) - [x] [Selecting the best Machine Learning algorithm for your regression problem](https://towardsdatascience.com/selecting-the-best-machine-learning-algorithm-for-your-regression-problem-20c330bad4ef) - [x] [Understanding Web 3 — A User Controlled Internet – The Coinbase Blog](https://blog.coinbase.com/understanding-web-3-a-user-controlled-internet-a39c21cf83f3) - [x] [How to Audit a Smart Contract (Blockgeeks Guide)](http://blockgeeks.acemlnb.com/lt.php?s=47e9a25245c7c2f7e31b1d3108b56620&i=693A730A6A69207) - [ ] ERC 998 standard - [ ] [Ethereum — Vyper Development Using Truffle – PI:NAME:<NAME>END_PI – Medium](https://medium.com/@johngrant/ethereum-vyper-development-using-truffle-73781c4d81d5) Might try a few of that - [ ] [ERC-721 metadata standards and IPFS – Blockchain Manchester – Medium](https://medium.com/blockchain-manchester/erc-721-metadata-standards-and-ipfs-94b01fea2a89) - [ ] [IPFS and Ethereum ERC721 token Helps Claiming Ownership of Digital Art](https://medium.com/coinmonks/ipfs-and-ethereum-erc721-token-helps-claiming-ownership-of-digital-art-2fe463244382) - [ ] [Program the Blockchain | Implementing Harberger Tax Deeds](https://programtheblockchain.com/posts/2018/09/19/implementing-harberger-tax-deeds/) - [x] [your-word/contracts at master · aviaryan/your-word · GitHub](https://github.com/aviaryan/your-word/tree/master/contracts) - [x] [Receive Ether* for quality answers – PI:NAME:<NAME>END_PI – Medium](https://medium.com/@patrykadas/receive-ether-for-quality-answers-50179c30ce28) !!! !!! hint AI Notes Add to lwarp AI Notes - [x] <https://hackernoon.com/the-simplest-explanation-of-machine-learning-youll-ever-read-bebc0700047c> - [ ] Finish C:\\Users\\wu\\Downloads\\University Fun\\Self Study\\Machine Learning\\GoogleCLoud !!! ''' tags: [] isStarred: false isTrashed: false
[ { "context": " modelKey: 'contentId'\n jsonKey: 'content_id'\n\n upload: (callback = null) =>\n throw new Er", "end": 708, "score": 0.737804651260376, "start": 706, "tag": "KEY", "value": "id" } ]
models/file.coffee
lever/nylas-nodejs
0
RestfulModel = require './restful-model' Attributes = require './attributes' _ = require 'underscore' module.exports = class File extends RestfulModel @collectionName: 'files' @attributes: _.extend {}, RestfulModel.attributes, 'filename': Attributes.String modelKey: 'filename' jsonKey: 'filename' 'size': Attributes.Number modelKey: 'size' jsonKey: 'size' 'contentType': Attributes.String modelKey: 'contentType' jsonKey: 'content_type' 'messageIds': Attributes.Collection modelKey: 'messageIds' jsonKey: 'message_ids' itemClass: String 'contentId': Attributes.String modelKey: 'contentId' jsonKey: 'content_id' upload: (callback = null) => throw new Error("Please define a filename") if not @filename throw new Error("Please add some data to the file") if not @data throw new Error("Please define a content-type") if not @contentType @connection.request method: 'POST' json: false path: "/#{@constructor.collectionName}" formData: file: value: @data options: filename: @filename contentType: @contentType .then (json) => # The API returns a list of files. It should # always have a length of 1 since we only # upload file-by-file. if json.length > 0 @fromJSON(json[0]) callback(null, @) if callback Promise.resolve(@) else Promise.reject(null) .catch (err) -> callback(err) if callback Promise.reject(err) download: (callback = null) => throw new Error("Please provide a File id") if not @id @connection.request path: "/files/#{@id}/download" encoding: null downloadRequest: true .then (response) => file = _.extend(response.headers, body: response.body) if 'content-disposition' of file filename = /filename=([^;]*)/.exec(file['content-disposition'])[1] || 'filename' else filename = 'filename' callback(null, file) if callback Promise.resolve(file) .catch (err) -> callback(err) if callback Promise.reject(err) metadata: (callback = null) -> throw new Error("Please provide a File id") if not @id @connection.request path: "/files/#{@id}" .then (response) -> callback(null, response) if callback Promise.resolve(response) .catch (err) -> callback(err) if callback Promise.reject(err)
54681
RestfulModel = require './restful-model' Attributes = require './attributes' _ = require 'underscore' module.exports = class File extends RestfulModel @collectionName: 'files' @attributes: _.extend {}, RestfulModel.attributes, 'filename': Attributes.String modelKey: 'filename' jsonKey: 'filename' 'size': Attributes.Number modelKey: 'size' jsonKey: 'size' 'contentType': Attributes.String modelKey: 'contentType' jsonKey: 'content_type' 'messageIds': Attributes.Collection modelKey: 'messageIds' jsonKey: 'message_ids' itemClass: String 'contentId': Attributes.String modelKey: 'contentId' jsonKey: 'content_<KEY>' upload: (callback = null) => throw new Error("Please define a filename") if not @filename throw new Error("Please add some data to the file") if not @data throw new Error("Please define a content-type") if not @contentType @connection.request method: 'POST' json: false path: "/#{@constructor.collectionName}" formData: file: value: @data options: filename: @filename contentType: @contentType .then (json) => # The API returns a list of files. It should # always have a length of 1 since we only # upload file-by-file. if json.length > 0 @fromJSON(json[0]) callback(null, @) if callback Promise.resolve(@) else Promise.reject(null) .catch (err) -> callback(err) if callback Promise.reject(err) download: (callback = null) => throw new Error("Please provide a File id") if not @id @connection.request path: "/files/#{@id}/download" encoding: null downloadRequest: true .then (response) => file = _.extend(response.headers, body: response.body) if 'content-disposition' of file filename = /filename=([^;]*)/.exec(file['content-disposition'])[1] || 'filename' else filename = 'filename' callback(null, file) if callback Promise.resolve(file) .catch (err) -> callback(err) if callback Promise.reject(err) metadata: (callback = null) -> throw new Error("Please provide a File id") if not @id @connection.request path: "/files/#{@id}" .then (response) -> callback(null, response) if callback Promise.resolve(response) .catch (err) -> callback(err) if callback Promise.reject(err)
true
RestfulModel = require './restful-model' Attributes = require './attributes' _ = require 'underscore' module.exports = class File extends RestfulModel @collectionName: 'files' @attributes: _.extend {}, RestfulModel.attributes, 'filename': Attributes.String modelKey: 'filename' jsonKey: 'filename' 'size': Attributes.Number modelKey: 'size' jsonKey: 'size' 'contentType': Attributes.String modelKey: 'contentType' jsonKey: 'content_type' 'messageIds': Attributes.Collection modelKey: 'messageIds' jsonKey: 'message_ids' itemClass: String 'contentId': Attributes.String modelKey: 'contentId' jsonKey: 'content_PI:KEY:<KEY>END_PI' upload: (callback = null) => throw new Error("Please define a filename") if not @filename throw new Error("Please add some data to the file") if not @data throw new Error("Please define a content-type") if not @contentType @connection.request method: 'POST' json: false path: "/#{@constructor.collectionName}" formData: file: value: @data options: filename: @filename contentType: @contentType .then (json) => # The API returns a list of files. It should # always have a length of 1 since we only # upload file-by-file. if json.length > 0 @fromJSON(json[0]) callback(null, @) if callback Promise.resolve(@) else Promise.reject(null) .catch (err) -> callback(err) if callback Promise.reject(err) download: (callback = null) => throw new Error("Please provide a File id") if not @id @connection.request path: "/files/#{@id}/download" encoding: null downloadRequest: true .then (response) => file = _.extend(response.headers, body: response.body) if 'content-disposition' of file filename = /filename=([^;]*)/.exec(file['content-disposition'])[1] || 'filename' else filename = 'filename' callback(null, file) if callback Promise.resolve(file) .catch (err) -> callback(err) if callback Promise.reject(err) metadata: (callback = null) -> throw new Error("Please provide a File id") if not @id @connection.request path: "/files/#{@id}" .then (response) -> callback(null, response) if callback Promise.resolve(response) .catch (err) -> callback(err) if callback Promise.reject(err)
[ { "context": "er:\n email: email\n password: password\n type: 'post'\n success: (res) =>\n ", "end": 2665, "score": 0.9980161190032959, "start": 2657, "tag": "PASSWORD", "value": "password" }, { "context": "er:\n email: email\n ...
public/scripts/backbone-schedule/models/session.coffee
courseshark/courseshark
1
define(['jQuery' 'Underscore' 'Backbone' 'models/model' 'models/user' 'views/auth/login' 'views/auth/signup' 'views/auth/forgot-password' 'views/auth/resolve-duplicate'], ($, _, Backbone, SharkModel, User, AuthLoginView, AuthSignupView, AuthForgotPasswordView, ResolveDuplicateView) -> class Session extends SharkModel defaults: access_token: null user_id: null user: null initalize: -> return start: -> if CS.loggedIn @_authorizeFromRes(CS.auth) else @reloadUser (()->return), false authenticated: -> !!@get("access_token") and !!@get("user") reloadUser: ( callback=(()->return), silent=true )-> $.ajax url: '/me' success: (res) => if res @_authorizeFromRes(res, silent, callback) else @trigger('unauthenticated') callback() facebookAuth: (accessToken, next=(()->return;)) => $.ajax url: '/auth/facebook-from-token' data: accessToken: accessToken success: (res) => if res.error return console.error res.error if !@authenticated() return @_authorizeFromRes res, next if res.duplicate return @resolveDuplicate res.duplicate, next else return next() logout: -> $.ajax url: '/logout' @unset 'access_token' @unset 'user_id' @unset 'user' @trigger('unauthenticated') login: (next=(()->return)) -> @loginView = new AuthLoginView({next: next}) if not @authenticated() loginWithFacebook: (callback=(()->return)) -> callback() if @authenticated() window.location = "/auth/facebook" if not FB FB.login (loginResponse) -> if loginResponse.authResponse Shark.session.facebookAuth loginResponse.authResponse.accessToken, callback signup: -> @signupView = new AuthSignupView() if not @authenticated() forgotPassword: -> @password = new AuthForgotPasswordView() if not @authenticated() _authorizeFromRes: (res, quiet=false, callback=(()->return)) -> if typeof quiet is 'function' callback = quiet quiet = false @set 'access_token', res.access_token @set 'user_id', res.user_id @set 'user', new User(res.user) @trigger('authenticated') if not quiet callback() doLogin: (email, password, success=(()->return), fail=(()->return)) -> $.ajax url: '/login.json' data: user: email: email password: password type: 'post' success: (res) => if res.success @_authorizeFromRes res success() else fail() error: => fail() doSignup: (email, password, success=(()->return), fail=(()->return)) -> $.ajax url: '/signup' data: user: email: email password: password type: 'post' success: (res) => if res.success @_authorizeFromRes res success() else fail() error: => fail() doPassword: (email, success=(()->return), fail=(()->return)) -> $.ajax url: ' /forgot-password' data: user: email: email type: 'post' success: (res) => if res success() else fail() error: => fail() doMerge: (model) -> $.ajax url: '/user/merge' data: duplicate: model.id type: 'post' success: (res) => if not res.error @._authorizeFromRes res resolveDuplicate: (duplicateId, next) -> duplicate = new User({_id:duplicateId}) @resolveDuplicateView = new ResolveDuplicateView(model: duplicate, next: next) @resolveDuplicateView.show() Session )
69246
define(['jQuery' 'Underscore' 'Backbone' 'models/model' 'models/user' 'views/auth/login' 'views/auth/signup' 'views/auth/forgot-password' 'views/auth/resolve-duplicate'], ($, _, Backbone, SharkModel, User, AuthLoginView, AuthSignupView, AuthForgotPasswordView, ResolveDuplicateView) -> class Session extends SharkModel defaults: access_token: null user_id: null user: null initalize: -> return start: -> if CS.loggedIn @_authorizeFromRes(CS.auth) else @reloadUser (()->return), false authenticated: -> !!@get("access_token") and !!@get("user") reloadUser: ( callback=(()->return), silent=true )-> $.ajax url: '/me' success: (res) => if res @_authorizeFromRes(res, silent, callback) else @trigger('unauthenticated') callback() facebookAuth: (accessToken, next=(()->return;)) => $.ajax url: '/auth/facebook-from-token' data: accessToken: accessToken success: (res) => if res.error return console.error res.error if !@authenticated() return @_authorizeFromRes res, next if res.duplicate return @resolveDuplicate res.duplicate, next else return next() logout: -> $.ajax url: '/logout' @unset 'access_token' @unset 'user_id' @unset 'user' @trigger('unauthenticated') login: (next=(()->return)) -> @loginView = new AuthLoginView({next: next}) if not @authenticated() loginWithFacebook: (callback=(()->return)) -> callback() if @authenticated() window.location = "/auth/facebook" if not FB FB.login (loginResponse) -> if loginResponse.authResponse Shark.session.facebookAuth loginResponse.authResponse.accessToken, callback signup: -> @signupView = new AuthSignupView() if not @authenticated() forgotPassword: -> @password = new AuthForgotPasswordView() if not @authenticated() _authorizeFromRes: (res, quiet=false, callback=(()->return)) -> if typeof quiet is 'function' callback = quiet quiet = false @set 'access_token', res.access_token @set 'user_id', res.user_id @set 'user', new User(res.user) @trigger('authenticated') if not quiet callback() doLogin: (email, password, success=(()->return), fail=(()->return)) -> $.ajax url: '/login.json' data: user: email: email password: <PASSWORD> type: 'post' success: (res) => if res.success @_authorizeFromRes res success() else fail() error: => fail() doSignup: (email, password, success=(()->return), fail=(()->return)) -> $.ajax url: '/signup' data: user: email: email password: <PASSWORD> type: 'post' success: (res) => if res.success @_authorizeFromRes res success() else fail() error: => fail() doPassword: (email, success=(()->return), fail=(()->return)) -> $.ajax url: ' /forgot-password' data: user: email: email type: 'post' success: (res) => if res success() else fail() error: => fail() doMerge: (model) -> $.ajax url: '/user/merge' data: duplicate: model.id type: 'post' success: (res) => if not res.error @._authorizeFromRes res resolveDuplicate: (duplicateId, next) -> duplicate = new User({_id:duplicateId}) @resolveDuplicateView = new ResolveDuplicateView(model: duplicate, next: next) @resolveDuplicateView.show() Session )
true
define(['jQuery' 'Underscore' 'Backbone' 'models/model' 'models/user' 'views/auth/login' 'views/auth/signup' 'views/auth/forgot-password' 'views/auth/resolve-duplicate'], ($, _, Backbone, SharkModel, User, AuthLoginView, AuthSignupView, AuthForgotPasswordView, ResolveDuplicateView) -> class Session extends SharkModel defaults: access_token: null user_id: null user: null initalize: -> return start: -> if CS.loggedIn @_authorizeFromRes(CS.auth) else @reloadUser (()->return), false authenticated: -> !!@get("access_token") and !!@get("user") reloadUser: ( callback=(()->return), silent=true )-> $.ajax url: '/me' success: (res) => if res @_authorizeFromRes(res, silent, callback) else @trigger('unauthenticated') callback() facebookAuth: (accessToken, next=(()->return;)) => $.ajax url: '/auth/facebook-from-token' data: accessToken: accessToken success: (res) => if res.error return console.error res.error if !@authenticated() return @_authorizeFromRes res, next if res.duplicate return @resolveDuplicate res.duplicate, next else return next() logout: -> $.ajax url: '/logout' @unset 'access_token' @unset 'user_id' @unset 'user' @trigger('unauthenticated') login: (next=(()->return)) -> @loginView = new AuthLoginView({next: next}) if not @authenticated() loginWithFacebook: (callback=(()->return)) -> callback() if @authenticated() window.location = "/auth/facebook" if not FB FB.login (loginResponse) -> if loginResponse.authResponse Shark.session.facebookAuth loginResponse.authResponse.accessToken, callback signup: -> @signupView = new AuthSignupView() if not @authenticated() forgotPassword: -> @password = new AuthForgotPasswordView() if not @authenticated() _authorizeFromRes: (res, quiet=false, callback=(()->return)) -> if typeof quiet is 'function' callback = quiet quiet = false @set 'access_token', res.access_token @set 'user_id', res.user_id @set 'user', new User(res.user) @trigger('authenticated') if not quiet callback() doLogin: (email, password, success=(()->return), fail=(()->return)) -> $.ajax url: '/login.json' data: user: email: email password: PI:PASSWORD:<PASSWORD>END_PI type: 'post' success: (res) => if res.success @_authorizeFromRes res success() else fail() error: => fail() doSignup: (email, password, success=(()->return), fail=(()->return)) -> $.ajax url: '/signup' data: user: email: email password: PI:PASSWORD:<PASSWORD>END_PI type: 'post' success: (res) => if res.success @_authorizeFromRes res success() else fail() error: => fail() doPassword: (email, success=(()->return), fail=(()->return)) -> $.ajax url: ' /forgot-password' data: user: email: email type: 'post' success: (res) => if res success() else fail() error: => fail() doMerge: (model) -> $.ajax url: '/user/merge' data: duplicate: model.id type: 'post' success: (res) => if not res.error @._authorizeFromRes res resolveDuplicate: (duplicateId, next) -> duplicate = new User({_id:duplicateId}) @resolveDuplicateView = new ResolveDuplicateView(model: duplicate, next: next) @resolveDuplicateView.show() Session )
[ { "context": "w Administrator({name: 'administrator 1', email: 'admin@email.com', password: '123456'});\n administrator.save( (", "end": 663, "score": 0.9999224543571472, "start": 648, "tag": "EMAIL", "value": "admin@email.com" }, { "context": "istrator 1', email: 'admin@email.com...
test/management/administrator.coffee
gertu/gertu
1
should = require("should") request = require('supertest') express = require('express'); server = require("../../server") mongoose = require("mongoose") Administrator = mongoose.model("Administrator") app = express() describe "Management administrator model testing", -> before (done) -> Administrator.remove().exec( () -> done() ) it "should be no adminsitrators", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(0); done() ) it "should add a new administrators", (done) -> administrator = new Administrator({name: 'administrator 1', email: 'admin@email.com', password: '123456'}); administrator.save( ()-> done() ) it "should have 1 administrator", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(1); done() ) it "should find 1 administrator for existant email", (done) -> Administrator.count({email: 'admin@email.com'}).exec( (err, count) -> count.should.equal(1); done() ) it "should find no administrator for non existant email", (done) -> Administrator.count({email: 'admin1@email.com'}).exec( (err, count) -> count.should.equal(0); done() ) it "should not add a new administrator with an existant email", (done) -> administrator = new Administrator({name: 'administrator 2', email: 'admin@email.com', password: '654321'}); administrator.save( (err)-> should.exist(err) done() ) it "should find just 1 administrator for existant email", (done) -> Administrator.count({email: 'admin@email.com'}).exec( (err, count) -> count.should.equal(1); done() ) it "should not add a new administrator with an empty name", (done) -> administrator = new Administrator({name: '', email: 'admin_new1@email.com', password: '654321'}); administrator.save( (err)-> should.exist(err) done() ) it "should not add a new administrator with an empty password", (done) -> administrator = new Administrator({name: 'administrator 3', email: 'admin_new1@email.com', password: ''}); administrator.save( (err)-> should.exist(err) done() ) it "should be just 1 administrator", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(1); done() ) it "should find an administrator given the email", (done) -> Administrator.findOne({email: 'admin@email.com'}).exec( (err, administrator) -> should.not.exist(err) should.exist(administrator) administrator.name.should.equal('administrator 1') done() ) it "should remove an administrator given the email", (done) -> Administrator.findOne({email: 'admin@email.com'}).exec( (err, administrator) -> administrator.remove( (err) -> should.not.exist(err) done() ) ) it "should not find an administrator given the email", (done) -> Administrator.findOne({email: 'admin@email.com'}).exec( (err, administrator) -> should.not.exist(administrator) done() ) after (done) -> Administrator.remove().exec( () -> # This is used in the application administrator = new Administrator({name: 'administrator 1', email: 'admin@email.com', password: '123456'}); administrator.save( ()-> done() ) )
195539
should = require("should") request = require('supertest') express = require('express'); server = require("../../server") mongoose = require("mongoose") Administrator = mongoose.model("Administrator") app = express() describe "Management administrator model testing", -> before (done) -> Administrator.remove().exec( () -> done() ) it "should be no adminsitrators", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(0); done() ) it "should add a new administrators", (done) -> administrator = new Administrator({name: 'administrator 1', email: '<EMAIL>', password: '<PASSWORD>'}); administrator.save( ()-> done() ) it "should have 1 administrator", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(1); done() ) it "should find 1 administrator for existant email", (done) -> Administrator.count({email: '<EMAIL>'}).exec( (err, count) -> count.should.equal(1); done() ) it "should find no administrator for non existant email", (done) -> Administrator.count({email: '<EMAIL>'}).exec( (err, count) -> count.should.equal(0); done() ) it "should not add a new administrator with an existant email", (done) -> administrator = new Administrator({name: 'administrator 2', email: '<EMAIL>', password: '<PASSWORD>'}); administrator.save( (err)-> should.exist(err) done() ) it "should find just 1 administrator for existant email", (done) -> Administrator.count({email: '<EMAIL>'}).exec( (err, count) -> count.should.equal(1); done() ) it "should not add a new administrator with an empty name", (done) -> administrator = new Administrator({name: '', email: '<EMAIL>', password: '<PASSWORD>'}); administrator.save( (err)-> should.exist(err) done() ) it "should not add a new administrator with an empty password", (done) -> administrator = new Administrator({name: 'administrator 3', email: '<EMAIL>', password: ''}); administrator.save( (err)-> should.exist(err) done() ) it "should be just 1 administrator", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(1); done() ) it "should find an administrator given the email", (done) -> Administrator.findOne({email: '<EMAIL>'}).exec( (err, administrator) -> should.not.exist(err) should.exist(administrator) administrator.name.should.equal('administrator 1') done() ) it "should remove an administrator given the email", (done) -> Administrator.findOne({email: '<EMAIL>'}).exec( (err, administrator) -> administrator.remove( (err) -> should.not.exist(err) done() ) ) it "should not find an administrator given the email", (done) -> Administrator.findOne({email: '<EMAIL>'}).exec( (err, administrator) -> should.not.exist(administrator) done() ) after (done) -> Administrator.remove().exec( () -> # This is used in the application administrator = new Administrator({name: 'administrator 1', email: '<EMAIL>', password: '<PASSWORD>'}); administrator.save( ()-> done() ) )
true
should = require("should") request = require('supertest') express = require('express'); server = require("../../server") mongoose = require("mongoose") Administrator = mongoose.model("Administrator") app = express() describe "Management administrator model testing", -> before (done) -> Administrator.remove().exec( () -> done() ) it "should be no adminsitrators", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(0); done() ) it "should add a new administrators", (done) -> administrator = new Administrator({name: 'administrator 1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}); administrator.save( ()-> done() ) it "should have 1 administrator", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(1); done() ) it "should find 1 administrator for existant email", (done) -> Administrator.count({email: 'PI:EMAIL:<EMAIL>END_PI'}).exec( (err, count) -> count.should.equal(1); done() ) it "should find no administrator for non existant email", (done) -> Administrator.count({email: 'PI:EMAIL:<EMAIL>END_PI'}).exec( (err, count) -> count.should.equal(0); done() ) it "should not add a new administrator with an existant email", (done) -> administrator = new Administrator({name: 'administrator 2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}); administrator.save( (err)-> should.exist(err) done() ) it "should find just 1 administrator for existant email", (done) -> Administrator.count({email: 'PI:EMAIL:<EMAIL>END_PI'}).exec( (err, count) -> count.should.equal(1); done() ) it "should not add a new administrator with an empty name", (done) -> administrator = new Administrator({name: '', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}); administrator.save( (err)-> should.exist(err) done() ) it "should not add a new administrator with an empty password", (done) -> administrator = new Administrator({name: 'administrator 3', email: 'PI:EMAIL:<EMAIL>END_PI', password: ''}); administrator.save( (err)-> should.exist(err) done() ) it "should be just 1 administrator", (done) -> Administrator.count({}).exec( (err, count) -> count.should.equal(1); done() ) it "should find an administrator given the email", (done) -> Administrator.findOne({email: 'PI:EMAIL:<EMAIL>END_PI'}).exec( (err, administrator) -> should.not.exist(err) should.exist(administrator) administrator.name.should.equal('administrator 1') done() ) it "should remove an administrator given the email", (done) -> Administrator.findOne({email: 'PI:EMAIL:<EMAIL>END_PI'}).exec( (err, administrator) -> administrator.remove( (err) -> should.not.exist(err) done() ) ) it "should not find an administrator given the email", (done) -> Administrator.findOne({email: 'PI:EMAIL:<EMAIL>END_PI'}).exec( (err, administrator) -> should.not.exist(administrator) done() ) after (done) -> Administrator.remove().exec( () -> # This is used in the application administrator = new Administrator({name: 'administrator 1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}); administrator.save( ()-> done() ) )
[ { "context": "###*\n *\n * 阿里字体下载\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\nloaderUtils ", "end": 35, "score": 0.9997057914733887, "start": 29, "tag": "USERNAME", "value": "vfasky" }, { "context": "###*\n *\n * 阿里字体下载\n * @author vfasky <vfasky@gmail.com>\n###\n'use...
loader.coffee
vfasky/iconfontcn-loader
1
###* * * 阿里字体下载 * @author vfasky <vfasky@gmail.com> ### 'use strict' loaderUtils = require 'loader-utils' request = require 'request' path = require 'path' fs = require 'fs-plus' alicdnReg = /\@import\s+url\([^\)]*at\.alicdn\.com\/t\/font[^\;]+\);?/ig urlReg = /\/\/[^\(]*at\.alicdn\.com\/t\/font[^\.css]+/i fontUrlReg = /\/\/[^\(]*at\.alicdn\.com\/t\/font[^']+/ig parseCss = (css, loader, done = ->)-> query = loaderUtils.parseQuery loader.query loaderContext = loader.context or= query.context sourcePathInfo = path.parse loader.resourcePath fontDir = path.join sourcePathInfo.dir, 'font' fs.makeTreeSync fontDir if false == fs.isDirectorySync fontDir downFiles = [] total = 0 css.replace fontUrlReg, (fontUrl)-> url = fontUrl.split('?').shift().split('#').shift() if url not in downFiles downFiles.push url fontUrl doneDownFiles = -> done css for fontUrl in downFiles pathInfo = path.parse fontUrl baseUrl = './font/' + pathInfo.base fullUrl = path.join sourcePathInfo.dir, baseUrl do (fontUrl, baseUrl)-> if false == fs.isFileSync(fullUrl) request.get 'http:' + fontUrl .on 'response', -> total++ reg = new RegExp fontUrl, 'ig' css = css.replace reg, baseUrl doneDownFiles() if total == downFiles.length .pipe fs.createWriteStream fullUrl else console.log '%s 已经下载,跳过', fontUrl total++ reg = new RegExp fontUrl, 'ig' css = css.replace reg, baseUrl doneDownFiles() if total == downFiles.length module.exports = (css)-> this.cacheable() if this.cacheable callback = this.async() loader = @ _reId = 0 reMap = {} total = 0 done = 0 css = css.replace alicdnReg, (importUrl)-> res = importUrl.match urlReg cssUrl = 'http:' + res[0] + '.css' # 如果url已经存在,删除这条import return '' if reMap[cssUrl] _reId++ reName = "/*{__replace__alicdn__#{_reId}}*/" total++ reMap[cssUrl] = name: reName soure: importUrl reName if Object.keys(reMap).length == 0 return callback null, css for cssUrl of reMap do (cssUrl)-> request cssUrl, (err, res, body)-> return callback err if err parseCss body, loader, (fontCss)-> done++ css = css.replace reMap[cssUrl].name, fontCss if done == total callback null, css
133768
###* * * 阿里字体下载 * @author vfasky <<EMAIL>> ### 'use strict' loaderUtils = require 'loader-utils' request = require 'request' path = require 'path' fs = require 'fs-plus' alicdnReg = /\@import\s+url\([^\)]*at\.alicdn\.com\/t\/font[^\;]+\);?/ig urlReg = /\/\/[^\(]*at\.alicdn\.com\/t\/font[^\.css]+/i fontUrlReg = /\/\/[^\(]*at\.alicdn\.com\/t\/font[^']+/ig parseCss = (css, loader, done = ->)-> query = loaderUtils.parseQuery loader.query loaderContext = loader.context or= query.context sourcePathInfo = path.parse loader.resourcePath fontDir = path.join sourcePathInfo.dir, 'font' fs.makeTreeSync fontDir if false == fs.isDirectorySync fontDir downFiles = [] total = 0 css.replace fontUrlReg, (fontUrl)-> url = fontUrl.split('?').shift().split('#').shift() if url not in downFiles downFiles.push url fontUrl doneDownFiles = -> done css for fontUrl in downFiles pathInfo = path.parse fontUrl baseUrl = './font/' + pathInfo.base fullUrl = path.join sourcePathInfo.dir, baseUrl do (fontUrl, baseUrl)-> if false == fs.isFileSync(fullUrl) request.get 'http:' + fontUrl .on 'response', -> total++ reg = new RegExp fontUrl, 'ig' css = css.replace reg, baseUrl doneDownFiles() if total == downFiles.length .pipe fs.createWriteStream fullUrl else console.log '%s 已经下载,跳过', fontUrl total++ reg = new RegExp fontUrl, 'ig' css = css.replace reg, baseUrl doneDownFiles() if total == downFiles.length module.exports = (css)-> this.cacheable() if this.cacheable callback = this.async() loader = @ _reId = 0 reMap = {} total = 0 done = 0 css = css.replace alicdnReg, (importUrl)-> res = importUrl.match urlReg cssUrl = 'http:' + res[0] + '.css' # 如果url已经存在,删除这条import return '' if reMap[cssUrl] _reId++ reName = "/*{__replace__alicdn__#{_reId}}*/" total++ reMap[cssUrl] = name: reName soure: importUrl reName if Object.keys(reMap).length == 0 return callback null, css for cssUrl of reMap do (cssUrl)-> request cssUrl, (err, res, body)-> return callback err if err parseCss body, loader, (fontCss)-> done++ css = css.replace reMap[cssUrl].name, fontCss if done == total callback null, css
true
###* * * 阿里字体下载 * @author vfasky <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' loaderUtils = require 'loader-utils' request = require 'request' path = require 'path' fs = require 'fs-plus' alicdnReg = /\@import\s+url\([^\)]*at\.alicdn\.com\/t\/font[^\;]+\);?/ig urlReg = /\/\/[^\(]*at\.alicdn\.com\/t\/font[^\.css]+/i fontUrlReg = /\/\/[^\(]*at\.alicdn\.com\/t\/font[^']+/ig parseCss = (css, loader, done = ->)-> query = loaderUtils.parseQuery loader.query loaderContext = loader.context or= query.context sourcePathInfo = path.parse loader.resourcePath fontDir = path.join sourcePathInfo.dir, 'font' fs.makeTreeSync fontDir if false == fs.isDirectorySync fontDir downFiles = [] total = 0 css.replace fontUrlReg, (fontUrl)-> url = fontUrl.split('?').shift().split('#').shift() if url not in downFiles downFiles.push url fontUrl doneDownFiles = -> done css for fontUrl in downFiles pathInfo = path.parse fontUrl baseUrl = './font/' + pathInfo.base fullUrl = path.join sourcePathInfo.dir, baseUrl do (fontUrl, baseUrl)-> if false == fs.isFileSync(fullUrl) request.get 'http:' + fontUrl .on 'response', -> total++ reg = new RegExp fontUrl, 'ig' css = css.replace reg, baseUrl doneDownFiles() if total == downFiles.length .pipe fs.createWriteStream fullUrl else console.log '%s 已经下载,跳过', fontUrl total++ reg = new RegExp fontUrl, 'ig' css = css.replace reg, baseUrl doneDownFiles() if total == downFiles.length module.exports = (css)-> this.cacheable() if this.cacheable callback = this.async() loader = @ _reId = 0 reMap = {} total = 0 done = 0 css = css.replace alicdnReg, (importUrl)-> res = importUrl.match urlReg cssUrl = 'http:' + res[0] + '.css' # 如果url已经存在,删除这条import return '' if reMap[cssUrl] _reId++ reName = "/*{__replace__alicdn__#{_reId}}*/" total++ reMap[cssUrl] = name: reName soure: importUrl reName if Object.keys(reMap).length == 0 return callback null, css for cssUrl of reMap do (cssUrl)-> request cssUrl, (err, res, body)-> return callback err if err parseCss body, loader, (fontCss)-> done++ css = css.replace reMap[cssUrl].name, fontCss if done == total callback null, css
[ { "context": "ase/Spell\"\n\nclass HolyBolt extends Spell\n name: \"holy bolt\"\n @element = HolyBolt::element = Spell::", "end": 79, "score": 0.754848301410675, "start": 78, "tag": "NAME", "value": "h" }, { "context": "s is a basic damaging spell.\n *\n * @name holy bolt...
src/character/spells/magical/holy/HolyBolt.coffee
sadbear-/IdleLands
3
Spell = require "../../../base/Spell" class HolyBolt extends Spell name: "holy bolt" @element = HolyBolt::element = Spell::Element.holy @tiers = HolyBolt::tiers = [ `/** * This is a basic damaging spell. * * @name holy bolt * @requirement {class} Cleric * @requirement {mp} 125 * @requirement {level} 5 * @element holy * @targets {enemy} 1 * @minDamage [wis/4] * @maxDamage [wis] * @category Cleric * @package Spells */` {name: "holy bolt", spellPower: 1, cost: 125, class: "Cleric", level: 5} `/** * This is a basic damaging spell. * * @name divine bolt * @requirement {class} Cleric * @requirement {mp} 250 * @requirement {level} 30 * @element holy * @targets {enemy} 1 * @minDamage [wis/4]*2 * @maxDamage [wis]*2 * @category Cleric * @package Spells */` {name: "divine bolt", spellPower: 2, cost: 250, class: "Cleric", level: 30} `/** * This is a basic damaging spell. * * @name celestial bolt * @requirement {class} Cleric * @requirement {mp} 500 * @requirement {level} 55 * @element holy * @targets {enemy} 1 * @minDamage [wis/4]*4 * @maxDamage [wis]*4 * @category Cleric * @package Spells */` {name: "celestial bolt", spellPower: 4, cost: 500, class: "Cleric", level: 55} ] calcDamage: -> minStat = @spellPower*(@caster.calc.stat 'wis')/4 maxStat = @spellPower*@caster.calc.stat 'wis' super() + @minMax minStat, maxStat cast: (player) -> damage = @calcDamage() message = "%casterName cast %spellName at %targetName for %damage HP damage!" @doDamageTo player, damage, message constructor: (@game, @caster) -> super @game, @caster @bindings = doSpellCast: @cast module.exports = exports = HolyBolt
59618
Spell = require "../../../base/Spell" class HolyBolt extends Spell name: "<NAME>oly bolt" @element = HolyBolt::element = Spell::Element.holy @tiers = HolyBolt::tiers = [ `/** * This is a basic damaging spell. * * @name <NAME>oly bolt * @requirement {class} Cleric * @requirement {mp} 125 * @requirement {level} 5 * @element holy * @targets {enemy} 1 * @minDamage [wis/4] * @maxDamage [wis] * @category Cleric * @package Spells */` {name: "<NAME>oly bolt", spellPower: 1, cost: 125, class: "Cleric", level: 5} `/** * This is a basic damaging spell. * * @name <NAME>ine bolt * @requirement {class} Cleric * @requirement {mp} 250 * @requirement {level} 30 * @element holy * @targets {enemy} 1 * @minDamage [wis/4]*2 * @maxDamage [wis]*2 * @category Cleric * @package Spells */` {name: "<NAME> b<NAME>", spellPower: 2, cost: 250, class: "Cleric", level: 30} `/** * This is a basic damaging spell. * * @name <NAME> b<NAME> * @requirement {class} Cleric * @requirement {mp} 500 * @requirement {level} 55 * @element holy * @targets {enemy} 1 * @minDamage [wis/4]*4 * @maxDamage [wis]*4 * @category Cleric * @package Spells */` {name: "<NAME>", spellPower: 4, cost: 500, class: "Cleric", level: 55} ] calcDamage: -> minStat = @spellPower*(@caster.calc.stat 'wis')/4 maxStat = @spellPower*@caster.calc.stat 'wis' super() + @minMax minStat, maxStat cast: (player) -> damage = @calcDamage() message = "%casterName cast %spellName at %targetName for %damage HP damage!" @doDamageTo player, damage, message constructor: (@game, @caster) -> super @game, @caster @bindings = doSpellCast: @cast module.exports = exports = HolyBolt
true
Spell = require "../../../base/Spell" class HolyBolt extends Spell name: "PI:NAME:<NAME>END_PIoly bolt" @element = HolyBolt::element = Spell::Element.holy @tiers = HolyBolt::tiers = [ `/** * This is a basic damaging spell. * * @name PI:NAME:<NAME>END_PIoly bolt * @requirement {class} Cleric * @requirement {mp} 125 * @requirement {level} 5 * @element holy * @targets {enemy} 1 * @minDamage [wis/4] * @maxDamage [wis] * @category Cleric * @package Spells */` {name: "PI:NAME:<NAME>END_PIoly bolt", spellPower: 1, cost: 125, class: "Cleric", level: 5} `/** * This is a basic damaging spell. * * @name PI:NAME:<NAME>END_PIine bolt * @requirement {class} Cleric * @requirement {mp} 250 * @requirement {level} 30 * @element holy * @targets {enemy} 1 * @minDamage [wis/4]*2 * @maxDamage [wis]*2 * @category Cleric * @package Spells */` {name: "PI:NAME:<NAME>END_PI bPI:NAME:<NAME>END_PI", spellPower: 2, cost: 250, class: "Cleric", level: 30} `/** * This is a basic damaging spell. * * @name PI:NAME:<NAME>END_PI bPI:NAME:<NAME>END_PI * @requirement {class} Cleric * @requirement {mp} 500 * @requirement {level} 55 * @element holy * @targets {enemy} 1 * @minDamage [wis/4]*4 * @maxDamage [wis]*4 * @category Cleric * @package Spells */` {name: "PI:NAME:<NAME>END_PI", spellPower: 4, cost: 500, class: "Cleric", level: 55} ] calcDamage: -> minStat = @spellPower*(@caster.calc.stat 'wis')/4 maxStat = @spellPower*@caster.calc.stat 'wis' super() + @minMax minStat, maxStat cast: (player) -> damage = @calcDamage() message = "%casterName cast %spellName at %targetName for %damage HP damage!" @doDamageTo player, damage, message constructor: (@game, @caster) -> super @game, @caster @bindings = doSpellCast: @cast module.exports = exports = HolyBolt
[ { "context": "v-test\",\n pathname: \"database\"\n auth: [\"username\", \"password\"]\n\n result.push \"appEnv.getServiceUR", "end": 917, "score": 0.9800472855567932, "start": 909, "tag": "USERNAME", "value": "username" }, { "context": " pathname: \"database\"\n auth: ...
node_modules/cfenv/lib-src/server.coffee
fahamk/writersblock
68
# Licensed under the Apache License. See footer for details. http = require "http" cfenv = require ".." #------------------------------------------------------------------------------- exports.main = -> appEnv = cfenv.getAppEnv() dump = generateDump appEnv # console.log "#{dump}\n" server = http.createServer() server.on "request", (request, response) -> response.writeHead 200, "Content-Type": "text/plain" response.end dump server.listen appEnv.port, appEnv.bind, -> console.log "server starting on #{appEnv.url}" #------------------------------------------------------------------------------- generateDump = (appEnv) -> result = [] result.push "cfenv.getAppEnv(): #{JL appEnv}" services = appEnv.getServices() result.push "appEnv.getServices(): #{JL services}" serviceURL = appEnv.getServiceURL "cf-env-test", pathname: "database" auth: ["username", "password"] result.push "appEnv.getServiceURL(): #{serviceURL}" return result.join "\n\n" #------------------------------------------------------------------------------- JS = (object) -> JSON.stringify object JL = (object) -> JSON.stringify object, null, 4 exports.main() if require.main is module #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # # 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. #-------------------------------------------------------------------------------
48860
# Licensed under the Apache License. See footer for details. http = require "http" cfenv = require ".." #------------------------------------------------------------------------------- exports.main = -> appEnv = cfenv.getAppEnv() dump = generateDump appEnv # console.log "#{dump}\n" server = http.createServer() server.on "request", (request, response) -> response.writeHead 200, "Content-Type": "text/plain" response.end dump server.listen appEnv.port, appEnv.bind, -> console.log "server starting on #{appEnv.url}" #------------------------------------------------------------------------------- generateDump = (appEnv) -> result = [] result.push "cfenv.getAppEnv(): #{JL appEnv}" services = appEnv.getServices() result.push "appEnv.getServices(): #{JL services}" serviceURL = appEnv.getServiceURL "cf-env-test", pathname: "database" auth: ["username", "<PASSWORD>"] result.push "appEnv.getServiceURL(): #{serviceURL}" return result.join "\n\n" #------------------------------------------------------------------------------- JS = (object) -> JSON.stringify object JL = (object) -> JSON.stringify object, null, 4 exports.main() if require.main is module #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # # 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. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. http = require "http" cfenv = require ".." #------------------------------------------------------------------------------- exports.main = -> appEnv = cfenv.getAppEnv() dump = generateDump appEnv # console.log "#{dump}\n" server = http.createServer() server.on "request", (request, response) -> response.writeHead 200, "Content-Type": "text/plain" response.end dump server.listen appEnv.port, appEnv.bind, -> console.log "server starting on #{appEnv.url}" #------------------------------------------------------------------------------- generateDump = (appEnv) -> result = [] result.push "cfenv.getAppEnv(): #{JL appEnv}" services = appEnv.getServices() result.push "appEnv.getServices(): #{JL services}" serviceURL = appEnv.getServiceURL "cf-env-test", pathname: "database" auth: ["username", "PI:PASSWORD:<PASSWORD>END_PI"] result.push "appEnv.getServiceURL(): #{serviceURL}" return result.join "\n\n" #------------------------------------------------------------------------------- JS = (object) -> JSON.stringify object JL = (object) -> JSON.stringify object, null, 4 exports.main() if require.main is module #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # # 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. #-------------------------------------------------------------------------------
[ { "context": "- An HTML5 Canvas game engine.\n\nCopyright (c) 2011 Matthew Perpick.\nWolf is freely distributable under the MIT licen", "end": 75, "score": 0.9998841881752014, "start": 60, "tag": "NAME", "value": "Matthew Perpick" }, { "context": "utable under the MIT license.\n\nhtt...
src/license.coffee
clutchski/wolf
2
### Wolf - An HTML5 Canvas game engine. Copyright (c) 2011 Matthew Perpick. Wolf is freely distributable under the MIT license. https://github.com/clutchski/wolf ### #= require_self #= require_tree .
115621
### Wolf - An HTML5 Canvas game engine. Copyright (c) 2011 <NAME>. Wolf is freely distributable under the MIT license. https://github.com/clutchski/wolf ### #= require_self #= require_tree .
true
### Wolf - An HTML5 Canvas game engine. Copyright (c) 2011 PI:NAME:<NAME>END_PI. Wolf is freely distributable under the MIT license. https://github.com/clutchski/wolf ### #= require_self #= require_tree .