├── CNAME
├── .gitignore
├── bg.png
├── icons
├── favicon.acorn
├── favicon.ico
├── favicon.png
├── apple-icon.png
├── favicon-16x16.png
├── favicon-32x32.png
├── favicon-96x96.png
├── apple-icon-57x57.png
├── apple-icon-60x60.png
├── apple-icon-72x72.png
├── apple-icon-76x76.png
├── android-icon-36x36.png
├── android-icon-48x48.png
├── android-icon-72x72.png
├── android-icon-96x96.png
├── apple-icon-114x114.png
├── apple-icon-120x120.png
├── apple-icon-144x144.png
├── apple-icon-152x152.png
├── apple-icon-180x180.png
├── android-icon-144x144.png
├── android-icon-192x192.png
├── apple-icon-precomposed.png
└── manifest.json
├── spec
├── lib
│ ├── jasmine_favicon.png
│ ├── jasmine.css
│ ├── jasmine-html.js
│ └── jasmine.js
├── ResultsSpec.coffee
└── ResultsSpec.js
├── spawn.coffee
├── LICENSE.txt
├── Cakefile
├── package.json
├── SpecRunner.html
├── README.md
├── scripts
├── application.coffee
└── spine.coffee
├── application.css
├── application.js
├── index.html
└── spine.js
/CNAME:
--------------------------------------------------------------------------------
1 | scriptular.com
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
--------------------------------------------------------------------------------
/bg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/bg.png
--------------------------------------------------------------------------------
/icons/favicon.acorn:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/favicon.acorn
--------------------------------------------------------------------------------
/icons/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/favicon.ico
--------------------------------------------------------------------------------
/icons/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/favicon.png
--------------------------------------------------------------------------------
/icons/apple-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon.png
--------------------------------------------------------------------------------
/icons/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/favicon-16x16.png
--------------------------------------------------------------------------------
/icons/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/favicon-32x32.png
--------------------------------------------------------------------------------
/icons/favicon-96x96.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/favicon-96x96.png
--------------------------------------------------------------------------------
/icons/apple-icon-57x57.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-57x57.png
--------------------------------------------------------------------------------
/icons/apple-icon-60x60.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-60x60.png
--------------------------------------------------------------------------------
/icons/apple-icon-72x72.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-72x72.png
--------------------------------------------------------------------------------
/icons/apple-icon-76x76.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-76x76.png
--------------------------------------------------------------------------------
/icons/android-icon-36x36.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/android-icon-36x36.png
--------------------------------------------------------------------------------
/icons/android-icon-48x48.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/android-icon-48x48.png
--------------------------------------------------------------------------------
/icons/android-icon-72x72.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/android-icon-72x72.png
--------------------------------------------------------------------------------
/icons/android-icon-96x96.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/android-icon-96x96.png
--------------------------------------------------------------------------------
/icons/apple-icon-114x114.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-114x114.png
--------------------------------------------------------------------------------
/icons/apple-icon-120x120.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-120x120.png
--------------------------------------------------------------------------------
/icons/apple-icon-144x144.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-144x144.png
--------------------------------------------------------------------------------
/icons/apple-icon-152x152.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-152x152.png
--------------------------------------------------------------------------------
/icons/apple-icon-180x180.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-180x180.png
--------------------------------------------------------------------------------
/spec/lib/jasmine_favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/spec/lib/jasmine_favicon.png
--------------------------------------------------------------------------------
/icons/android-icon-144x144.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/android-icon-144x144.png
--------------------------------------------------------------------------------
/icons/android-icon-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/android-icon-192x192.png
--------------------------------------------------------------------------------
/icons/apple-icon-precomposed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jonmagic/scriptular/HEAD/icons/apple-icon-precomposed.png
--------------------------------------------------------------------------------
/spawn.coffee:
--------------------------------------------------------------------------------
1 | (->
2 | self = this
3 | spawn = undefined
4 | windowsSpawn = undefined
5 | spawn = require('child_process').spawn
6 |
7 | windowsSpawn = (executable, args, options) ->
8 | spawn process.env.comspec or 'cmd.exe', [
9 | '/c'
10 | executable
11 | ].concat(args), options
12 |
13 | if process.platform == 'win32'
14 | exports.spawn = windowsSpawn
15 | else
16 | exports.spawn = spawn
17 | return
18 | ).call this
19 |
--------------------------------------------------------------------------------
/icons/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Scriptular",
3 | "start_url": ".",
4 | "display": "browser",
5 | "icons": [
6 | {
7 | "src": "\/android-icon-36x36.png",
8 | "sizes": "36x36",
9 | "type": "image\/png",
10 | "density": "0.75"
11 | },
12 | {
13 | "src": "\/android-icon-48x48.png",
14 | "sizes": "48x48",
15 | "type": "image\/png",
16 | "density": "1.0"
17 | },
18 | {
19 | "src": "\/android-icon-72x72.png",
20 | "sizes": "72x72",
21 | "type": "image\/png",
22 | "density": "1.5"
23 | },
24 | {
25 | "src": "\/android-icon-96x96.png",
26 | "sizes": "96x96",
27 | "type": "image\/png",
28 | "density": "2.0"
29 | },
30 | {
31 | "src": "\/android-icon-144x144.png",
32 | "sizes": "144x144",
33 | "type": "image\/png",
34 | "density": "3.0"
35 | },
36 | {
37 | "src": "\/android-icon-192x192.png",
38 | "sizes": "192x192",
39 | "type": "image\/png",
40 | "density": "4.0"
41 | }
42 | ],
43 | "lang": "en-US",
44 | "dir": "ltr",
45 | "theme_color": "#222222"
46 | }
47 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) 2011 Jonathan Hoyt
2 |
3 | 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:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | 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.
--------------------------------------------------------------------------------
/Cakefile:
--------------------------------------------------------------------------------
1 | {print} = require 'util'
2 | {spawn} = require './spawn'
3 |
4 | build = (callback) ->
5 | coffee = spawn 'coffee', ['-c', '-o', './', 'scripts']
6 | coffee.stderr.on 'data', (data) ->
7 | process.stderr.write data.toString()
8 | coffee.stdout.on 'data', (data) ->
9 | print data.toString()
10 | coffee.on 'exit', (code) ->
11 | callback?() if code is 0
12 |
13 | coffee = spawn 'coffee', ['-c', '-o', 'spec/', 'Spec']
14 | coffee.stderr.on 'data', (data) ->
15 | process.stderr.write data.toString()
16 | coffee.stdout.on 'data', (data) ->
17 | print data.toString()
18 | coffee.on 'exit', (code) ->
19 | callback?() if code is 0
20 |
21 | watch = (callback) ->
22 | coffee = spawn 'coffee', ['-w', '-c', '-o', './', 'scripts']
23 | coffee.stderr.on 'data', (data) ->
24 | process.stderr.write data.toString()
25 | coffee.stdout.on 'data', (data) ->
26 | print data.toString()
27 | coffee.on 'exit', (code) ->
28 | callback?() if code is 0
29 |
30 | coffee = spawn 'coffee', ['-w', '-c', '-o', 'spec/', 'Spec']
31 | coffee.stderr.on 'data', (data) ->
32 | process.stderr.write data.toString()
33 | coffee.stdout.on 'data', (data) ->
34 | print data.toString()
35 | coffee.on 'exit', (code) ->
36 | callback?() if code is 0
37 |
38 |
39 | task 'build', 'Build application.js from srcipts/', ->
40 | build()
41 |
42 | task 'watch', 'Continuously compile application.js from scripts/', ->
43 | watch()
44 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "scriptular",
3 | "version": "1.0.0",
4 | "description": "A rubular.com clone for JavaScript regular expressions",
5 | "main": "application.js",
6 | "private": true,
7 | "scripts": {
8 | "test": "echo \"Open SpecRunner.html in a browser to run tests\" && exit 0",
9 | "build": "cake build"
10 | },
11 | "repository": {
12 | "type": "git",
13 | "url": "git+https://github.com/jonmagic/scriptular.git"
14 | },
15 | "keywords": [
16 | "regexp",
17 | "front-end"
18 | ],
19 | "contributors": [
20 | "Jonathan Hoyt (https://github.com/jonmagic)",
21 | "Brandon Keepers (https://github.com/bkeepers)",
22 | "Aaron Kalin (https://github.com/martinisoft)",
23 | "Ben Truyman (https://github.com/bentruyman)",
24 | "John K. Paul (https://github.com/johnkpaul)",
25 | "Adam Brodzinski (https://github.com/AdamBrodzinski)",
26 | "brycecr (https://github.com/brycecr)",
27 | "Judith Hendeveld (https://github.com/judith)",
28 | "beechnut (https://github.com/beechnut)",
29 | "Blair Anderson (https://github.com/blairanderson)",
30 | "Vladimir Pestov (https://github.com/KozzyKoder)",
31 | "Corey Leveen (https://github.com/coreyleveen)",
32 | "Daniel Arthur Gallagher (https://github.com/DanArthurGallagher)",
33 | "Mosh Feu (https://github.com/moshfeu)"
34 | ],
35 | "license": "MIT",
36 | "bugs": {
37 | "url": "https://github.com/jonmagic/scriptular/issues"
38 | },
39 | "homepage": "https://github.com/jonmagic/scriptular#readme",
40 | "devDependencies": {
41 | "coffeescript": "1.12.7"
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/SpecRunner.html:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 | Jasmine Spec Runner
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/spec/lib/jasmine.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;
3 | }
4 |
5 |
6 | .jasmine_reporter a:visited, .jasmine_reporter a {
7 | color: #303;
8 | }
9 |
10 | .jasmine_reporter a:hover, .jasmine_reporter a:active {
11 | color: blue;
12 | }
13 |
14 | .run_spec {
15 | float:right;
16 | padding-right: 5px;
17 | font-size: .8em;
18 | text-decoration: none;
19 | }
20 |
21 | .jasmine_reporter {
22 | margin: 0 5px;
23 | }
24 |
25 | .banner {
26 | color: #303;
27 | background-color: #fef;
28 | padding: 5px;
29 | }
30 |
31 | .logo {
32 | float: left;
33 | font-size: 1.1em;
34 | padding-left: 5px;
35 | }
36 |
37 | .logo .version {
38 | font-size: .6em;
39 | padding-left: 1em;
40 | }
41 |
42 | .runner.running {
43 | background-color: yellow;
44 | }
45 |
46 |
47 | .options {
48 | text-align: right;
49 | font-size: .8em;
50 | }
51 |
52 |
53 |
54 |
55 | .suite {
56 | border: 1px outset gray;
57 | margin: 5px 0;
58 | padding-left: 1em;
59 | }
60 |
61 | .suite .suite {
62 | margin: 5px;
63 | }
64 |
65 | .suite.passed {
66 | background-color: #dfd;
67 | }
68 |
69 | .suite.failed {
70 | background-color: #fdd;
71 | }
72 |
73 | .spec {
74 | margin: 5px;
75 | padding-left: 1em;
76 | clear: both;
77 | }
78 |
79 | .spec.failed, .spec.passed, .spec.skipped {
80 | padding-bottom: 5px;
81 | border: 1px solid gray;
82 | }
83 |
84 | .spec.failed {
85 | background-color: #fbb;
86 | border-color: red;
87 | }
88 |
89 | .spec.passed {
90 | background-color: #bfb;
91 | border-color: green;
92 | }
93 |
94 | .spec.skipped {
95 | background-color: #bbb;
96 | }
97 |
98 | .messages {
99 | border-left: 1px dashed gray;
100 | padding-left: 1em;
101 | padding-right: 1em;
102 | }
103 |
104 | .passed {
105 | background-color: #cfc;
106 | display: none;
107 | }
108 |
109 | .failed {
110 | background-color: #fbb;
111 | }
112 |
113 | .skipped {
114 | color: #777;
115 | background-color: #eee;
116 | display: none;
117 | }
118 |
119 |
120 | /*.resultMessage {*/
121 | /*white-space: pre;*/
122 | /*}*/
123 |
124 | .resultMessage span.result {
125 | display: block;
126 | line-height: 2em;
127 | color: black;
128 | }
129 |
130 | .resultMessage .mismatch {
131 | color: black;
132 | }
133 |
134 | .stackTrace {
135 | white-space: pre;
136 | font-size: .8em;
137 | margin-left: 10px;
138 | max-height: 5em;
139 | overflow: auto;
140 | border: 1px inset red;
141 | padding: 1em;
142 | background: #eef;
143 | }
144 |
145 | .finished-at {
146 | padding-left: 1em;
147 | font-size: .6em;
148 | }
149 |
150 | .show-passed .passed,
151 | .show-skipped .skipped {
152 | display: block;
153 | }
154 |
155 |
156 | #jasmine_content {
157 | position:fixed;
158 | right: 100%;
159 | }
160 |
161 | .runner {
162 | border: 1px solid gray;
163 | display: block;
164 | margin: 5px 0;
165 | padding: 2px 0 2px 10px;
166 | }
167 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Scriptular
2 | ==========
3 |
4 | A regular expression editor for javascript.
5 |
6 | ## Backstory
7 |
8 | Before the summer of 2011 I never took the time to dig into regular expressions and actually learn how they work. Then [Hubot](http://hubot.github.com) came along and suddenly regular expressions were cool.
9 |
10 | Immediately I began writing hubot scripts and started using [Rubular](http://rubular.com) to test my regular expressions. Unforunately there are some differences between regular expressions in Ruby and javascript.
11 |
12 | So I created [Scriptular](http://scriptular.com) and started regular expressing myself ;)
13 |
14 | ## Compiling Coffeescript in Development
15 |
16 | 1. clone the repo
17 | 2. npm install
18 | 3. npm run build
19 |
20 | ## Running Tests
21 |
22 | Just open SpecRunner.html in a browser to run the test suite.
23 |
24 | ## Contribute
25 |
26 | If you'd like to hack on Scriptular, start by forking the repo on GitHub:
27 |
28 | https://github.com/jonmagic/scriptular
29 |
30 | The best way to get your changes merged back into core is as follows:
31 |
32 | 1. Clone down your fork
33 | 1. Create a thoughtfully named topic branch to contain your change
34 | 1. Hack away
35 | 1. If you are adding new functionality, document it in the README
36 | 1. If necessary, rebase your commits into logical chunks, without errors
37 | 1. Push the branch up to GitHub
38 | 1. Send a pull request for your branch
39 |
40 | ## Contributors
41 |
42 | * [Jonathan Hoyt](https://github.com/jonmagic)
43 | * [Brandon Keepers](https://github.com/bkeepers)
44 | * [Aaron Kalin](https://github.com/martinisoft)
45 | * [Ben Truyman](https://github.com/bentruyman)
46 | * [John K. Paul](https://github.com/johnkpaul)
47 | * [Adam Brodzinski](https://github.com/AdamBrodzinski)
48 | * [brycecr](https://github.com/brycecr)
49 | * [Judith Hengeveld](https://github.com/judith)
50 | * [beechnut](https://github.com/beechnut)
51 | * [Blair Anderson](https://github.com/blairanderson)
52 | * [Vladimir Pestov](https://github.com/KozzyKoder)
53 | * [Corey Leveen](https://github.com/coreyleveen)
54 | * [Daniel Arthur Gallagher](https://github.com/DanArthurGallagher)
55 | * [Mosh Feu](https://github.com/moshfeu)
56 | * [Wendy](https://github.com/w-kuhn)
57 |
58 | ## License
59 |
60 | Copyright (c) 2011 Jonathan Hoyt
61 |
62 | Permission is hereby granted, free of charge, to any person obtaining
63 | a copy of this software and associated documentation files (the
64 | "Software"), to deal in the Software without restriction, including
65 | without limitation the rights to use, copy, modify, merge, publish,
66 | distribute, sublicense, and/or sell copies of the Software, and to
67 | permit persons to whom the Software is furnished to do so, subject to
68 | the following conditions:
69 |
70 | The above copyright notice and this permission notice shall be
71 | included in all copies or substantial portions of the Software.
72 |
73 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
74 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
75 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
76 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
77 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
78 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
79 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
80 |
--------------------------------------------------------------------------------
/spec/ResultsSpec.coffee:
--------------------------------------------------------------------------------
1 | describe 'Results', ->
2 | beforeEach ->
3 | @app = new App
4 | $('ul#results').remove()
5 | $('body').append('')
6 | $('ul#groups').remove()
7 | $('body').append('')
8 |
9 | subjects = [
10 | {'regex': 'a', 'test_strings': [{'string': 'a'}], 'output': 'a '}
11 | {'regex': '(issues)?', 'test_strings': [{'string': 'issues'}], 'output': 'issues '}
12 | {'regex': 'a$', 'test_strings': [{'string': 'asdfja'}], 'output': 'asdfja '}
13 | {'regex': '"$', 'test_strings': [{'string': '"hello"'}], 'output': '"hello" '}
14 | {'regex': 'a(.*)c', 'test_strings': [{'string': 'abcdd', 'matches': ['b']}], 'output': 'abc dd'}
15 | {'regex': 'f(oo)', 'test_strings': [{'string': 'foodbar', 'matches': ['oo']}], 'output': 'foo dbar'}
16 | {
17 | 'regex': 'color-stop\\((.+?)\\)'
18 | 'option':'g'
19 | 'test_strings': [{'string': '-webkit-gradient(linear, right top, left top, color-stop(0, #FF7417), color-stop(1, #82A8FF))'}]
20 | 'output': '-webkit-gradient(linear, right top, left top, color-stop(0, #FF7417) , color-stop(1, #82A8FF) )'
21 | }
22 | {
23 | 'regex': '^(https?)'
24 | 'test_strings': [{'string': 'https://github.com', 'matches': ['https']}]
25 | 'output': 'https ://github.com'
26 | }
27 | {
28 | 'regex': '^(https?)://((?:[A-Z0-9]*\\.?)*)((?:\\/?[A-Z0-9])*)'
29 | 'option': 'i'
30 | 'test_strings': [
31 | {'string': 'https://github.com/jonmagic/scriptular', 'matches': ['https', 'github.com', '/jonmagic/scriptular']}
32 | {'string': 'http://scriptular.com', 'matches': ['http', 'scriptular.com']}
33 | {'string': 'http://www.google.com'}
34 | {'string': 'http://www.guardian.co.uk'}
35 | ]
36 | 'output': 'https://github.com/jonmagic/scriptular '
37 | }
38 | {'regex': 'mono', 'option': 'g', 'test_strings': [{'string': 'monolimamonolima'}], 'output': 'mono limamono lima'}
39 | {'regex': '(<.{1,2}>)', 'option': '', 'test_strings': [{'string': 'foo '}], 'output': '<li> foo</li>'}
40 | {'regex': '(<\/?(LI)>)', 'option': 'gi', 'test_strings': [{'string': 'foo '}], 'output': '<li> foo</li> '}
41 | ]
42 |
43 | for subject, i in subjects
44 | do (subject) ->
45 | it "subject #{i} returns correct output", ->
46 | @app.expression.value = @app.expression.buildRegex(subject['regex'], subject['option'])
47 | @app.test_strings.values = (item['string'] for item in subject['test_strings'])
48 |
49 | @app.results.compile()
50 | expect($('ul#results li').html()).toEqual(subject['output'])
51 |
52 | for subject in subjects
53 | do (subject) ->
54 | it "subject #{subject['regex']} returns correct groups", ->
55 | for test in subject['test_strings']
56 | return true unless test['matches']
57 |
58 | @app.expression.value = @app.expression.buildRegex(subject['regex'], subject['option'])
59 | @app.test_strings.values = [test['string']]
60 |
61 | @app.results.compile()
62 |
63 | expect($('ul#groups ol li').length).toBe(test['matches'].length)
64 |
65 | for match, i in test['matches']
66 | expect($($('ul#groups ol li')[i]).text()).toEqual(match);
67 |
--------------------------------------------------------------------------------
/scripts/application.coffee:
--------------------------------------------------------------------------------
1 | $ = jQuery
2 |
3 | class Expression extends Spine.Controller
4 | elements:
5 | 'input[name=expression]': 'regexp'
6 | 'input[name=option]': 'option'
7 |
8 | events:
9 | 'keyup input': 'onKeyPress'
10 |
11 | onKeyPress: (event) ->
12 | try
13 | @value = @buildRegex @regexp.val(), @option.val()
14 | catch error
15 | @.trigger 'update'
16 |
17 | buildRegex: (value, option) ->
18 | new RegExp(value, option)
19 |
20 | asUrlPart:() ->
21 | encodeURIComponent(@regexp.val() + "||||" + @option.val())
22 |
23 | class TestStrings extends Spine.Controller
24 | elements:
25 | 'textarea': 'input'
26 |
27 | events:
28 | 'keyup textarea': 'onKeyPress'
29 |
30 | onKeyPress: (event) ->
31 | @getValues(@input.val())
32 | @.trigger 'update'
33 |
34 | getValues: (val) ->
35 | @values = val.split('\n')
36 |
37 | asUrlPart:() ->
38 | encodeURIComponent(JSON.stringify(@values))
39 |
40 | class Results
41 | constructor: (@expression, @test_strings) ->
42 | @expression.bind 'update', @compile
43 | @test_strings.bind 'update', @compile
44 |
45 | compile: =>
46 | $('ul#results').empty()
47 | $('ul#groups').empty()
48 | count = 1
49 |
50 | if @expression.regexp.val() != ''
51 | try
52 | new RegExp(@expression.regexp.val())
53 | catch
54 | @showRegexError()
55 | return true
56 | if @expression.regexp.val() == '' && @test_strings.input.val() == ''
57 | @showIntro()
58 | return true
59 | else if @expression.regexp.val() == '' || @test_strings.input.val() == ''
60 | @showError()
61 | return true
62 | else unless @test_strings.values
63 | return true
64 |
65 | try
66 | for value in @test_strings.values
67 | matches = value.match(@expression.value)
68 | @matchResults(value, matches)
69 | @matchGroups(value, matches, count)
70 | count += 1
71 | @addShareLink(@expression.asUrlPart(), @test_strings.asUrlPart())
72 | @showOutput()
73 | catch error
74 | @showError()
75 |
76 | addShareLink: (expression_url, test_strings_url) ->
77 | url = window.location.protocol + "//" + window.location.host
78 | url += "/#" + expression_url + encodeURIComponent("||||") + test_strings_url
79 | $("#share_link").attr("href", url)
80 |
81 | ###
82 | escape function from Peter Hoffman found at
83 | http://peter-hoffmann.com/2012/coffeescript-string-interpolation-with-html-escaping.html
84 | ###
85 | escape: (s) ->
86 | (''+s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"')
88 | .replace(/'/g, ''').replace(/\//g,'/')
89 |
90 | matchResults: (value, matches) ->
91 | return unless matches
92 |
93 | string = @generateMatches(value,@expression.value);
94 | @drawResult string
95 |
96 | generateMatches: (value, regex) ->
97 | @escape(value.replace(regex, "~~scriptular_begin_match~~$&~~scriptular_end_match~~"))
98 | .replace(/~~scriptular_begin_match~~/g, '')
99 | .replace(/~~scriptular_end_match~~/g, ' ')
100 |
101 | drawResult: (string) ->
102 | $('ul#results').append("#{string} ")
103 |
104 | matchGroups: (value, matches, count) ->
105 | return unless matches
106 |
107 | $('ul#groups').append("Match #{count} ")
108 |
109 | if @expression.value.global
110 | for match in matches
111 | return if match == ''
112 | @drawGroup(count, match)
113 | else
114 | for match in matches[1..-1]
115 | return if match == ''
116 | @drawGroup(count, match)
117 |
118 | drawGroup: (count, match) ->
119 | match = @escape match
120 | $("ul#groups li#match_#{count} ol").append("#{match} ")
121 |
122 | showIntro: ->
123 | $('#error').hide()
124 | $('#output').hide()
125 | $('#intro').show()
126 | $('#regex-error').hide()
127 |
128 | showError: ->
129 | $('#intro').hide()
130 | $('#output').hide()
131 | $('#error').show()
132 | $('#regex-error').hide()
133 |
134 | showOutput: ->
135 | $('#intro').hide()
136 | $('#error').hide()
137 | $('#output').show()
138 | $('#regex-error').hide()
139 |
140 | showRegexError: ->
141 | $('#intro').hide()
142 | $('#error').hide()
143 | $('#output').hide()
144 | $('#regex-error').show()
145 |
146 | class App
147 | constructor: ->
148 | @expression = new Expression(el: '#expression')
149 | @test_strings = new TestStrings(el: '#test_strings')
150 | @results = new Results(@expression, @test_strings)
151 | $('#example').bind 'click', @loadExample
152 | @loadFromHash() if window.location.hash != ''
153 |
154 | loadFromHash: () =>
155 | [regex, option, test_strings_from_url] = decodeURIComponent(window.location.hash.substr(1)).split("||||")
156 | test_strings_from_url = JSON.parse(test_strings_from_url)
157 |
158 | @load(regex,option,test_strings_from_url)
159 |
160 | loadExample: (event) =>
161 | event.preventDefault()
162 |
163 | regex = "^(https?)://((?:[A-Z0-9]*\\\.?)*)((?:\\\/?[A-Z0-9])*)"
164 | option = 'i'
165 | test_strings = [
166 | 'https://github.com/jonmagic/scriptular'
167 | 'http://scriptular.com'
168 | 'http://www.google.com'
169 | 'http://www.guardian.co.uk'
170 | ]
171 |
172 | @load(regex,option,test_strings)
173 |
174 | load: (regex,option,test_strings) =>
175 | $('input[name=expression]').val(regex)
176 | $('input[name=option]').val(option)
177 | $('textarea').val(test_strings.join('\n'))
178 | @expression.onKeyPress()
179 | @test_strings.onKeyPress()
180 | @results.compile
181 |
182 |
183 | window.App = App
184 | window.$ = $
185 |
--------------------------------------------------------------------------------
/spec/ResultsSpec.js:
--------------------------------------------------------------------------------
1 | // Generated by CoffeeScript 1.12.7
2 | (function() {
3 | describe('Results', function() {
4 | var fn, i, j, k, len, len1, results, subject, subjects;
5 | beforeEach(function() {
6 | this.app = new App;
7 | $('ul#results').remove();
8 | $('body').append('');
9 | $('ul#groups').remove();
10 | return $('body').append('');
11 | });
12 | subjects = [
13 | {
14 | 'regex': 'a',
15 | 'test_strings': [
16 | {
17 | 'string': 'a'
18 | }
19 | ],
20 | 'output': 'a '
21 | }, {
22 | 'regex': '(issues)?',
23 | 'test_strings': [
24 | {
25 | 'string': 'issues'
26 | }
27 | ],
28 | 'output': 'issues '
29 | }, {
30 | 'regex': 'a$',
31 | 'test_strings': [
32 | {
33 | 'string': 'asdfja'
34 | }
35 | ],
36 | 'output': 'asdfja '
37 | }, {
38 | 'regex': '"$',
39 | 'test_strings': [
40 | {
41 | 'string': '"hello"'
42 | }
43 | ],
44 | 'output': '"hello" '
45 | }, {
46 | 'regex': 'a(.*)c',
47 | 'test_strings': [
48 | {
49 | 'string': 'abcdd',
50 | 'matches': ['b']
51 | }
52 | ],
53 | 'output': 'abc dd'
54 | }, {
55 | 'regex': 'f(oo)',
56 | 'test_strings': [
57 | {
58 | 'string': 'foodbar',
59 | 'matches': ['oo']
60 | }
61 | ],
62 | 'output': 'foo dbar'
63 | }, {
64 | 'regex': 'color-stop\\((.+?)\\)',
65 | 'option': 'g',
66 | 'test_strings': [
67 | {
68 | 'string': '-webkit-gradient(linear, right top, left top, color-stop(0, #FF7417), color-stop(1, #82A8FF))'
69 | }
70 | ],
71 | 'output': '-webkit-gradient(linear, right top, left top, color-stop(0, #FF7417) , color-stop(1, #82A8FF) )'
72 | }, {
73 | 'regex': '^(https?)',
74 | 'test_strings': [
75 | {
76 | 'string': 'https://github.com',
77 | 'matches': ['https']
78 | }
79 | ],
80 | 'output': 'https ://github.com'
81 | }, {
82 | 'regex': '^(https?)://((?:[A-Z0-9]*\\.?)*)((?:\\/?[A-Z0-9])*)',
83 | 'option': 'i',
84 | 'test_strings': [
85 | {
86 | 'string': 'https://github.com/jonmagic/scriptular',
87 | 'matches': ['https', 'github.com', '/jonmagic/scriptular']
88 | }, {
89 | 'string': 'http://scriptular.com',
90 | 'matches': ['http', 'scriptular.com']
91 | }, {
92 | 'string': 'http://www.google.com'
93 | }, {
94 | 'string': 'http://www.guardian.co.uk'
95 | }
96 | ],
97 | 'output': 'https://github.com/jonmagic/scriptular '
98 | }, {
99 | 'regex': 'mono',
100 | 'option': 'g',
101 | 'test_strings': [
102 | {
103 | 'string': 'monolimamonolima'
104 | }
105 | ],
106 | 'output': 'mono limamono lima'
107 | }, {
108 | 'regex': '(<.{1,2}>)',
109 | 'option': '',
110 | 'test_strings': [
111 | {
112 | 'string': 'foo '
113 | }
114 | ],
115 | 'output': '<li> foo</li>'
116 | }, {
117 | 'regex': '(<\/?(LI)>)',
118 | 'option': 'gi',
119 | 'test_strings': [
120 | {
121 | 'string': 'foo '
122 | }
123 | ],
124 | 'output': '<li> foo</li> '
125 | }
126 | ];
127 | fn = function(subject) {
128 | return it("subject " + i + " returns correct output", function() {
129 | var item;
130 | this.app.expression.value = this.app.expression.buildRegex(subject['regex'], subject['option']);
131 | this.app.test_strings.values = (function() {
132 | var k, len1, ref, results;
133 | ref = subject['test_strings'];
134 | results = [];
135 | for (k = 0, len1 = ref.length; k < len1; k++) {
136 | item = ref[k];
137 | results.push(item['string']);
138 | }
139 | return results;
140 | })();
141 | this.app.results.compile();
142 | return expect($('ul#results li').html()).toEqual(subject['output']);
143 | });
144 | };
145 | for (i = j = 0, len = subjects.length; j < len; i = ++j) {
146 | subject = subjects[i];
147 | fn(subject);
148 | }
149 | results = [];
150 | for (k = 0, len1 = subjects.length; k < len1; k++) {
151 | subject = subjects[k];
152 | results.push((function(subject) {
153 | return it("subject " + subject['regex'] + " returns correct groups", function() {
154 | var l, len2, len3, m, match, ref, ref1, test;
155 | ref = subject['test_strings'];
156 | for (l = 0, len2 = ref.length; l < len2; l++) {
157 | test = ref[l];
158 | if (!test['matches']) {
159 | return true;
160 | }
161 | this.app.expression.value = this.app.expression.buildRegex(subject['regex'], subject['option']);
162 | this.app.test_strings.values = [test['string']];
163 | this.app.results.compile();
164 | expect($('ul#groups ol li').length).toBe(test['matches'].length);
165 | ref1 = test['matches'];
166 | for (i = m = 0, len3 = ref1.length; m < len3; i = ++m) {
167 | match = ref1[i];
168 | expect($($('ul#groups ol li')[i]).text()).toEqual(match);
169 | }
170 | }
171 | });
172 | })(subject));
173 | }
174 | return results;
175 | });
176 |
177 | }).call(this);
178 |
--------------------------------------------------------------------------------
/application.css:
--------------------------------------------------------------------------------
1 | /* RESET */
2 | html, body, div, span, applet, object, iframe,
3 | h1, h2, h3, h4, h5, h6, p, blockquote, pre,
4 | a, abbr, acronym, address, big, cite, code,
5 | del, dfn, em, img, ins, kbd, q, s, samp,
6 | small, strike, strong, sub, sup, tt, var,
7 | b, u, i, center,
8 | dl, dt, dd, ol, ul, li,
9 | fieldset, form, label, legend,
10 | table, caption, tbody, tfoot, thead, tr, th, td,
11 | article, aside, canvas, details, embed,
12 | figure, figcaption, footer, header, hgroup,
13 | menu, nav, output, ruby, section, summary,
14 | time, mark, audio, video {
15 | margin: 0;
16 | padding: 0;
17 | border: 0;
18 | font-size: 100%;
19 | font: inherit;
20 | vertical-align: baseline;
21 | }
22 |
23 | body {
24 | line-height: 1;
25 | }
26 |
27 | ol, ul {
28 | list-style: none;
29 | }
30 |
31 | table {
32 | border-collapse: collapse;
33 | border-spacing: 0;
34 | }
35 |
36 | caption, th, td {
37 | text-align: left;
38 | font-weight: normal;
39 | vertical-align: middle;
40 | }
41 |
42 | q, blockquote {
43 | quotes: none;
44 | }
45 |
46 | q:before, q:after, blockquote:before, blockquote:after {
47 | content: "";
48 | content: none;
49 | }
50 |
51 | a img {
52 | border: none;
53 | }
54 |
55 | article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary {
56 | display: block;
57 | }
58 |
59 |
60 | /* my styles */
61 | body {
62 | color: #080901;
63 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
64 | font-size: 18px;
65 | background: #222 url(bg.png);
66 | color: #ccc;
67 | }
68 |
69 | #container {
70 | width: 960px;
71 | margin: 0 auto;
72 | }
73 |
74 | #header {
75 | position: relative;
76 | overflow: hidden;
77 | }
78 |
79 | #header h1 {
80 | font-family: 'Reenie Beanie', cursive, sans-serif;
81 | font-size: 96px;
82 | font-weight: bold;
83 | margin: 0.1em 0;
84 | color: #FFF;
85 | line-height: 96px;
86 | float: left;
87 | }
88 |
89 | #header h1 a:hover {
90 | text-decoration: none;
91 | }
92 |
93 | #header h2 {
94 | color: #aaa;
95 | text-align: right;
96 | line-height: 18px;
97 | margin-top: 60px;
98 | font-weight: 100;
99 | letter-spacing: 0.1em;
100 | }
101 |
102 | h2 {
103 | font-size: 18px;
104 | margin-bottom: 10px;
105 | }
106 |
107 | p {
108 | font-size: 14px;
109 | margin-bottom: 10px;
110 | }
111 |
112 | a {
113 | color: #FFF;
114 | text-decoration: none;
115 | }
116 | a:hover {
117 | text-decoration: underline;
118 | }
119 |
120 | #main {
121 | float:left;
122 | width:590px;
123 | background-color: #FFFFFF;
124 | -moz-border-radius: 4px;
125 | -webkit-border-radius: 4px;
126 | -o-border-radius: 4px;
127 | -ms-border-radius: 4px;
128 | -khtml-border-radius: 4px;
129 | box-shadow: 0 0 30px #000;
130 | border-radius: 4px;
131 | padding: 30px;
132 | overflow: hidden;
133 | color: #333;
134 | }
135 |
136 | #main h2 {
137 | font-weight: 700;
138 | color: #369;
139 | }
140 |
141 | #main a {
142 | color: #F7296F;
143 | }
144 |
145 | #quick_reference {
146 | background-color: rgba(50,50,50,0.5);
147 | color: #FFF;
148 | height:350px;
149 | margin: 20px 0 0 650px;
150 | padding:20px 10px 0 20px;
151 | width: 280px;
152 | -webkit-border-top-right-radius: 10px;
153 | -webkit-border-bottom-right-radius: 10px;
154 | -moz-border-radius-topright: 10px;
155 | -moz-border-radius-bottomright: 10px;
156 | border-top-right-radius: 10px;
157 | border-bottom-right-radius: 10px;
158 | }
159 |
160 | #quick_reference .scrollable {
161 | overflow:auto;
162 | height:330px;
163 | }
164 |
165 | #quick_reference h2 {
166 | color: #999;
167 | }
168 |
169 | #quick_reference table {
170 | color: #FFF;
171 | font-size: 60%;
172 | margin-bottom: 20px;
173 | }
174 |
175 | #quick_reference th,
176 | #quick_reference td {
177 | padding-right: 15px;
178 | line-height:1.5em;
179 | }
180 |
181 | #quick_reference .regex {
182 | color: #F7296F;
183 | font-size: 14px;
184 | padding-right: 5px;
185 | text-align: center;
186 | width:60px;
187 | }
188 |
189 | input, textarea, #results, #groups {
190 | margin-bottom: 20px;
191 | background-color: white;
192 | border: 1px solid #ccc;
193 | font-size: 16px;
194 | padding: 10px;
195 | -moz-border-radius: 3px;
196 | -webkit-border-radius: 3px;
197 | -o-border-radius: 3px;
198 | -ms-border-radius: 3px;
199 | -khtml-border-radius: 3px;
200 | border-radius: 3px;
201 | }
202 |
203 | #expression {
204 | font-size: 25px;
205 | }
206 |
207 | #expression input[name=expression] {
208 | margin: 0 4px;
209 | width: 464px;
210 | }
211 |
212 | #expression input[name=option] {
213 | box-sizing: border-box;
214 | margin-left: 4px;
215 | width: 70px;
216 | }
217 |
218 | .invalid-expression, input:invalid {
219 | border: 1px solid #F7296F;
220 | }
221 |
222 | #expression input[name=expression],
223 | #expression input[name=option] {
224 | font-family: menlo, courier, sans-serif;
225 | }
226 |
227 | #test_strings textarea {
228 | height: 95px;
229 | width: 565px;
230 | }
231 |
232 | #output, #error, #regex-error {
233 | display: none;
234 | }
235 |
236 | #intro, #error, #output, #regex-error {
237 | margin: 10px -30px -30px -30px;
238 | padding: 30px;
239 | background-color: #eef;
240 | border-top: 1px solid #dde;
241 | }
242 |
243 | #regex-error {
244 | color: #f7296f;
245 | font-size: 14px;
246 | }
247 |
248 | #results li {
249 | margin-bottom: 10px;
250 | }
251 |
252 | #results li:last-child {
253 | margin-bottom: 0px;
254 | }
255 |
256 | #results span {
257 | background-color: #9CE39E;
258 | margin: 3px;
259 | }
260 |
261 | #groups {
262 | margin-bottom: 20px;
263 | }
264 |
265 | #groups h3 {
266 | font-size: 1em;
267 | margin-bottom: 5px;
268 | color: #999;
269 |
270 | }
271 |
272 | #groups ol {
273 | list-style-type: decimal;
274 | margin-bottom: 10px;
275 | padding-left: 30px;
276 | }
277 |
278 | #shares a {
279 | color: #444;
280 | font-size: 14px;
281 | text-decoration: underline;
282 | }
283 |
284 | #footer {
285 | clear: both;
286 | padding-top: 20px;
287 | text-align: left;
288 | font-size: 0.9em;
289 | -webkit-font-smoothing: antialiased;
290 | }
291 |
--------------------------------------------------------------------------------
/spec/lib/jasmine-html.js:
--------------------------------------------------------------------------------
1 | jasmine.TrivialReporter = function(doc) {
2 | this.document = doc || document;
3 | this.suiteDivs = {};
4 | this.logRunningSpecs = false;
5 | };
6 |
7 | jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
8 | var el = document.createElement(type);
9 |
10 | for (var i = 2; i < arguments.length; i++) {
11 | var child = arguments[i];
12 |
13 | if (typeof child === 'string') {
14 | el.appendChild(document.createTextNode(child));
15 | } else {
16 | if (child) { el.appendChild(child); }
17 | }
18 | }
19 |
20 | for (var attr in attrs) {
21 | if (attr == "className") {
22 | el[attr] = attrs[attr];
23 | } else {
24 | el.setAttribute(attr, attrs[attr]);
25 | }
26 | }
27 |
28 | return el;
29 | };
30 |
31 | jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
32 | var showPassed, showSkipped;
33 |
34 | this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' },
35 | this.createDom('div', { className: 'banner' },
36 | this.createDom('div', { className: 'logo' },
37 | this.createDom('span', { className: 'title' }, "Jasmine"),
38 | this.createDom('span', { className: 'version' }, runner.env.versionString())),
39 | this.createDom('div', { className: 'options' },
40 | "Show ",
41 | showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
42 | this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
43 | showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
44 | this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
45 | )
46 | ),
47 |
48 | this.runnerDiv = this.createDom('div', { className: 'runner running' },
49 | this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
50 | this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
51 | this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
52 | );
53 |
54 | this.document.body.appendChild(this.outerDiv);
55 |
56 | var suites = runner.suites();
57 | for (var i = 0; i < suites.length; i++) {
58 | var suite = suites[i];
59 | var suiteDiv = this.createDom('div', { className: 'suite' },
60 | this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
61 | this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
62 | this.suiteDivs[suite.id] = suiteDiv;
63 | var parentDiv = this.outerDiv;
64 | if (suite.parentSuite) {
65 | parentDiv = this.suiteDivs[suite.parentSuite.id];
66 | }
67 | parentDiv.appendChild(suiteDiv);
68 | }
69 |
70 | this.startedAt = new Date();
71 |
72 | var self = this;
73 | showPassed.onclick = function(evt) {
74 | if (showPassed.checked) {
75 | self.outerDiv.className += ' show-passed';
76 | } else {
77 | self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
78 | }
79 | };
80 |
81 | showSkipped.onclick = function(evt) {
82 | if (showSkipped.checked) {
83 | self.outerDiv.className += ' show-skipped';
84 | } else {
85 | self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
86 | }
87 | };
88 | };
89 |
90 | jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
91 | var results = runner.results();
92 | var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
93 | this.runnerDiv.setAttribute("class", className);
94 | //do it twice for IE
95 | this.runnerDiv.setAttribute("className", className);
96 | var specs = runner.specs();
97 | var specCount = 0;
98 | for (var i = 0; i < specs.length; i++) {
99 | if (this.specFilter(specs[i])) {
100 | specCount++;
101 | }
102 | }
103 | var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
104 | message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
105 | this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
106 |
107 | this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
108 | };
109 |
110 | jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
111 | var results = suite.results();
112 | var status = results.passed() ? 'passed' : 'failed';
113 | if (results.totalCount === 0) { // todo: change this to check results.skipped
114 | status = 'skipped';
115 | }
116 | this.suiteDivs[suite.id].className += " " + status;
117 | };
118 |
119 | jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) {
120 | if (this.logRunningSpecs) {
121 | this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
122 | }
123 | };
124 |
125 | jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
126 | var results = spec.results();
127 | var status = results.passed() ? 'passed' : 'failed';
128 | if (results.skipped) {
129 | status = 'skipped';
130 | }
131 | var specDiv = this.createDom('div', { className: 'spec ' + status },
132 | this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
133 | this.createDom('a', {
134 | className: 'description',
135 | href: '?spec=' + encodeURIComponent(spec.getFullName()),
136 | title: spec.getFullName()
137 | }, spec.description));
138 |
139 |
140 | var resultItems = results.getItems();
141 | var messagesDiv = this.createDom('div', { className: 'messages' });
142 | for (var i = 0; i < resultItems.length; i++) {
143 | var result = resultItems[i];
144 |
145 | if (result.type == 'log') {
146 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
147 | } else if (result.type == 'expect' && result.passed && !result.passed()) {
148 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
149 |
150 | if (result.trace.stack) {
151 | messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
152 | }
153 | }
154 | }
155 |
156 | if (messagesDiv.childNodes.length > 0) {
157 | specDiv.appendChild(messagesDiv);
158 | }
159 |
160 | this.suiteDivs[spec.suite.id].appendChild(specDiv);
161 | };
162 |
163 | jasmine.TrivialReporter.prototype.log = function() {
164 | var console = jasmine.getGlobal().console;
165 | if (console && console.log) {
166 | if (console.log.apply) {
167 | console.log.apply(console, arguments);
168 | } else {
169 | console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
170 | }
171 | }
172 | };
173 |
174 | jasmine.TrivialReporter.prototype.getLocation = function() {
175 | return this.document.location;
176 | };
177 |
178 | jasmine.TrivialReporter.prototype.specFilter = function(spec) {
179 | var paramMap = {};
180 | var params = this.getLocation().search.substring(1).split('&');
181 | for (var i = 0; i < params.length; i++) {
182 | var p = params[i].split('=');
183 | paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
184 | }
185 |
186 | if (!paramMap.spec) {
187 | return true;
188 | }
189 | return spec.getFullName().indexOf(paramMap.spec) === 0;
190 | };
191 |
--------------------------------------------------------------------------------
/application.js:
--------------------------------------------------------------------------------
1 | // Generated by CoffeeScript 1.12.7
2 | (function() {
3 | var $, App, Expression, Results, TestStrings,
4 | extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
5 | hasProp = {}.hasOwnProperty,
6 | bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
7 |
8 | $ = jQuery;
9 |
10 | Expression = (function(superClass) {
11 | extend(Expression, superClass);
12 |
13 | function Expression() {
14 | return Expression.__super__.constructor.apply(this, arguments);
15 | }
16 |
17 | Expression.prototype.elements = {
18 | 'input[name=expression]': 'regexp',
19 | 'input[name=option]': 'option'
20 | };
21 |
22 | Expression.prototype.events = {
23 | 'keyup input': 'onKeyPress'
24 | };
25 |
26 | Expression.prototype.onKeyPress = function(event) {
27 | var error;
28 | try {
29 | this.value = this.buildRegex(this.regexp.val(), this.option.val());
30 | } catch (error1) {
31 | error = error1;
32 | }
33 | return this.trigger('update');
34 | };
35 |
36 | Expression.prototype.buildRegex = function(value, option) {
37 | return new RegExp(value, option);
38 | };
39 |
40 | Expression.prototype.asUrlPart = function() {
41 | return encodeURIComponent(this.regexp.val() + "||||" + this.option.val());
42 | };
43 |
44 | return Expression;
45 |
46 | })(Spine.Controller);
47 |
48 | TestStrings = (function(superClass) {
49 | extend(TestStrings, superClass);
50 |
51 | function TestStrings() {
52 | return TestStrings.__super__.constructor.apply(this, arguments);
53 | }
54 |
55 | TestStrings.prototype.elements = {
56 | 'textarea': 'input'
57 | };
58 |
59 | TestStrings.prototype.events = {
60 | 'keyup textarea': 'onKeyPress'
61 | };
62 |
63 | TestStrings.prototype.onKeyPress = function(event) {
64 | this.getValues(this.input.val());
65 | return this.trigger('update');
66 | };
67 |
68 | TestStrings.prototype.getValues = function(val) {
69 | return this.values = val.split('\n');
70 | };
71 |
72 | TestStrings.prototype.asUrlPart = function() {
73 | return encodeURIComponent(JSON.stringify(this.values));
74 | };
75 |
76 | return TestStrings;
77 |
78 | })(Spine.Controller);
79 |
80 | Results = (function() {
81 | function Results(expression, test_strings1) {
82 | this.expression = expression;
83 | this.test_strings = test_strings1;
84 | this.compile = bind(this.compile, this);
85 | this.expression.bind('update', this.compile);
86 | this.test_strings.bind('update', this.compile);
87 | }
88 |
89 | Results.prototype.compile = function() {
90 | var count, error, i, len, matches, ref, value;
91 | $('ul#results').empty();
92 | $('ul#groups').empty();
93 | count = 1;
94 | if (this.expression.regexp.val() !== '') {
95 | try {
96 | new RegExp(this.expression.regexp.val());
97 | } catch (error1) {
98 | this.showRegexError();
99 | return true;
100 | }
101 | }
102 | if (this.expression.regexp.val() === '' && this.test_strings.input.val() === '') {
103 | this.showIntro();
104 | return true;
105 | } else if (this.expression.regexp.val() === '' || this.test_strings.input.val() === '') {
106 | this.showError();
107 | return true;
108 | } else if (!this.test_strings.values) {
109 | return true;
110 | }
111 | try {
112 | ref = this.test_strings.values;
113 | for (i = 0, len = ref.length; i < len; i++) {
114 | value = ref[i];
115 | matches = value.match(this.expression.value);
116 | this.matchResults(value, matches);
117 | this.matchGroups(value, matches, count);
118 | count += 1;
119 | }
120 | this.addShareLink(this.expression.asUrlPart(), this.test_strings.asUrlPart());
121 | return this.showOutput();
122 | } catch (error1) {
123 | error = error1;
124 | return this.showError();
125 | }
126 | };
127 |
128 | Results.prototype.addShareLink = function(expression_url, test_strings_url) {
129 | var url;
130 | url = window.location.protocol + "//" + window.location.host;
131 | url += "/#" + expression_url + encodeURIComponent("||||") + test_strings_url;
132 | return $("#share_link").attr("href", url);
133 | };
134 |
135 |
136 | /*
137 | escape function from Peter Hoffman found at
138 | http://peter-hoffmann.com/2012/coffeescript-string-interpolation-with-html-escaping.html
139 | */
140 |
141 | Results.prototype.escape = function(s) {
142 | return ('' + s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g, '/');
143 | };
144 |
145 | Results.prototype.matchResults = function(value, matches) {
146 | var string;
147 | if (!matches) {
148 | return;
149 | }
150 | string = this.generateMatches(value, this.expression.value);
151 | return this.drawResult(string);
152 | };
153 |
154 | Results.prototype.generateMatches = function(value, regex) {
155 | return this.escape(value.replace(regex, "~~scriptular_begin_match~~$&~~scriptular_end_match~~")).replace(/~~scriptular_begin_match~~/g, '').replace(/~~scriptular_end_match~~/g, ' ');
156 | };
157 |
158 | Results.prototype.drawResult = function(string) {
159 | return $('ul#results').append("" + string + " ");
160 | };
161 |
162 | Results.prototype.matchGroups = function(value, matches, count) {
163 | var i, j, len, len1, match, ref;
164 | if (!matches) {
165 | return;
166 | }
167 | $('ul#groups').append("Match " + count + " ");
168 | if (this.expression.value.global) {
169 | for (i = 0, len = matches.length; i < len; i++) {
170 | match = matches[i];
171 | if (match === '') {
172 | return;
173 | }
174 | this.drawGroup(count, match);
175 | }
176 | } else {
177 | ref = matches.slice(1);
178 | for (j = 0, len1 = ref.length; j < len1; j++) {
179 | match = ref[j];
180 | if (match === '') {
181 | return;
182 | }
183 | this.drawGroup(count, match);
184 | }
185 | }
186 | };
187 |
188 | Results.prototype.drawGroup = function(count, match) {
189 | match = this.escape(match);
190 | return $("ul#groups li#match_" + count + " ol").append("" + match + " ");
191 | };
192 |
193 | Results.prototype.showIntro = function() {
194 | $('#error').hide();
195 | $('#output').hide();
196 | $('#intro').show();
197 | return $('#regex-error').hide();
198 | };
199 |
200 | Results.prototype.showError = function() {
201 | $('#intro').hide();
202 | $('#output').hide();
203 | $('#error').show();
204 | return $('#regex-error').hide();
205 | };
206 |
207 | Results.prototype.showOutput = function() {
208 | $('#intro').hide();
209 | $('#error').hide();
210 | $('#output').show();
211 | return $('#regex-error').hide();
212 | };
213 |
214 | Results.prototype.showRegexError = function() {
215 | $('#intro').hide();
216 | $('#error').hide();
217 | $('#output').hide();
218 | return $('#regex-error').show();
219 | };
220 |
221 | return Results;
222 |
223 | })();
224 |
225 | App = (function() {
226 | function App() {
227 | this.load = bind(this.load, this);
228 | this.loadExample = bind(this.loadExample, this);
229 | this.loadFromHash = bind(this.loadFromHash, this);
230 | this.expression = new Expression({
231 | el: '#expression'
232 | });
233 | this.test_strings = new TestStrings({
234 | el: '#test_strings'
235 | });
236 | this.results = new Results(this.expression, this.test_strings);
237 | $('#example').bind('click', this.loadExample);
238 | if (window.location.hash !== '') {
239 | this.loadFromHash();
240 | }
241 | }
242 |
243 | App.prototype.loadFromHash = function() {
244 | var option, ref, regex, test_strings_from_url;
245 | ref = decodeURIComponent(window.location.hash.substr(1)).split("||||"), regex = ref[0], option = ref[1], test_strings_from_url = ref[2];
246 | test_strings_from_url = JSON.parse(test_strings_from_url);
247 | return this.load(regex, option, test_strings_from_url);
248 | };
249 |
250 | App.prototype.loadExample = function(event) {
251 | var option, regex, test_strings;
252 | event.preventDefault();
253 | regex = "^(https?)://((?:[A-Z0-9]*\\\.?)*)((?:\\\/?[A-Z0-9])*)";
254 | option = 'i';
255 | test_strings = ['https://github.com/jonmagic/scriptular', 'http://scriptular.com', 'http://www.google.com', 'http://www.guardian.co.uk'];
256 | return this.load(regex, option, test_strings);
257 | };
258 |
259 | App.prototype.load = function(regex, option, test_strings) {
260 | $('input[name=expression]').val(regex);
261 | $('input[name=option]').val(option);
262 | $('textarea').val(test_strings.join('\n'));
263 | this.expression.onKeyPress();
264 | this.test_strings.onKeyPress();
265 | return this.results.compile;
266 | };
267 |
268 | return App;
269 |
270 | })();
271 |
272 | window.App = App;
273 |
274 | window.$ = $;
275 |
276 | }).call(this);
277 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Scriptular - Javascript Regular Expression Editor
5 |
6 |
7 |
8 |
9 |
10 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
37 |
38 |
39 |
Regular Expression:
40 | / /
41 |
42 |
43 |
44 |
Test Strings:
45 |
46 |
47 |
48 |
49 |
Scriptular is a javascript regular expression editor. Inspired by Rubular it gives you a simple way to test javascript regular expressions as you write them.
50 |
51 |
Start by entering a regular expression and then a test string. Or give this example a try .
52 |
53 |
Learn more about regular expressions in javascript.
54 |
55 |
56 |
59 |
60 |
Invalid regular expression
61 |
62 |
63 |
64 |
Match Results:
65 |
66 |
Match Groups:
67 |
68 |
Share Link:
69 |
72 |
73 |
74 |
75 |
224 |
225 |
228 |
229 |
243 |
244 |
245 |
--------------------------------------------------------------------------------
/scripts/spine.coffee:
--------------------------------------------------------------------------------
1 | ###
2 | Spine.js MVC library
3 | Released under the MIT License
4 | ###
5 |
6 | Events =
7 | bind: (ev, callback) ->
8 | evs = ev.split(' ')
9 | @_callbacks = {} unless @hasOwnProperty('_callbacks') and @_callbacks
10 | for name in evs
11 | @_callbacks[name] or= []
12 | @_callbacks[name].push(callback)
13 | this
14 |
15 | one: (ev, callback) ->
16 | @bind ev, handler = ->
17 | @unbind(ev, handler)
18 | callback.apply(this, arguments)
19 |
20 | trigger: (args...) ->
21 | ev = args.shift()
22 | list = @hasOwnProperty('_callbacks') and @_callbacks?[ev]
23 | return unless list
24 | for callback in list
25 | if callback.apply(this, args) is false
26 | break
27 | true
28 |
29 | listenTo: (obj, ev, callback) ->
30 | obj.bind(ev, callback)
31 | @listeningTo or= []
32 | @listeningTo.push {obj, ev, callback}
33 | this
34 |
35 | listenToOnce: (obj, ev, callback) ->
36 | listeningToOnce = @listeningToOnce or= []
37 | obj.bind ev, handler = ->
38 | idx = -1
39 | for lt, i in listeningToOnce when lt.obj is obj
40 | idx = i if lt.ev is ev and lt.callback is callback
41 | obj.unbind(ev, handler)
42 | listeningToOnce.splice(idx, 1) unless idx is -1
43 | callback.apply(this, arguments)
44 | listeningToOnce.push {obj, ev, callback, handler}
45 | this
46 |
47 | stopListening: (obj, events, callback) ->
48 | if arguments.length is 0
49 | for listeningTo in [@listeningTo, @listeningToOnce]
50 | continue unless listeningTo
51 | for lt in listeningTo
52 | lt.obj.unbind(lt.ev, lt.handler or lt.callback)
53 | @listeningTo = undefined
54 | @listeningToOnce = undefined
55 |
56 | else if obj
57 | for listeningTo in [@listeningTo, @listeningToOnce]
58 | continue unless listeningTo
59 | events = if events then events.split(' ') else [undefined]
60 | for ev in events
61 | for idx in [listeningTo.length-1..0]
62 | lt = listeningTo[idx]
63 | continue if callback and (lt.handler or lt.callback) isnt callback
64 | if (not ev) or (ev is lt.ev)
65 | lt.obj.unbind(lt.ev, lt.handler or lt.callback)
66 | listeningTo.splice(idx, 1) unless idx is -1
67 | else if ev
68 | evts = lt.ev.split(' ')
69 | if ev in evts
70 | evts = (e for e in evts when e isnt ev)
71 | lt.ev = $.trim(evts.join(' '))
72 | lt.obj.unbind(ev, lt.handler or lt.callback)
73 |
74 | unbind: (ev, callback) ->
75 | if arguments.length is 0
76 | @_callbacks = {}
77 | return this
78 | return this unless ev
79 | evs = ev.split(' ')
80 | for name in evs
81 | list = @_callbacks?[name]
82 | continue unless list
83 | unless callback
84 | delete @_callbacks[name]
85 | continue
86 | for cb, i in list when (cb is callback)
87 | list = list.slice()
88 | list.splice(i, 1)
89 | @_callbacks[name] = list
90 | break
91 | this
92 |
93 | Events.on = Events.bind
94 | Events.off = Events.unbind
95 |
96 | Log =
97 | trace: true
98 |
99 | logPrefix: '(App)'
100 |
101 | log: (args...) ->
102 | return unless @trace
103 | if @logPrefix then args.unshift(@logPrefix)
104 | console?.log?(args...)
105 | this
106 |
107 | moduleKeywords = ['included', 'extended']
108 |
109 | class Module
110 | @include: (obj) ->
111 | throw new Error('include(obj) requires obj') unless obj
112 | for key, value of obj when key not in moduleKeywords
113 | @::[key] = value
114 | obj.included?.apply(this)
115 | this
116 |
117 | @extend: (obj) ->
118 | throw new Error('extend(obj) requires obj') unless obj
119 | for key, value of obj when key not in moduleKeywords
120 | @[key] = value
121 | obj.extended?.apply(this)
122 | this
123 |
124 | @proxy: (func) ->
125 | => func.apply(this, arguments)
126 |
127 | proxy: (func) ->
128 | => func.apply(this, arguments)
129 |
130 | constructor: ->
131 | @init?(arguments...)
132 |
133 | class Model extends Module
134 | @extend Events
135 |
136 | @records : []
137 | @irecords : {}
138 | @attributes : []
139 |
140 | @configure: (name, attributes...) ->
141 | @className = name
142 | @deleteAll()
143 | @attributes = attributes if attributes.length
144 | @attributes and= makeArray(@attributes)
145 | @attributes or= []
146 | @unbind()
147 | this
148 |
149 | @toString: -> "#{@className}(#{@attributes.join(", ")})"
150 |
151 | @find: (id, notFound = @notFound) ->
152 | @irecords[id]?.clone() or notFound?(id)
153 |
154 | @notFound: (id) -> null
155 |
156 | @exists: (id) -> Boolean @irecords[id]
157 |
158 | @addRecord: (record, options = {}) ->
159 | if record.id and @irecords[record.id]
160 | @irecords[record.id].remove(options)
161 | record = @irecords[record.id].load(record) unless options.clear
162 | record.id or= record.cid
163 | @irecords[record.id] ?= record
164 | @irecords[record.cid] ?= record
165 | @records.push(record)
166 |
167 | @refresh: (values, options = {}) ->
168 | @deleteAll() if options.clear
169 |
170 | records = @fromJSON(values)
171 | records = [records] unless isArray(records)
172 | @addRecord(record, options) for record in records
173 | @sort()
174 |
175 | result = @cloneArray(records)
176 | @trigger('refresh', result, options)
177 | result
178 |
179 | @select: (callback) ->
180 | (record.clone() for record in @records when callback(record))
181 |
182 | @findByAttribute: (name, value) ->
183 | for record in @records
184 | if record[name] is value
185 | return record.clone()
186 | null
187 |
188 | @findAllByAttribute: (name, value) ->
189 | @select (item) ->
190 | item[name] is value
191 |
192 | @each: (callback) ->
193 | callback(record.clone()) for record in @records
194 |
195 | @all: ->
196 | @cloneArray(@records)
197 |
198 | @slice: (begin = 0, end)->
199 | @cloneArray(@records.slice(begin, end))
200 |
201 | @first: (end = 1)->
202 | if end > 1
203 | @cloneArray(@records.slice(0, end))
204 | else
205 | @records[0]?.clone()
206 |
207 | @last: (begin)->
208 | if typeof begin is 'number'
209 | @cloneArray(@records.slice(-begin))
210 | else
211 | @records[@records.length - 1]?.clone()
212 |
213 | @count: ->
214 | @records.length
215 |
216 | @deleteAll: ->
217 | @records = []
218 | @irecords = {}
219 |
220 | @destroyAll: (options) ->
221 | record.destroy(options) for record in @records
222 |
223 | @update: (id, atts, options) ->
224 | @find(id).updateAttributes(atts, options)
225 |
226 | @create: (atts, options) ->
227 | record = new @(atts)
228 | record.save(options)
229 |
230 | @destroy: (id, options) ->
231 | @find(id).destroy(options)
232 |
233 | @change: (callbackOrParams) ->
234 | if typeof callbackOrParams is 'function'
235 | @bind('change', callbackOrParams)
236 | else
237 | @trigger('change', arguments...)
238 |
239 | @fetch: (callbackOrParams) ->
240 | if typeof callbackOrParams is 'function'
241 | @bind('fetch', callbackOrParams)
242 | else
243 | @trigger('fetch', arguments...)
244 |
245 | @toJSON: ->
246 | @records
247 |
248 | @fromJSON: (objects) ->
249 | return unless objects
250 | if typeof objects is 'string'
251 | objects = JSON.parse(objects)
252 | if isArray(objects)
253 | for value in objects
254 | if value instanceof this
255 | value
256 | else
257 | new @(value)
258 | else
259 | return objects if objects instanceof this
260 | new @(objects)
261 |
262 | @fromForm: ->
263 | (new this).fromForm(arguments...)
264 |
265 | @sort: ->
266 | if @comparator
267 | @records.sort @comparator
268 | this
269 |
270 | # Private
271 |
272 | @cloneArray: (array) ->
273 | (value.clone() for value in array)
274 |
275 | @idCounter: 0
276 |
277 | @uid: (prefix = '') ->
278 | uid = prefix + @idCounter++
279 | uid = @uid(prefix) if @exists(uid)
280 | uid
281 |
282 | # Instance
283 |
284 | constructor: (atts) ->
285 | super
286 | if @constructor.uuid? and typeof @constructor.uuid is 'function'
287 | @cid = @constructor.uuid()
288 | @id = @cid unless @id
289 | else
290 | @cid = atts?.cid or @constructor.uid('c-')
291 | @load atts if atts
292 |
293 | isNew: ->
294 | not @exists()
295 |
296 | isValid: ->
297 | not @validate()
298 |
299 | validate: ->
300 |
301 | load: (atts) ->
302 | if atts.id then @id = atts.id
303 | for key, value of atts
304 | if typeof @[key] is 'function'
305 | continue if typeof value is 'function'
306 | @[key](value)
307 | else
308 | @[key] = value
309 | this
310 |
311 | attributes: ->
312 | result = {}
313 | for key in @constructor.attributes when key of this
314 | if typeof @[key] is 'function'
315 | result[key] = @[key]()
316 | else
317 | result[key] = @[key]
318 | result.id = @id if @id
319 | result
320 |
321 | eql: (rec) ->
322 | rec and rec.constructor is @constructor and
323 | ((rec.cid is @cid) or (rec.id and rec.id is @id))
324 |
325 | save: (options = {}) ->
326 | unless options.validate is false
327 | error = @validate()
328 | if error
329 | @trigger('error', error)
330 | return false
331 |
332 | @trigger('beforeSave', options)
333 | record = if @isNew() then @create(options) else @update(options)
334 | @stripCloneAttrs()
335 | @trigger('save', options)
336 | record
337 |
338 | stripCloneAttrs: ->
339 | return if @hasOwnProperty 'cid' # Make sure it's not the raw object
340 | for own key, value of this
341 | delete @[key] if key in @constructor.attributes
342 | this
343 |
344 | updateAttribute: (name, value, options) ->
345 | atts = {}
346 | atts[name] = value
347 | @updateAttributes(atts, options)
348 |
349 | updateAttributes: (atts, options) ->
350 | @load(atts)
351 | @save(options)
352 |
353 | changeID: (id) ->
354 | return if id is @id
355 | records = @constructor.irecords
356 | records[id] = records[@id]
357 | delete records[@id] unless @cid is @id
358 | @id = id
359 | @save()
360 |
361 | remove: (options = {}) ->
362 | # Remove record from model
363 | records = @constructor.records.slice(0)
364 | for record, i in records when @eql(record)
365 | records.splice(i, 1)
366 | break
367 | @constructor.records = records
368 | if options.clear
369 | # Remove the ID and CID indexes
370 | delete @constructor.irecords[@id]
371 | delete @constructor.irecords[@cid]
372 |
373 | destroy: (options = {}) ->
374 | options.clear ?= true
375 | @trigger('beforeDestroy', options)
376 | @remove(options)
377 | @destroyed = true
378 | # handle events
379 | @trigger('destroy', options)
380 | @trigger('change', 'destroy', options)
381 | if @listeningTo
382 | @stopListening()
383 | @unbind()
384 | this
385 |
386 | dup: (newRecord = true) ->
387 | atts = @attributes()
388 | if newRecord
389 | delete atts.id
390 | else
391 | atts.cid = @cid
392 | new @constructor(atts)
393 |
394 | clone: ->
395 | createObject(this)
396 |
397 | reload: ->
398 | return this if @isNew()
399 | original = @constructor.find(@id)
400 | @load(original.attributes())
401 | original
402 |
403 | refresh: (data) ->
404 | # go to the source and load attributes
405 | root = @constructor.irecords[@id]
406 | root.load(data)
407 | @trigger('refresh')
408 | @
409 |
410 | toJSON: ->
411 | @attributes()
412 |
413 | toString: ->
414 | "<#{@constructor.className} (#{JSON.stringify(this)})>"
415 |
416 | fromForm: (form) ->
417 | result = {}
418 |
419 | for checkbox in $(form).find('[type=checkbox]:not([value])')
420 | result[checkbox.name] = $(checkbox).prop('checked')
421 |
422 | for checkbox in $(form).find('[type=checkbox][name$="[]"]')
423 | name = checkbox.name.replace(/\[\]$/, '')
424 | result[name] or= []
425 | result[name].push checkbox.value if $(checkbox).prop('checked')
426 |
427 | for key in $(form).serializeArray()
428 | result[key.name] or= key.value
429 |
430 | @load(result)
431 |
432 | exists: ->
433 | @constructor.exists(@id)
434 |
435 | # Private
436 |
437 | update: (options) ->
438 | @trigger('beforeUpdate', options)
439 |
440 | records = @constructor.irecords
441 | records[@id].load @attributes()
442 |
443 | @constructor.sort()
444 |
445 | clone = records[@id].clone()
446 | clone.trigger('update', options)
447 | clone.trigger('change', 'update', options)
448 | clone
449 |
450 | create: (options) ->
451 | @trigger('beforeCreate', options)
452 | @id or= @cid
453 |
454 | record = @dup(false)
455 | @constructor.addRecord(record)
456 | @constructor.sort()
457 |
458 | clone = record.clone()
459 | clone.trigger('create', options)
460 | clone.trigger('change', 'create', options)
461 | clone
462 |
463 | bind: (events, callback) ->
464 | @constructor.bind events, binder = (record) =>
465 | if record && @eql(record)
466 | callback.apply(this, arguments)
467 | # create a wrapper function to be called with 'unbind' for each event
468 | for singleEvent in events.split(' ')
469 | do (singleEvent) =>
470 | @constructor.bind "unbind", unbinder = (record, event, cb) =>
471 | if record && @eql(record)
472 | return if event and event isnt singleEvent
473 | return if cb and cb isnt callback
474 | @constructor.unbind(singleEvent, binder)
475 | @constructor.unbind("unbind", unbinder)
476 | this
477 |
478 | one: (events, callback) ->
479 | @bind events, handler = =>
480 | @unbind(events, handler)
481 | callback.apply(this, arguments)
482 |
483 | trigger: (args...) ->
484 | args.splice(1, 0, this)
485 | @constructor.trigger(args...)
486 |
487 | listenTo: -> Events.listenTo.apply @, arguments
488 | listenToOnce: -> Events.listenToOnce.apply @, arguments
489 | stopListening: -> Events.stopListening.apply @, arguments
490 |
491 | unbind: (events, callback) ->
492 | if arguments.length is 0
493 | @trigger('unbind')
494 | else if events
495 | for event in events.split(' ')
496 | @trigger('unbind', event, callback)
497 |
498 | Model::on = Model::bind
499 | Model::off = Model::unbind
500 |
501 | class Controller extends Module
502 | @include Events
503 | @include Log
504 |
505 | eventSplitter: /^(\S+)\s*(.*)$/
506 | tag: 'div'
507 |
508 | constructor: (options) ->
509 | @options = options
510 |
511 | for key, value of @options
512 | @[key] = value
513 |
514 | @el = document.createElement(@tag) unless @el
515 | @el = $(@el)
516 | @$el = @el
517 |
518 | @el.addClass(@className) if @className
519 | @el.attr(@attributes) if @attributes
520 |
521 | @events = @constructor.events unless @events
522 | @elements = @constructor.elements unless @elements
523 |
524 | context = @
525 | while parent_prototype = context.constructor.__super__
526 | @events = $.extend({}, parent_prototype.events, @events) if parent_prototype.events
527 | @elements = $.extend({}, parent_prototype.elements, @elements) if parent_prototype.elements
528 | context = parent_prototype
529 |
530 | @delegateEvents(@events) if @events
531 | @refreshElements() if @elements
532 |
533 | super
534 |
535 | release: =>
536 | @trigger 'release', this
537 | # no need to unDelegateEvents since remove will end up handling that
538 | @el.remove()
539 | @unbind()
540 | @stopListening()
541 |
542 | $: (selector) -> $(selector, @el)
543 |
544 | delegateEvents: (events) ->
545 | for key, method of events
546 |
547 | if typeof(method) is 'function'
548 | # Always return true from event handlers
549 | method = do (method) => =>
550 | method.apply(this, arguments)
551 | true
552 | else
553 | unless @[method]
554 | throw new Error("#{method} doesn't exist")
555 |
556 | method = do (method) => =>
557 | @[method].apply(this, arguments)
558 | true
559 |
560 | match = key.match(@eventSplitter)
561 | eventName = match[1]
562 | selector = match[2]
563 |
564 | if selector is ''
565 | @el.bind(eventName, method)
566 | else
567 | @el.on(eventName, selector, method)
568 |
569 | refreshElements: ->
570 | for key, value of @elements
571 | @[value] = @$(key)
572 |
573 | delay: (func, timeout) ->
574 | setTimeout(@proxy(func), timeout || 0)
575 |
576 | # keep controllers elements obj in sync with it contents
577 |
578 | html: (element) ->
579 | @el.html(element.el or element)
580 | @refreshElements()
581 | @el
582 |
583 | append: (elements...) ->
584 | elements = (e.el or e for e in elements)
585 | @el.append(elements...)
586 | @refreshElements()
587 | @el
588 |
589 | appendTo: (element) ->
590 | @el.appendTo(element.el or element)
591 | @refreshElements()
592 | @el
593 |
594 | prepend: (elements...) ->
595 | elements = (e.el or e for e in elements)
596 | @el.prepend(elements...)
597 | @refreshElements()
598 | @el
599 |
600 | replace: (element) ->
601 | element = element.el or element
602 | element = $.trim(element) if typeof element is "string"
603 | # parseHTML is incompatible with Zepto
604 | [previous, @el] = [@el, $($.parseHTML(element)?[0] or element)]
605 | previous.replaceWith(@el)
606 | @delegateEvents(@events)
607 | @refreshElements()
608 | @el
609 |
610 | # Utilities & Shims
611 |
612 | $ = window?.jQuery or window?.Zepto or (element) -> element
613 |
614 | createObject = Object.create or (o) ->
615 | Func = ->
616 | Func.prototype = o
617 | new Func()
618 |
619 | isArray = (value) ->
620 | Object::toString.call(value) is '[object Array]'
621 |
622 | isBlank = (value) ->
623 | return true unless value
624 | return false for key of value
625 | true
626 |
627 | makeArray = (args) ->
628 | Array::slice.call(args, 0)
629 |
630 | # Globals
631 |
632 | Spine = @Spine = {}
633 | module?.exports = Spine
634 |
635 | Spine.version = '1.3.1'
636 | Spine.isArray = isArray
637 | Spine.isBlank = isBlank
638 | Spine.$ = $
639 | Spine.Events = Events
640 | Spine.Log = Log
641 | Spine.Module = Module
642 | Spine.Controller = Controller
643 | Spine.Model = Model
644 |
645 | # Global events
646 |
647 | Module.extend.call(Spine, Events)
648 |
649 | # JavaScript compatability
650 |
651 | Module.create = Module.sub =
652 | Controller.create = Controller.sub =
653 | Model.sub = (instances, statics) ->
654 | class Result extends this
655 | Result.include(instances) if instances
656 | Result.extend(statics) if statics
657 | Result.unbind?()
658 | Result
659 |
660 | Model.setup = (name, attributes = []) ->
661 | class Instance extends this
662 | Instance.configure(name, attributes...)
663 | Instance
664 |
665 | Spine.Class = Module
666 |
--------------------------------------------------------------------------------
/spine.js:
--------------------------------------------------------------------------------
1 | // Generated by CoffeeScript 1.12.7
2 |
3 | /*
4 | Spine.js MVC library
5 | Released under the MIT License
6 | */
7 |
8 | (function() {
9 | var $, Controller, Events, Log, Model, Module, Spine, createObject, isArray, isBlank, makeArray, moduleKeywords,
10 | slice = [].slice,
11 | indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
12 | extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
13 | hasProp = {}.hasOwnProperty,
14 | bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
15 |
16 | Events = {
17 | bind: function(ev, callback) {
18 | var base, evs, j, len, name;
19 | evs = ev.split(' ');
20 | if (!(this.hasOwnProperty('_callbacks') && this._callbacks)) {
21 | this._callbacks = {};
22 | }
23 | for (j = 0, len = evs.length; j < len; j++) {
24 | name = evs[j];
25 | (base = this._callbacks)[name] || (base[name] = []);
26 | this._callbacks[name].push(callback);
27 | }
28 | return this;
29 | },
30 | one: function(ev, callback) {
31 | var handler;
32 | return this.bind(ev, handler = function() {
33 | this.unbind(ev, handler);
34 | return callback.apply(this, arguments);
35 | });
36 | },
37 | trigger: function() {
38 | var args, callback, ev, j, len, list, ref;
39 | args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
40 | ev = args.shift();
41 | list = this.hasOwnProperty('_callbacks') && ((ref = this._callbacks) != null ? ref[ev] : void 0);
42 | if (!list) {
43 | return;
44 | }
45 | for (j = 0, len = list.length; j < len; j++) {
46 | callback = list[j];
47 | if (callback.apply(this, args) === false) {
48 | break;
49 | }
50 | }
51 | return true;
52 | },
53 | listenTo: function(obj, ev, callback) {
54 | obj.bind(ev, callback);
55 | this.listeningTo || (this.listeningTo = []);
56 | this.listeningTo.push({
57 | obj: obj,
58 | ev: ev,
59 | callback: callback
60 | });
61 | return this;
62 | },
63 | listenToOnce: function(obj, ev, callback) {
64 | var handler, listeningToOnce;
65 | listeningToOnce = this.listeningToOnce || (this.listeningToOnce = []);
66 | obj.bind(ev, handler = function() {
67 | var i, idx, j, len, lt;
68 | idx = -1;
69 | for (i = j = 0, len = listeningToOnce.length; j < len; i = ++j) {
70 | lt = listeningToOnce[i];
71 | if (lt.obj === obj) {
72 | if (lt.ev === ev && lt.callback === callback) {
73 | idx = i;
74 | }
75 | }
76 | }
77 | obj.unbind(ev, handler);
78 | if (idx !== -1) {
79 | listeningToOnce.splice(idx, 1);
80 | }
81 | return callback.apply(this, arguments);
82 | });
83 | listeningToOnce.push({
84 | obj: obj,
85 | ev: ev,
86 | callback: callback,
87 | handler: handler
88 | });
89 | return this;
90 | },
91 | stopListening: function(obj, events, callback) {
92 | var e, ev, evts, idx, j, k, l, len, len1, len2, listeningTo, lt, ref, ref1, results;
93 | if (arguments.length === 0) {
94 | ref = [this.listeningTo, this.listeningToOnce];
95 | for (j = 0, len = ref.length; j < len; j++) {
96 | listeningTo = ref[j];
97 | if (!listeningTo) {
98 | continue;
99 | }
100 | for (k = 0, len1 = listeningTo.length; k < len1; k++) {
101 | lt = listeningTo[k];
102 | lt.obj.unbind(lt.ev, lt.handler || lt.callback);
103 | }
104 | }
105 | this.listeningTo = void 0;
106 | return this.listeningToOnce = void 0;
107 | } else if (obj) {
108 | ref1 = [this.listeningTo, this.listeningToOnce];
109 | results = [];
110 | for (l = 0, len2 = ref1.length; l < len2; l++) {
111 | listeningTo = ref1[l];
112 | if (!listeningTo) {
113 | continue;
114 | }
115 | events = events ? events.split(' ') : [void 0];
116 | results.push((function() {
117 | var len3, m, results1;
118 | results1 = [];
119 | for (m = 0, len3 = events.length; m < len3; m++) {
120 | ev = events[m];
121 | results1.push((function() {
122 | var n, ref2, results2;
123 | results2 = [];
124 | for (idx = n = ref2 = listeningTo.length - 1; ref2 <= 0 ? n <= 0 : n >= 0; idx = ref2 <= 0 ? ++n : --n) {
125 | lt = listeningTo[idx];
126 | if (callback && (lt.handler || lt.callback) !== callback) {
127 | continue;
128 | }
129 | if ((!ev) || (ev === lt.ev)) {
130 | lt.obj.unbind(lt.ev, lt.handler || lt.callback);
131 | if (idx !== -1) {
132 | results2.push(listeningTo.splice(idx, 1));
133 | } else {
134 | results2.push(void 0);
135 | }
136 | } else if (ev) {
137 | evts = lt.ev.split(' ');
138 | if (indexOf.call(evts, ev) >= 0) {
139 | evts = (function() {
140 | var len4, p, results3;
141 | results3 = [];
142 | for (p = 0, len4 = evts.length; p < len4; p++) {
143 | e = evts[p];
144 | if (e !== ev) {
145 | results3.push(e);
146 | }
147 | }
148 | return results3;
149 | })();
150 | lt.ev = $.trim(evts.join(' '));
151 | results2.push(lt.obj.unbind(ev, lt.handler || lt.callback));
152 | } else {
153 | results2.push(void 0);
154 | }
155 | } else {
156 | results2.push(void 0);
157 | }
158 | }
159 | return results2;
160 | })());
161 | }
162 | return results1;
163 | })());
164 | }
165 | return results;
166 | }
167 | },
168 | unbind: function(ev, callback) {
169 | var cb, evs, i, j, k, len, len1, list, name, ref;
170 | if (arguments.length === 0) {
171 | this._callbacks = {};
172 | return this;
173 | }
174 | if (!ev) {
175 | return this;
176 | }
177 | evs = ev.split(' ');
178 | for (j = 0, len = evs.length; j < len; j++) {
179 | name = evs[j];
180 | list = (ref = this._callbacks) != null ? ref[name] : void 0;
181 | if (!list) {
182 | continue;
183 | }
184 | if (!callback) {
185 | delete this._callbacks[name];
186 | continue;
187 | }
188 | for (i = k = 0, len1 = list.length; k < len1; i = ++k) {
189 | cb = list[i];
190 | if (!(cb === callback)) {
191 | continue;
192 | }
193 | list = list.slice();
194 | list.splice(i, 1);
195 | this._callbacks[name] = list;
196 | break;
197 | }
198 | }
199 | return this;
200 | }
201 | };
202 |
203 | Events.on = Events.bind;
204 |
205 | Events.off = Events.unbind;
206 |
207 | Log = {
208 | trace: true,
209 | logPrefix: '(App)',
210 | log: function() {
211 | var args;
212 | args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
213 | if (!this.trace) {
214 | return;
215 | }
216 | if (this.logPrefix) {
217 | args.unshift(this.logPrefix);
218 | }
219 | if (typeof console !== "undefined" && console !== null) {
220 | if (typeof console.log === "function") {
221 | console.log.apply(console, args);
222 | }
223 | }
224 | return this;
225 | }
226 | };
227 |
228 | moduleKeywords = ['included', 'extended'];
229 |
230 | Module = (function() {
231 | Module.include = function(obj) {
232 | var key, ref, value;
233 | if (!obj) {
234 | throw new Error('include(obj) requires obj');
235 | }
236 | for (key in obj) {
237 | value = obj[key];
238 | if (indexOf.call(moduleKeywords, key) < 0) {
239 | this.prototype[key] = value;
240 | }
241 | }
242 | if ((ref = obj.included) != null) {
243 | ref.apply(this);
244 | }
245 | return this;
246 | };
247 |
248 | Module.extend = function(obj) {
249 | var key, ref, value;
250 | if (!obj) {
251 | throw new Error('extend(obj) requires obj');
252 | }
253 | for (key in obj) {
254 | value = obj[key];
255 | if (indexOf.call(moduleKeywords, key) < 0) {
256 | this[key] = value;
257 | }
258 | }
259 | if ((ref = obj.extended) != null) {
260 | ref.apply(this);
261 | }
262 | return this;
263 | };
264 |
265 | Module.proxy = function(func) {
266 | return (function(_this) {
267 | return function() {
268 | return func.apply(_this, arguments);
269 | };
270 | })(this);
271 | };
272 |
273 | Module.prototype.proxy = function(func) {
274 | return (function(_this) {
275 | return function() {
276 | return func.apply(_this, arguments);
277 | };
278 | })(this);
279 | };
280 |
281 | function Module() {
282 | if (typeof this.init === "function") {
283 | this.init.apply(this, arguments);
284 | }
285 | }
286 |
287 | return Module;
288 |
289 | })();
290 |
291 | Model = (function(superClass) {
292 | extend(Model, superClass);
293 |
294 | Model.extend(Events);
295 |
296 | Model.records = [];
297 |
298 | Model.irecords = {};
299 |
300 | Model.attributes = [];
301 |
302 | Model.configure = function() {
303 | var attributes, name;
304 | name = arguments[0], attributes = 2 <= arguments.length ? slice.call(arguments, 1) : [];
305 | this.className = name;
306 | this.deleteAll();
307 | if (attributes.length) {
308 | this.attributes = attributes;
309 | }
310 | this.attributes && (this.attributes = makeArray(this.attributes));
311 | this.attributes || (this.attributes = []);
312 | this.unbind();
313 | return this;
314 | };
315 |
316 | Model.toString = function() {
317 | return this.className + "(" + (this.attributes.join(", ")) + ")";
318 | };
319 |
320 | Model.find = function(id, notFound) {
321 | var ref;
322 | if (notFound == null) {
323 | notFound = this.notFound;
324 | }
325 | return ((ref = this.irecords[id]) != null ? ref.clone() : void 0) || (typeof notFound === "function" ? notFound(id) : void 0);
326 | };
327 |
328 | Model.notFound = function(id) {
329 | return null;
330 | };
331 |
332 | Model.exists = function(id) {
333 | return Boolean(this.irecords[id]);
334 | };
335 |
336 | Model.addRecord = function(record, options) {
337 | var base, base1, name1, name2;
338 | if (options == null) {
339 | options = {};
340 | }
341 | if (record.id && this.irecords[record.id]) {
342 | this.irecords[record.id].remove(options);
343 | if (!options.clear) {
344 | record = this.irecords[record.id].load(record);
345 | }
346 | }
347 | record.id || (record.id = record.cid);
348 | if ((base = this.irecords)[name1 = record.id] == null) {
349 | base[name1] = record;
350 | }
351 | if ((base1 = this.irecords)[name2 = record.cid] == null) {
352 | base1[name2] = record;
353 | }
354 | return this.records.push(record);
355 | };
356 |
357 | Model.refresh = function(values, options) {
358 | var j, len, record, records, result;
359 | if (options == null) {
360 | options = {};
361 | }
362 | if (options.clear) {
363 | this.deleteAll();
364 | }
365 | records = this.fromJSON(values);
366 | if (!isArray(records)) {
367 | records = [records];
368 | }
369 | for (j = 0, len = records.length; j < len; j++) {
370 | record = records[j];
371 | this.addRecord(record, options);
372 | }
373 | this.sort();
374 | result = this.cloneArray(records);
375 | this.trigger('refresh', result, options);
376 | return result;
377 | };
378 |
379 | Model.select = function(callback) {
380 | var j, len, record, ref, results;
381 | ref = this.records;
382 | results = [];
383 | for (j = 0, len = ref.length; j < len; j++) {
384 | record = ref[j];
385 | if (callback(record)) {
386 | results.push(record.clone());
387 | }
388 | }
389 | return results;
390 | };
391 |
392 | Model.findByAttribute = function(name, value) {
393 | var j, len, record, ref;
394 | ref = this.records;
395 | for (j = 0, len = ref.length; j < len; j++) {
396 | record = ref[j];
397 | if (record[name] === value) {
398 | return record.clone();
399 | }
400 | }
401 | return null;
402 | };
403 |
404 | Model.findAllByAttribute = function(name, value) {
405 | return this.select(function(item) {
406 | return item[name] === value;
407 | });
408 | };
409 |
410 | Model.each = function(callback) {
411 | var j, len, record, ref, results;
412 | ref = this.records;
413 | results = [];
414 | for (j = 0, len = ref.length; j < len; j++) {
415 | record = ref[j];
416 | results.push(callback(record.clone()));
417 | }
418 | return results;
419 | };
420 |
421 | Model.all = function() {
422 | return this.cloneArray(this.records);
423 | };
424 |
425 | Model.slice = function(begin, end) {
426 | if (begin == null) {
427 | begin = 0;
428 | }
429 | return this.cloneArray(this.records.slice(begin, end));
430 | };
431 |
432 | Model.first = function(end) {
433 | var ref;
434 | if (end == null) {
435 | end = 1;
436 | }
437 | if (end > 1) {
438 | return this.cloneArray(this.records.slice(0, end));
439 | } else {
440 | return (ref = this.records[0]) != null ? ref.clone() : void 0;
441 | }
442 | };
443 |
444 | Model.last = function(begin) {
445 | var ref;
446 | if (typeof begin === 'number') {
447 | return this.cloneArray(this.records.slice(-begin));
448 | } else {
449 | return (ref = this.records[this.records.length - 1]) != null ? ref.clone() : void 0;
450 | }
451 | };
452 |
453 | Model.count = function() {
454 | return this.records.length;
455 | };
456 |
457 | Model.deleteAll = function() {
458 | this.records = [];
459 | return this.irecords = {};
460 | };
461 |
462 | Model.destroyAll = function(options) {
463 | var j, len, record, ref, results;
464 | ref = this.records;
465 | results = [];
466 | for (j = 0, len = ref.length; j < len; j++) {
467 | record = ref[j];
468 | results.push(record.destroy(options));
469 | }
470 | return results;
471 | };
472 |
473 | Model.update = function(id, atts, options) {
474 | return this.find(id).updateAttributes(atts, options);
475 | };
476 |
477 | Model.create = function(atts, options) {
478 | var record;
479 | record = new this(atts);
480 | return record.save(options);
481 | };
482 |
483 | Model.destroy = function(id, options) {
484 | return this.find(id).destroy(options);
485 | };
486 |
487 | Model.change = function(callbackOrParams) {
488 | if (typeof callbackOrParams === 'function') {
489 | return this.bind('change', callbackOrParams);
490 | } else {
491 | return this.trigger.apply(this, ['change'].concat(slice.call(arguments)));
492 | }
493 | };
494 |
495 | Model.fetch = function(callbackOrParams) {
496 | if (typeof callbackOrParams === 'function') {
497 | return this.bind('fetch', callbackOrParams);
498 | } else {
499 | return this.trigger.apply(this, ['fetch'].concat(slice.call(arguments)));
500 | }
501 | };
502 |
503 | Model.toJSON = function() {
504 | return this.records;
505 | };
506 |
507 | Model.fromJSON = function(objects) {
508 | var j, len, results, value;
509 | if (!objects) {
510 | return;
511 | }
512 | if (typeof objects === 'string') {
513 | objects = JSON.parse(objects);
514 | }
515 | if (isArray(objects)) {
516 | results = [];
517 | for (j = 0, len = objects.length; j < len; j++) {
518 | value = objects[j];
519 | if (value instanceof this) {
520 | results.push(value);
521 | } else {
522 | results.push(new this(value));
523 | }
524 | }
525 | return results;
526 | } else {
527 | if (objects instanceof this) {
528 | return objects;
529 | }
530 | return new this(objects);
531 | }
532 | };
533 |
534 | Model.fromForm = function() {
535 | var ref;
536 | return (ref = new this).fromForm.apply(ref, arguments);
537 | };
538 |
539 | Model.sort = function() {
540 | if (this.comparator) {
541 | this.records.sort(this.comparator);
542 | }
543 | return this;
544 | };
545 |
546 | Model.cloneArray = function(array) {
547 | var j, len, results, value;
548 | results = [];
549 | for (j = 0, len = array.length; j < len; j++) {
550 | value = array[j];
551 | results.push(value.clone());
552 | }
553 | return results;
554 | };
555 |
556 | Model.idCounter = 0;
557 |
558 | Model.uid = function(prefix) {
559 | var uid;
560 | if (prefix == null) {
561 | prefix = '';
562 | }
563 | uid = prefix + this.idCounter++;
564 | if (this.exists(uid)) {
565 | uid = this.uid(prefix);
566 | }
567 | return uid;
568 | };
569 |
570 | function Model(atts) {
571 | Model.__super__.constructor.apply(this, arguments);
572 | if ((this.constructor.uuid != null) && typeof this.constructor.uuid === 'function') {
573 | this.cid = this.constructor.uuid();
574 | if (!this.id) {
575 | this.id = this.cid;
576 | }
577 | } else {
578 | this.cid = (atts != null ? atts.cid : void 0) || this.constructor.uid('c-');
579 | }
580 | if (atts) {
581 | this.load(atts);
582 | }
583 | }
584 |
585 | Model.prototype.isNew = function() {
586 | return !this.exists();
587 | };
588 |
589 | Model.prototype.isValid = function() {
590 | return !this.validate();
591 | };
592 |
593 | Model.prototype.validate = function() {};
594 |
595 | Model.prototype.load = function(atts) {
596 | var key, value;
597 | if (atts.id) {
598 | this.id = atts.id;
599 | }
600 | for (key in atts) {
601 | value = atts[key];
602 | if (typeof this[key] === 'function') {
603 | if (typeof value === 'function') {
604 | continue;
605 | }
606 | this[key](value);
607 | } else {
608 | this[key] = value;
609 | }
610 | }
611 | return this;
612 | };
613 |
614 | Model.prototype.attributes = function() {
615 | var j, key, len, ref, result;
616 | result = {};
617 | ref = this.constructor.attributes;
618 | for (j = 0, len = ref.length; j < len; j++) {
619 | key = ref[j];
620 | if (key in this) {
621 | if (typeof this[key] === 'function') {
622 | result[key] = this[key]();
623 | } else {
624 | result[key] = this[key];
625 | }
626 | }
627 | }
628 | if (this.id) {
629 | result.id = this.id;
630 | }
631 | return result;
632 | };
633 |
634 | Model.prototype.eql = function(rec) {
635 | return rec && rec.constructor === this.constructor && ((rec.cid === this.cid) || (rec.id && rec.id === this.id));
636 | };
637 |
638 | Model.prototype.save = function(options) {
639 | var error, record;
640 | if (options == null) {
641 | options = {};
642 | }
643 | if (options.validate !== false) {
644 | error = this.validate();
645 | if (error) {
646 | this.trigger('error', error);
647 | return false;
648 | }
649 | }
650 | this.trigger('beforeSave', options);
651 | record = this.isNew() ? this.create(options) : this.update(options);
652 | this.stripCloneAttrs();
653 | this.trigger('save', options);
654 | return record;
655 | };
656 |
657 | Model.prototype.stripCloneAttrs = function() {
658 | var key, ref, value;
659 | if (this.hasOwnProperty('cid')) {
660 | return;
661 | }
662 | ref = this;
663 | for (key in ref) {
664 | if (!hasProp.call(ref, key)) continue;
665 | value = ref[key];
666 | if (indexOf.call(this.constructor.attributes, key) >= 0) {
667 | delete this[key];
668 | }
669 | }
670 | return this;
671 | };
672 |
673 | Model.prototype.updateAttribute = function(name, value, options) {
674 | var atts;
675 | atts = {};
676 | atts[name] = value;
677 | return this.updateAttributes(atts, options);
678 | };
679 |
680 | Model.prototype.updateAttributes = function(atts, options) {
681 | this.load(atts);
682 | return this.save(options);
683 | };
684 |
685 | Model.prototype.changeID = function(id) {
686 | var records;
687 | if (id === this.id) {
688 | return;
689 | }
690 | records = this.constructor.irecords;
691 | records[id] = records[this.id];
692 | if (this.cid !== this.id) {
693 | delete records[this.id];
694 | }
695 | this.id = id;
696 | return this.save();
697 | };
698 |
699 | Model.prototype.remove = function(options) {
700 | var i, j, len, record, records;
701 | if (options == null) {
702 | options = {};
703 | }
704 | records = this.constructor.records.slice(0);
705 | for (i = j = 0, len = records.length; j < len; i = ++j) {
706 | record = records[i];
707 | if (!(this.eql(record))) {
708 | continue;
709 | }
710 | records.splice(i, 1);
711 | break;
712 | }
713 | this.constructor.records = records;
714 | if (options.clear) {
715 | delete this.constructor.irecords[this.id];
716 | return delete this.constructor.irecords[this.cid];
717 | }
718 | };
719 |
720 | Model.prototype.destroy = function(options) {
721 | if (options == null) {
722 | options = {};
723 | }
724 | if (options.clear == null) {
725 | options.clear = true;
726 | }
727 | this.trigger('beforeDestroy', options);
728 | this.remove(options);
729 | this.destroyed = true;
730 | this.trigger('destroy', options);
731 | this.trigger('change', 'destroy', options);
732 | if (this.listeningTo) {
733 | this.stopListening();
734 | }
735 | this.unbind();
736 | return this;
737 | };
738 |
739 | Model.prototype.dup = function(newRecord) {
740 | var atts;
741 | if (newRecord == null) {
742 | newRecord = true;
743 | }
744 | atts = this.attributes();
745 | if (newRecord) {
746 | delete atts.id;
747 | } else {
748 | atts.cid = this.cid;
749 | }
750 | return new this.constructor(atts);
751 | };
752 |
753 | Model.prototype.clone = function() {
754 | return createObject(this);
755 | };
756 |
757 | Model.prototype.reload = function() {
758 | var original;
759 | if (this.isNew()) {
760 | return this;
761 | }
762 | original = this.constructor.find(this.id);
763 | this.load(original.attributes());
764 | return original;
765 | };
766 |
767 | Model.prototype.refresh = function(data) {
768 | var root;
769 | root = this.constructor.irecords[this.id];
770 | root.load(data);
771 | this.trigger('refresh');
772 | return this;
773 | };
774 |
775 | Model.prototype.toJSON = function() {
776 | return this.attributes();
777 | };
778 |
779 | Model.prototype.toString = function() {
780 | return "<" + this.constructor.className + " (" + (JSON.stringify(this)) + ")>";
781 | };
782 |
783 | Model.prototype.fromForm = function(form) {
784 | var checkbox, j, k, key, l, len, len1, len2, name, name1, ref, ref1, ref2, result;
785 | result = {};
786 | ref = $(form).find('[type=checkbox]:not([value])');
787 | for (j = 0, len = ref.length; j < len; j++) {
788 | checkbox = ref[j];
789 | result[checkbox.name] = $(checkbox).prop('checked');
790 | }
791 | ref1 = $(form).find('[type=checkbox][name$="[]"]');
792 | for (k = 0, len1 = ref1.length; k < len1; k++) {
793 | checkbox = ref1[k];
794 | name = checkbox.name.replace(/\[\]$/, '');
795 | result[name] || (result[name] = []);
796 | if ($(checkbox).prop('checked')) {
797 | result[name].push(checkbox.value);
798 | }
799 | }
800 | ref2 = $(form).serializeArray();
801 | for (l = 0, len2 = ref2.length; l < len2; l++) {
802 | key = ref2[l];
803 | result[name1 = key.name] || (result[name1] = key.value);
804 | }
805 | return this.load(result);
806 | };
807 |
808 | Model.prototype.exists = function() {
809 | return this.constructor.exists(this.id);
810 | };
811 |
812 | Model.prototype.update = function(options) {
813 | var clone, records;
814 | this.trigger('beforeUpdate', options);
815 | records = this.constructor.irecords;
816 | records[this.id].load(this.attributes());
817 | this.constructor.sort();
818 | clone = records[this.id].clone();
819 | clone.trigger('update', options);
820 | clone.trigger('change', 'update', options);
821 | return clone;
822 | };
823 |
824 | Model.prototype.create = function(options) {
825 | var clone, record;
826 | this.trigger('beforeCreate', options);
827 | this.id || (this.id = this.cid);
828 | record = this.dup(false);
829 | this.constructor.addRecord(record);
830 | this.constructor.sort();
831 | clone = record.clone();
832 | clone.trigger('create', options);
833 | clone.trigger('change', 'create', options);
834 | return clone;
835 | };
836 |
837 | Model.prototype.bind = function(events, callback) {
838 | var binder, fn, j, len, ref, singleEvent;
839 | this.constructor.bind(events, binder = (function(_this) {
840 | return function(record) {
841 | if (record && _this.eql(record)) {
842 | return callback.apply(_this, arguments);
843 | }
844 | };
845 | })(this));
846 | ref = events.split(' ');
847 | fn = (function(_this) {
848 | return function(singleEvent) {
849 | var unbinder;
850 | return _this.constructor.bind("unbind", unbinder = function(record, event, cb) {
851 | if (record && _this.eql(record)) {
852 | if (event && event !== singleEvent) {
853 | return;
854 | }
855 | if (cb && cb !== callback) {
856 | return;
857 | }
858 | _this.constructor.unbind(singleEvent, binder);
859 | return _this.constructor.unbind("unbind", unbinder);
860 | }
861 | });
862 | };
863 | })(this);
864 | for (j = 0, len = ref.length; j < len; j++) {
865 | singleEvent = ref[j];
866 | fn(singleEvent);
867 | }
868 | return this;
869 | };
870 |
871 | Model.prototype.one = function(events, callback) {
872 | var handler;
873 | return this.bind(events, handler = (function(_this) {
874 | return function() {
875 | _this.unbind(events, handler);
876 | return callback.apply(_this, arguments);
877 | };
878 | })(this));
879 | };
880 |
881 | Model.prototype.trigger = function() {
882 | var args, ref;
883 | args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
884 | args.splice(1, 0, this);
885 | return (ref = this.constructor).trigger.apply(ref, args);
886 | };
887 |
888 | Model.prototype.listenTo = function() {
889 | return Events.listenTo.apply(this, arguments);
890 | };
891 |
892 | Model.prototype.listenToOnce = function() {
893 | return Events.listenToOnce.apply(this, arguments);
894 | };
895 |
896 | Model.prototype.stopListening = function() {
897 | return Events.stopListening.apply(this, arguments);
898 | };
899 |
900 | Model.prototype.unbind = function(events, callback) {
901 | var event, j, len, ref, results;
902 | if (arguments.length === 0) {
903 | return this.trigger('unbind');
904 | } else if (events) {
905 | ref = events.split(' ');
906 | results = [];
907 | for (j = 0, len = ref.length; j < len; j++) {
908 | event = ref[j];
909 | results.push(this.trigger('unbind', event, callback));
910 | }
911 | return results;
912 | }
913 | };
914 |
915 | return Model;
916 |
917 | })(Module);
918 |
919 | Model.prototype.on = Model.prototype.bind;
920 |
921 | Model.prototype.off = Model.prototype.unbind;
922 |
923 | Controller = (function(superClass) {
924 | extend(Controller, superClass);
925 |
926 | Controller.include(Events);
927 |
928 | Controller.include(Log);
929 |
930 | Controller.prototype.eventSplitter = /^(\S+)\s*(.*)$/;
931 |
932 | Controller.prototype.tag = 'div';
933 |
934 | function Controller(options) {
935 | this.release = bind(this.release, this);
936 | var context, key, parent_prototype, ref, value;
937 | this.options = options;
938 | ref = this.options;
939 | for (key in ref) {
940 | value = ref[key];
941 | this[key] = value;
942 | }
943 | if (!this.el) {
944 | this.el = document.createElement(this.tag);
945 | }
946 | this.el = $(this.el);
947 | this.$el = this.el;
948 | if (this.className) {
949 | this.el.addClass(this.className);
950 | }
951 | if (this.attributes) {
952 | this.el.attr(this.attributes);
953 | }
954 | if (!this.events) {
955 | this.events = this.constructor.events;
956 | }
957 | if (!this.elements) {
958 | this.elements = this.constructor.elements;
959 | }
960 | context = this;
961 | while (parent_prototype = context.constructor.__super__) {
962 | if (parent_prototype.events) {
963 | this.events = $.extend({}, parent_prototype.events, this.events);
964 | }
965 | if (parent_prototype.elements) {
966 | this.elements = $.extend({}, parent_prototype.elements, this.elements);
967 | }
968 | context = parent_prototype;
969 | }
970 | if (this.events) {
971 | this.delegateEvents(this.events);
972 | }
973 | if (this.elements) {
974 | this.refreshElements();
975 | }
976 | Controller.__super__.constructor.apply(this, arguments);
977 | }
978 |
979 | Controller.prototype.release = function() {
980 | this.trigger('release', this);
981 | this.el.remove();
982 | this.unbind();
983 | return this.stopListening();
984 | };
985 |
986 | Controller.prototype.$ = function(selector) {
987 | return $(selector, this.el);
988 | };
989 |
990 | Controller.prototype.delegateEvents = function(events) {
991 | var eventName, key, match, method, results, selector;
992 | results = [];
993 | for (key in events) {
994 | method = events[key];
995 | if (typeof method === 'function') {
996 | method = (function(_this) {
997 | return function(method) {
998 | return function() {
999 | method.apply(_this, arguments);
1000 | return true;
1001 | };
1002 | };
1003 | })(this)(method);
1004 | } else {
1005 | if (!this[method]) {
1006 | throw new Error(method + " doesn't exist");
1007 | }
1008 | method = (function(_this) {
1009 | return function(method) {
1010 | return function() {
1011 | _this[method].apply(_this, arguments);
1012 | return true;
1013 | };
1014 | };
1015 | })(this)(method);
1016 | }
1017 | match = key.match(this.eventSplitter);
1018 | eventName = match[1];
1019 | selector = match[2];
1020 | if (selector === '') {
1021 | results.push(this.el.bind(eventName, method));
1022 | } else {
1023 | results.push(this.el.on(eventName, selector, method));
1024 | }
1025 | }
1026 | return results;
1027 | };
1028 |
1029 | Controller.prototype.refreshElements = function() {
1030 | var key, ref, results, value;
1031 | ref = this.elements;
1032 | results = [];
1033 | for (key in ref) {
1034 | value = ref[key];
1035 | results.push(this[value] = this.$(key));
1036 | }
1037 | return results;
1038 | };
1039 |
1040 | Controller.prototype.delay = function(func, timeout) {
1041 | return setTimeout(this.proxy(func), timeout || 0);
1042 | };
1043 |
1044 | Controller.prototype.html = function(element) {
1045 | this.el.html(element.el || element);
1046 | this.refreshElements();
1047 | return this.el;
1048 | };
1049 |
1050 | Controller.prototype.append = function() {
1051 | var e, elements, ref;
1052 | elements = 1 <= arguments.length ? slice.call(arguments, 0) : [];
1053 | elements = (function() {
1054 | var j, len, results;
1055 | results = [];
1056 | for (j = 0, len = elements.length; j < len; j++) {
1057 | e = elements[j];
1058 | results.push(e.el || e);
1059 | }
1060 | return results;
1061 | })();
1062 | (ref = this.el).append.apply(ref, elements);
1063 | this.refreshElements();
1064 | return this.el;
1065 | };
1066 |
1067 | Controller.prototype.appendTo = function(element) {
1068 | this.el.appendTo(element.el || element);
1069 | this.refreshElements();
1070 | return this.el;
1071 | };
1072 |
1073 | Controller.prototype.prepend = function() {
1074 | var e, elements, ref;
1075 | elements = 1 <= arguments.length ? slice.call(arguments, 0) : [];
1076 | elements = (function() {
1077 | var j, len, results;
1078 | results = [];
1079 | for (j = 0, len = elements.length; j < len; j++) {
1080 | e = elements[j];
1081 | results.push(e.el || e);
1082 | }
1083 | return results;
1084 | })();
1085 | (ref = this.el).prepend.apply(ref, elements);
1086 | this.refreshElements();
1087 | return this.el;
1088 | };
1089 |
1090 | Controller.prototype.replace = function(element) {
1091 | var previous, ref, ref1;
1092 | element = element.el || element;
1093 | if (typeof element === "string") {
1094 | element = $.trim(element);
1095 | }
1096 | ref1 = [this.el, $(((ref = $.parseHTML(element)) != null ? ref[0] : void 0) || element)], previous = ref1[0], this.el = ref1[1];
1097 | previous.replaceWith(this.el);
1098 | this.delegateEvents(this.events);
1099 | this.refreshElements();
1100 | return this.el;
1101 | };
1102 |
1103 | return Controller;
1104 |
1105 | })(Module);
1106 |
1107 | $ = (typeof window !== "undefined" && window !== null ? window.jQuery : void 0) || (typeof window !== "undefined" && window !== null ? window.Zepto : void 0) || function(element) {
1108 | return element;
1109 | };
1110 |
1111 | createObject = Object.create || function(o) {
1112 | var Func;
1113 | Func = function() {};
1114 | Func.prototype = o;
1115 | return new Func();
1116 | };
1117 |
1118 | isArray = function(value) {
1119 | return Object.prototype.toString.call(value) === '[object Array]';
1120 | };
1121 |
1122 | isBlank = function(value) {
1123 | var key;
1124 | if (!value) {
1125 | return true;
1126 | }
1127 | for (key in value) {
1128 | return false;
1129 | }
1130 | return true;
1131 | };
1132 |
1133 | makeArray = function(args) {
1134 | return Array.prototype.slice.call(args, 0);
1135 | };
1136 |
1137 | Spine = this.Spine = {};
1138 |
1139 | if (typeof module !== "undefined" && module !== null) {
1140 | module.exports = Spine;
1141 | }
1142 |
1143 | Spine.version = '1.3.1';
1144 |
1145 | Spine.isArray = isArray;
1146 |
1147 | Spine.isBlank = isBlank;
1148 |
1149 | Spine.$ = $;
1150 |
1151 | Spine.Events = Events;
1152 |
1153 | Spine.Log = Log;
1154 |
1155 | Spine.Module = Module;
1156 |
1157 | Spine.Controller = Controller;
1158 |
1159 | Spine.Model = Model;
1160 |
1161 | Module.extend.call(Spine, Events);
1162 |
1163 | Module.create = Module.sub = Controller.create = Controller.sub = Model.sub = function(instances, statics) {
1164 | var Result;
1165 | Result = (function(superClass) {
1166 | extend(Result, superClass);
1167 |
1168 | function Result() {
1169 | return Result.__super__.constructor.apply(this, arguments);
1170 | }
1171 |
1172 | return Result;
1173 |
1174 | })(this);
1175 | if (instances) {
1176 | Result.include(instances);
1177 | }
1178 | if (statics) {
1179 | Result.extend(statics);
1180 | }
1181 | if (typeof Result.unbind === "function") {
1182 | Result.unbind();
1183 | }
1184 | return Result;
1185 | };
1186 |
1187 | Model.setup = function(name, attributes) {
1188 | var Instance;
1189 | if (attributes == null) {
1190 | attributes = [];
1191 | }
1192 | Instance = (function(superClass) {
1193 | extend(Instance, superClass);
1194 |
1195 | function Instance() {
1196 | return Instance.__super__.constructor.apply(this, arguments);
1197 | }
1198 |
1199 | return Instance;
1200 |
1201 | })(this);
1202 | Instance.configure.apply(Instance, [name].concat(slice.call(attributes)));
1203 | return Instance;
1204 | };
1205 |
1206 | Spine.Class = Module;
1207 |
1208 | }).call(this);
1209 |
--------------------------------------------------------------------------------
/spec/lib/jasmine.js:
--------------------------------------------------------------------------------
1 | var isCommonJS = typeof window == "undefined";
2 |
3 | /**
4 | * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework.
5 | *
6 | * @namespace
7 | */
8 | var jasmine = {};
9 | if (isCommonJS) exports.jasmine = jasmine;
10 | /**
11 | * @private
12 | */
13 | jasmine.unimplementedMethod_ = function() {
14 | throw new Error("unimplemented method");
15 | };
16 |
17 | /**
18 | * Use jasmine.undefined instead of undefined, since undefined is just
19 | * a plain old variable and may be redefined by somebody else.
20 | *
21 | * @private
22 | */
23 | jasmine.undefined = jasmine.___undefined___;
24 |
25 | /**
26 | * Show diagnostic messages in the console if set to true
27 | *
28 | */
29 | jasmine.VERBOSE = false;
30 |
31 | /**
32 | * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed.
33 | *
34 | */
35 | jasmine.DEFAULT_UPDATE_INTERVAL = 250;
36 |
37 | /**
38 | * Default timeout interval in milliseconds for waitsFor() blocks.
39 | */
40 | jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;
41 |
42 | jasmine.getGlobal = function() {
43 | function getGlobal() {
44 | return this;
45 | }
46 |
47 | return getGlobal();
48 | };
49 |
50 | /**
51 | * Allows for bound functions to be compared. Internal use only.
52 | *
53 | * @ignore
54 | * @private
55 | * @param base {Object} bound 'this' for the function
56 | * @param name {Function} function to find
57 | */
58 | jasmine.bindOriginal_ = function(base, name) {
59 | var original = base[name];
60 | if (original.apply) {
61 | return function() {
62 | return original.apply(base, arguments);
63 | };
64 | } else {
65 | // IE support
66 | return jasmine.getGlobal()[name];
67 | }
68 | };
69 |
70 | jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout');
71 | jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout');
72 | jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval');
73 | jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval');
74 |
75 | jasmine.MessageResult = function(values) {
76 | this.type = 'log';
77 | this.values = values;
78 | this.trace = new Error(); // todo: test better
79 | };
80 |
81 | jasmine.MessageResult.prototype.toString = function() {
82 | var text = "";
83 | for (var i = 0; i < this.values.length; i++) {
84 | if (i > 0) text += " ";
85 | if (jasmine.isString_(this.values[i])) {
86 | text += this.values[i];
87 | } else {
88 | text += jasmine.pp(this.values[i]);
89 | }
90 | }
91 | return text;
92 | };
93 |
94 | jasmine.ExpectationResult = function(params) {
95 | this.type = 'expect';
96 | this.matcherName = params.matcherName;
97 | this.passed_ = params.passed;
98 | this.expected = params.expected;
99 | this.actual = params.actual;
100 | this.message = this.passed_ ? 'Passed.' : params.message;
101 |
102 | var trace = (params.trace || new Error(this.message));
103 | this.trace = this.passed_ ? '' : trace;
104 | };
105 |
106 | jasmine.ExpectationResult.prototype.toString = function () {
107 | return this.message;
108 | };
109 |
110 | jasmine.ExpectationResult.prototype.passed = function () {
111 | return this.passed_;
112 | };
113 |
114 | /**
115 | * Getter for the Jasmine environment. Ensures one gets created
116 | */
117 | jasmine.getEnv = function() {
118 | var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env();
119 | return env;
120 | };
121 |
122 | /**
123 | * @ignore
124 | * @private
125 | * @param value
126 | * @returns {Boolean}
127 | */
128 | jasmine.isArray_ = function(value) {
129 | return jasmine.isA_("Array", value);
130 | };
131 |
132 | /**
133 | * @ignore
134 | * @private
135 | * @param value
136 | * @returns {Boolean}
137 | */
138 | jasmine.isString_ = function(value) {
139 | return jasmine.isA_("String", value);
140 | };
141 |
142 | /**
143 | * @ignore
144 | * @private
145 | * @param value
146 | * @returns {Boolean}
147 | */
148 | jasmine.isNumber_ = function(value) {
149 | return jasmine.isA_("Number", value);
150 | };
151 |
152 | /**
153 | * @ignore
154 | * @private
155 | * @param {String} typeName
156 | * @param value
157 | * @returns {Boolean}
158 | */
159 | jasmine.isA_ = function(typeName, value) {
160 | return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
161 | };
162 |
163 | /**
164 | * Pretty printer for expecations. Takes any object and turns it into a human-readable string.
165 | *
166 | * @param value {Object} an object to be outputted
167 | * @returns {String}
168 | */
169 | jasmine.pp = function(value) {
170 | var stringPrettyPrinter = new jasmine.StringPrettyPrinter();
171 | stringPrettyPrinter.format(value);
172 | return stringPrettyPrinter.string;
173 | };
174 |
175 | /**
176 | * Returns true if the object is a DOM Node.
177 | *
178 | * @param {Object} obj object to check
179 | * @returns {Boolean}
180 | */
181 | jasmine.isDomNode = function(obj) {
182 | return obj.nodeType > 0;
183 | };
184 |
185 | /**
186 | * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter.
187 | *
188 | * @example
189 | * // don't care about which function is passed in, as long as it's a function
190 | * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function));
191 | *
192 | * @param {Class} clazz
193 | * @returns matchable object of the type clazz
194 | */
195 | jasmine.any = function(clazz) {
196 | return new jasmine.Matchers.Any(clazz);
197 | };
198 |
199 | /**
200 | * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks.
201 | *
202 | * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine
203 | * expectation syntax. Spies can be checked if they were called or not and what the calling params were.
204 | *
205 | * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs).
206 | *
207 | * Spies are torn down at the end of every spec.
208 | *
209 | * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj.
210 | *
211 | * @example
212 | * // a stub
213 | * var myStub = jasmine.createSpy('myStub'); // can be used anywhere
214 | *
215 | * // spy example
216 | * var foo = {
217 | * not: function(bool) { return !bool; }
218 | * }
219 | *
220 | * // actual foo.not will not be called, execution stops
221 | * spyOn(foo, 'not');
222 |
223 | // foo.not spied upon, execution will continue to implementation
224 | * spyOn(foo, 'not').andCallThrough();
225 | *
226 | * // fake example
227 | * var foo = {
228 | * not: function(bool) { return !bool; }
229 | * }
230 | *
231 | * // foo.not(val) will return val
232 | * spyOn(foo, 'not').andCallFake(function(value) {return value;});
233 | *
234 | * // mock example
235 | * foo.not(7 == 7);
236 | * expect(foo.not).toHaveBeenCalled();
237 | * expect(foo.not).toHaveBeenCalledWith(true);
238 | *
239 | * @constructor
240 | * @see spyOn, jasmine.createSpy, jasmine.createSpyObj
241 | * @param {String} name
242 | */
243 | jasmine.Spy = function(name) {
244 | /**
245 | * The name of the spy, if provided.
246 | */
247 | this.identity = name || 'unknown';
248 | /**
249 | * Is this Object a spy?
250 | */
251 | this.isSpy = true;
252 | /**
253 | * The actual function this spy stubs.
254 | */
255 | this.plan = function() {
256 | };
257 | /**
258 | * Tracking of the most recent call to the spy.
259 | * @example
260 | * var mySpy = jasmine.createSpy('foo');
261 | * mySpy(1, 2);
262 | * mySpy.mostRecentCall.args = [1, 2];
263 | */
264 | this.mostRecentCall = {};
265 |
266 | /**
267 | * Holds arguments for each call to the spy, indexed by call count
268 | * @example
269 | * var mySpy = jasmine.createSpy('foo');
270 | * mySpy(1, 2);
271 | * mySpy(7, 8);
272 | * mySpy.mostRecentCall.args = [7, 8];
273 | * mySpy.argsForCall[0] = [1, 2];
274 | * mySpy.argsForCall[1] = [7, 8];
275 | */
276 | this.argsForCall = [];
277 | this.calls = [];
278 | };
279 |
280 | /**
281 | * Tells a spy to call through to the actual implemenatation.
282 | *
283 | * @example
284 | * var foo = {
285 | * bar: function() { // do some stuff }
286 | * }
287 | *
288 | * // defining a spy on an existing property: foo.bar
289 | * spyOn(foo, 'bar').andCallThrough();
290 | */
291 | jasmine.Spy.prototype.andCallThrough = function() {
292 | this.plan = this.originalValue;
293 | return this;
294 | };
295 |
296 | /**
297 | * For setting the return value of a spy.
298 | *
299 | * @example
300 | * // defining a spy from scratch: foo() returns 'baz'
301 | * var foo = jasmine.createSpy('spy on foo').andReturn('baz');
302 | *
303 | * // defining a spy on an existing property: foo.bar() returns 'baz'
304 | * spyOn(foo, 'bar').andReturn('baz');
305 | *
306 | * @param {Object} value
307 | */
308 | jasmine.Spy.prototype.andReturn = function(value) {
309 | this.plan = function() {
310 | return value;
311 | };
312 | return this;
313 | };
314 |
315 | /**
316 | * For throwing an exception when a spy is called.
317 | *
318 | * @example
319 | * // defining a spy from scratch: foo() throws an exception w/ message 'ouch'
320 | * var foo = jasmine.createSpy('spy on foo').andThrow('baz');
321 | *
322 | * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch'
323 | * spyOn(foo, 'bar').andThrow('baz');
324 | *
325 | * @param {String} exceptionMsg
326 | */
327 | jasmine.Spy.prototype.andThrow = function(exceptionMsg) {
328 | this.plan = function() {
329 | throw exceptionMsg;
330 | };
331 | return this;
332 | };
333 |
334 | /**
335 | * Calls an alternate implementation when a spy is called.
336 | *
337 | * @example
338 | * var baz = function() {
339 | * // do some stuff, return something
340 | * }
341 | * // defining a spy from scratch: foo() calls the function baz
342 | * var foo = jasmine.createSpy('spy on foo').andCall(baz);
343 | *
344 | * // defining a spy on an existing property: foo.bar() calls an anonymnous function
345 | * spyOn(foo, 'bar').andCall(function() { return 'baz';} );
346 | *
347 | * @param {Function} fakeFunc
348 | */
349 | jasmine.Spy.prototype.andCallFake = function(fakeFunc) {
350 | this.plan = fakeFunc;
351 | return this;
352 | };
353 |
354 | /**
355 | * Resets all of a spy's the tracking variables so that it can be used again.
356 | *
357 | * @example
358 | * spyOn(foo, 'bar');
359 | *
360 | * foo.bar();
361 | *
362 | * expect(foo.bar.callCount).toEqual(1);
363 | *
364 | * foo.bar.reset();
365 | *
366 | * expect(foo.bar.callCount).toEqual(0);
367 | */
368 | jasmine.Spy.prototype.reset = function() {
369 | this.wasCalled = false;
370 | this.callCount = 0;
371 | this.argsForCall = [];
372 | this.calls = [];
373 | this.mostRecentCall = {};
374 | };
375 |
376 | jasmine.createSpy = function(name) {
377 |
378 | var spyObj = function() {
379 | spyObj.wasCalled = true;
380 | spyObj.callCount++;
381 | var args = jasmine.util.argsToArray(arguments);
382 | spyObj.mostRecentCall.object = this;
383 | spyObj.mostRecentCall.args = args;
384 | spyObj.argsForCall.push(args);
385 | spyObj.calls.push({object: this, args: args});
386 | return spyObj.plan.apply(this, arguments);
387 | };
388 |
389 | var spy = new jasmine.Spy(name);
390 |
391 | for (var prop in spy) {
392 | spyObj[prop] = spy[prop];
393 | }
394 |
395 | spyObj.reset();
396 |
397 | return spyObj;
398 | };
399 |
400 | /**
401 | * Determines whether an object is a spy.
402 | *
403 | * @param {jasmine.Spy|Object} putativeSpy
404 | * @returns {Boolean}
405 | */
406 | jasmine.isSpy = function(putativeSpy) {
407 | return putativeSpy && putativeSpy.isSpy;
408 | };
409 |
410 | /**
411 | * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something
412 | * large in one call.
413 | *
414 | * @param {String} baseName name of spy class
415 | * @param {Array} methodNames array of names of methods to make spies
416 | */
417 | jasmine.createSpyObj = function(baseName, methodNames) {
418 | if (!jasmine.isArray_(methodNames) || methodNames.length === 0) {
419 | throw new Error('createSpyObj requires a non-empty array of method names to create spies for');
420 | }
421 | var obj = {};
422 | for (var i = 0; i < methodNames.length; i++) {
423 | obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]);
424 | }
425 | return obj;
426 | };
427 |
428 | /**
429 | * All parameters are pretty-printed and concatenated together, then written to the current spec's output.
430 | *
431 | * Be careful not to leave calls to jasmine.log in production code.
432 | */
433 | jasmine.log = function() {
434 | var spec = jasmine.getEnv().currentSpec;
435 | spec.log.apply(spec, arguments);
436 | };
437 |
438 | /**
439 | * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy.
440 | *
441 | * @example
442 | * // spy example
443 | * var foo = {
444 | * not: function(bool) { return !bool; }
445 | * }
446 | * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops
447 | *
448 | * @see jasmine.createSpy
449 | * @param obj
450 | * @param methodName
451 | * @returns a Jasmine spy that can be chained with all spy methods
452 | */
453 | var spyOn = function(obj, methodName) {
454 | return jasmine.getEnv().currentSpec.spyOn(obj, methodName);
455 | };
456 | if (isCommonJS) exports.spyOn = spyOn;
457 |
458 | /**
459 | * Creates a Jasmine spec that will be added to the current suite.
460 | *
461 | * // TODO: pending tests
462 | *
463 | * @example
464 | * it('should be true', function() {
465 | * expect(true).toEqual(true);
466 | * });
467 | *
468 | * @param {String} desc description of this specification
469 | * @param {Function} func defines the preconditions and expectations of the spec
470 | */
471 | var it = function(desc, func) {
472 | return jasmine.getEnv().it(desc, func);
473 | };
474 | if (isCommonJS) exports.it = it;
475 |
476 | /**
477 | * Creates a disabled Jasmine spec.
478 | *
479 | * A convenience method that allows existing specs to be disabled temporarily during development.
480 | *
481 | * @param {String} desc description of this specification
482 | * @param {Function} func defines the preconditions and expectations of the spec
483 | */
484 | var xit = function(desc, func) {
485 | return jasmine.getEnv().xit(desc, func);
486 | };
487 | if (isCommonJS) exports.xit = xit;
488 |
489 | /**
490 | * Starts a chain for a Jasmine expectation.
491 | *
492 | * It is passed an Object that is the actual value and should chain to one of the many
493 | * jasmine.Matchers functions.
494 | *
495 | * @param {Object} actual Actual value to test against and expected value
496 | */
497 | var expect = function(actual) {
498 | return jasmine.getEnv().currentSpec.expect(actual);
499 | };
500 | if (isCommonJS) exports.expect = expect;
501 |
502 | /**
503 | * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs.
504 | *
505 | * @param {Function} func Function that defines part of a jasmine spec.
506 | */
507 | var runs = function(func) {
508 | jasmine.getEnv().currentSpec.runs(func);
509 | };
510 | if (isCommonJS) exports.runs = runs;
511 |
512 | /**
513 | * Waits a fixed time period before moving to the next block.
514 | *
515 | * @deprecated Use waitsFor() instead
516 | * @param {Number} timeout milliseconds to wait
517 | */
518 | var waits = function(timeout) {
519 | jasmine.getEnv().currentSpec.waits(timeout);
520 | };
521 | if (isCommonJS) exports.waits = waits;
522 |
523 | /**
524 | * Waits for the latchFunction to return true before proceeding to the next block.
525 | *
526 | * @param {Function} latchFunction
527 | * @param {String} optional_timeoutMessage
528 | * @param {Number} optional_timeout
529 | */
530 | var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
531 | jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
532 | };
533 | if (isCommonJS) exports.waitsFor = waitsFor;
534 |
535 | /**
536 | * A function that is called before each spec in a suite.
537 | *
538 | * Used for spec setup, including validating assumptions.
539 | *
540 | * @param {Function} beforeEachFunction
541 | */
542 | var beforeEach = function(beforeEachFunction) {
543 | jasmine.getEnv().beforeEach(beforeEachFunction);
544 | };
545 | if (isCommonJS) exports.beforeEach = beforeEach;
546 |
547 | /**
548 | * A function that is called after each spec in a suite.
549 | *
550 | * Used for restoring any state that is hijacked during spec execution.
551 | *
552 | * @param {Function} afterEachFunction
553 | */
554 | var afterEach = function(afterEachFunction) {
555 | jasmine.getEnv().afterEach(afterEachFunction);
556 | };
557 | if (isCommonJS) exports.afterEach = afterEach;
558 |
559 | /**
560 | * Defines a suite of specifications.
561 | *
562 | * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared
563 | * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization
564 | * of setup in some tests.
565 | *
566 | * @example
567 | * // TODO: a simple suite
568 | *
569 | * // TODO: a simple suite with a nested describe block
570 | *
571 | * @param {String} description A string, usually the class under test.
572 | * @param {Function} specDefinitions function that defines several specs.
573 | */
574 | var describe = function(description, specDefinitions) {
575 | return jasmine.getEnv().describe(description, specDefinitions);
576 | };
577 | if (isCommonJS) exports.describe = describe;
578 |
579 | /**
580 | * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
581 | *
582 | * @param {String} description A string, usually the class under test.
583 | * @param {Function} specDefinitions function that defines several specs.
584 | */
585 | var xdescribe = function(description, specDefinitions) {
586 | return jasmine.getEnv().xdescribe(description, specDefinitions);
587 | };
588 | if (isCommonJS) exports.xdescribe = xdescribe;
589 |
590 |
591 | // Provide the XMLHttpRequest class for IE 5.x-6.x:
592 | jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() {
593 | function tryIt(f) {
594 | try {
595 | return f();
596 | } catch(e) {
597 | }
598 | return null;
599 | }
600 |
601 | var xhr = tryIt(function() {
602 | return new ActiveXObject("Msxml2.XMLHTTP.6.0");
603 | }) ||
604 | tryIt(function() {
605 | return new ActiveXObject("Msxml2.XMLHTTP.3.0");
606 | }) ||
607 | tryIt(function() {
608 | return new ActiveXObject("Msxml2.XMLHTTP");
609 | }) ||
610 | tryIt(function() {
611 | return new ActiveXObject("Microsoft.XMLHTTP");
612 | });
613 |
614 | if (!xhr) throw new Error("This browser does not support XMLHttpRequest.");
615 |
616 | return xhr;
617 | } : XMLHttpRequest;
618 | /**
619 | * @namespace
620 | */
621 | jasmine.util = {};
622 |
623 | /**
624 | * Declare that a child class inherit it's prototype from the parent class.
625 | *
626 | * @private
627 | * @param {Function} childClass
628 | * @param {Function} parentClass
629 | */
630 | jasmine.util.inherit = function(childClass, parentClass) {
631 | /**
632 | * @private
633 | */
634 | var subclass = function() {
635 | };
636 | subclass.prototype = parentClass.prototype;
637 | childClass.prototype = new subclass();
638 | };
639 |
640 | jasmine.util.formatException = function(e) {
641 | var lineNumber;
642 | if (e.line) {
643 | lineNumber = e.line;
644 | }
645 | else if (e.lineNumber) {
646 | lineNumber = e.lineNumber;
647 | }
648 |
649 | var file;
650 |
651 | if (e.sourceURL) {
652 | file = e.sourceURL;
653 | }
654 | else if (e.fileName) {
655 | file = e.fileName;
656 | }
657 |
658 | var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString();
659 |
660 | if (file && lineNumber) {
661 | message += ' in ' + file + ' (line ' + lineNumber + ')';
662 | }
663 |
664 | return message;
665 | };
666 |
667 | jasmine.util.htmlEscape = function(str) {
668 | if (!str) return str;
669 | return str.replace(/&/g, '&')
670 | .replace(//g, '>');
672 | };
673 |
674 | jasmine.util.argsToArray = function(args) {
675 | var arrayOfArgs = [];
676 | for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]);
677 | return arrayOfArgs;
678 | };
679 |
680 | jasmine.util.extend = function(destination, source) {
681 | for (var property in source) destination[property] = source[property];
682 | return destination;
683 | };
684 |
685 | /**
686 | * Environment for Jasmine
687 | *
688 | * @constructor
689 | */
690 | jasmine.Env = function() {
691 | this.currentSpec = null;
692 | this.currentSuite = null;
693 | this.currentRunner_ = new jasmine.Runner(this);
694 |
695 | this.reporter = new jasmine.MultiReporter();
696 |
697 | this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL;
698 | this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL;
699 | this.lastUpdate = 0;
700 | this.specFilter = function() {
701 | return true;
702 | };
703 |
704 | this.nextSpecId_ = 0;
705 | this.nextSuiteId_ = 0;
706 | this.equalityTesters_ = [];
707 |
708 | // wrap matchers
709 | this.matchersClass = function() {
710 | jasmine.Matchers.apply(this, arguments);
711 | };
712 | jasmine.util.inherit(this.matchersClass, jasmine.Matchers);
713 |
714 | jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass);
715 | };
716 |
717 |
718 | jasmine.Env.prototype.setTimeout = jasmine.setTimeout;
719 | jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout;
720 | jasmine.Env.prototype.setInterval = jasmine.setInterval;
721 | jasmine.Env.prototype.clearInterval = jasmine.clearInterval;
722 |
723 | /**
724 | * @returns an object containing jasmine version build info, if set.
725 | */
726 | jasmine.Env.prototype.version = function () {
727 | if (jasmine.version_) {
728 | return jasmine.version_;
729 | } else {
730 | throw new Error('Version not set');
731 | }
732 | };
733 |
734 | /**
735 | * @returns string containing jasmine version build info, if set.
736 | */
737 | jasmine.Env.prototype.versionString = function() {
738 | if (!jasmine.version_) {
739 | return "version unknown";
740 | }
741 |
742 | var version = this.version();
743 | var versionString = version.major + "." + version.minor + "." + version.build;
744 | if (version.release_candidate) {
745 | versionString += ".rc" + version.release_candidate;
746 | }
747 | versionString += " revision " + version.revision;
748 | return versionString;
749 | };
750 |
751 | /**
752 | * @returns a sequential integer starting at 0
753 | */
754 | jasmine.Env.prototype.nextSpecId = function () {
755 | return this.nextSpecId_++;
756 | };
757 |
758 | /**
759 | * @returns a sequential integer starting at 0
760 | */
761 | jasmine.Env.prototype.nextSuiteId = function () {
762 | return this.nextSuiteId_++;
763 | };
764 |
765 | /**
766 | * Register a reporter to receive status updates from Jasmine.
767 | * @param {jasmine.Reporter} reporter An object which will receive status updates.
768 | */
769 | jasmine.Env.prototype.addReporter = function(reporter) {
770 | this.reporter.addReporter(reporter);
771 | };
772 |
773 | jasmine.Env.prototype.execute = function() {
774 | this.currentRunner_.execute();
775 | };
776 |
777 | jasmine.Env.prototype.describe = function(description, specDefinitions) {
778 | var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite);
779 |
780 | var parentSuite = this.currentSuite;
781 | if (parentSuite) {
782 | parentSuite.add(suite);
783 | } else {
784 | this.currentRunner_.add(suite);
785 | }
786 |
787 | this.currentSuite = suite;
788 |
789 | var declarationError = null;
790 | try {
791 | specDefinitions.call(suite);
792 | } catch(e) {
793 | declarationError = e;
794 | }
795 |
796 | if (declarationError) {
797 | this.it("encountered a declaration exception", function() {
798 | throw declarationError;
799 | });
800 | }
801 |
802 | this.currentSuite = parentSuite;
803 |
804 | return suite;
805 | };
806 |
807 | jasmine.Env.prototype.beforeEach = function(beforeEachFunction) {
808 | if (this.currentSuite) {
809 | this.currentSuite.beforeEach(beforeEachFunction);
810 | } else {
811 | this.currentRunner_.beforeEach(beforeEachFunction);
812 | }
813 | };
814 |
815 | jasmine.Env.prototype.currentRunner = function () {
816 | return this.currentRunner_;
817 | };
818 |
819 | jasmine.Env.prototype.afterEach = function(afterEachFunction) {
820 | if (this.currentSuite) {
821 | this.currentSuite.afterEach(afterEachFunction);
822 | } else {
823 | this.currentRunner_.afterEach(afterEachFunction);
824 | }
825 |
826 | };
827 |
828 | jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) {
829 | return {
830 | execute: function() {
831 | }
832 | };
833 | };
834 |
835 | jasmine.Env.prototype.it = function(description, func) {
836 | var spec = new jasmine.Spec(this, this.currentSuite, description);
837 | this.currentSuite.add(spec);
838 | this.currentSpec = spec;
839 |
840 | if (func) {
841 | spec.runs(func);
842 | }
843 |
844 | return spec;
845 | };
846 |
847 | jasmine.Env.prototype.xit = function(desc, func) {
848 | return {
849 | id: this.nextSpecId(),
850 | runs: function() {
851 | }
852 | };
853 | };
854 |
855 | jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) {
856 | if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) {
857 | return true;
858 | }
859 |
860 | a.__Jasmine_been_here_before__ = b;
861 | b.__Jasmine_been_here_before__ = a;
862 |
863 | var hasKey = function(obj, keyName) {
864 | return obj !== null && obj[keyName] !== jasmine.undefined;
865 | };
866 |
867 | for (var property in b) {
868 | if (!hasKey(a, property) && hasKey(b, property)) {
869 | mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
870 | }
871 | }
872 | for (property in a) {
873 | if (!hasKey(b, property) && hasKey(a, property)) {
874 | mismatchKeys.push("expected missing key '" + property + "', but present in actual.");
875 | }
876 | }
877 | for (property in b) {
878 | if (property == '__Jasmine_been_here_before__') continue;
879 | if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) {
880 | mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual.");
881 | }
882 | }
883 |
884 | if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) {
885 | mismatchValues.push("arrays were not the same length");
886 | }
887 |
888 | delete a.__Jasmine_been_here_before__;
889 | delete b.__Jasmine_been_here_before__;
890 | return (mismatchKeys.length === 0 && mismatchValues.length === 0);
891 | };
892 |
893 | jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) {
894 | mismatchKeys = mismatchKeys || [];
895 | mismatchValues = mismatchValues || [];
896 |
897 | for (var i = 0; i < this.equalityTesters_.length; i++) {
898 | var equalityTester = this.equalityTesters_[i];
899 | var result = equalityTester(a, b, this, mismatchKeys, mismatchValues);
900 | if (result !== jasmine.undefined) return result;
901 | }
902 |
903 | if (a === b) return true;
904 |
905 | if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) {
906 | return (a == jasmine.undefined && b == jasmine.undefined);
907 | }
908 |
909 | if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) {
910 | return a === b;
911 | }
912 |
913 | if (a instanceof Date && b instanceof Date) {
914 | return a.getTime() == b.getTime();
915 | }
916 |
917 | if (a instanceof jasmine.Matchers.Any) {
918 | return a.matches(b);
919 | }
920 |
921 | if (b instanceof jasmine.Matchers.Any) {
922 | return b.matches(a);
923 | }
924 |
925 | if (jasmine.isString_(a) && jasmine.isString_(b)) {
926 | return (a == b);
927 | }
928 |
929 | if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) {
930 | return (a == b);
931 | }
932 |
933 | if (typeof a === "object" && typeof b === "object") {
934 | return this.compareObjects_(a, b, mismatchKeys, mismatchValues);
935 | }
936 |
937 | //Straight check
938 | return (a === b);
939 | };
940 |
941 | jasmine.Env.prototype.contains_ = function(haystack, needle) {
942 | if (jasmine.isArray_(haystack)) {
943 | for (var i = 0; i < haystack.length; i++) {
944 | if (this.equals_(haystack[i], needle)) return true;
945 | }
946 | return false;
947 | }
948 | return haystack.indexOf(needle) >= 0;
949 | };
950 |
951 | jasmine.Env.prototype.addEqualityTester = function(equalityTester) {
952 | this.equalityTesters_.push(equalityTester);
953 | };
954 | /** No-op base class for Jasmine reporters.
955 | *
956 | * @constructor
957 | */
958 | jasmine.Reporter = function() {
959 | };
960 |
961 | //noinspection JSUnusedLocalSymbols
962 | jasmine.Reporter.prototype.reportRunnerStarting = function(runner) {
963 | };
964 |
965 | //noinspection JSUnusedLocalSymbols
966 | jasmine.Reporter.prototype.reportRunnerResults = function(runner) {
967 | };
968 |
969 | //noinspection JSUnusedLocalSymbols
970 | jasmine.Reporter.prototype.reportSuiteResults = function(suite) {
971 | };
972 |
973 | //noinspection JSUnusedLocalSymbols
974 | jasmine.Reporter.prototype.reportSpecStarting = function(spec) {
975 | };
976 |
977 | //noinspection JSUnusedLocalSymbols
978 | jasmine.Reporter.prototype.reportSpecResults = function(spec) {
979 | };
980 |
981 | //noinspection JSUnusedLocalSymbols
982 | jasmine.Reporter.prototype.log = function(str) {
983 | };
984 |
985 | /**
986 | * Blocks are functions with executable code that make up a spec.
987 | *
988 | * @constructor
989 | * @param {jasmine.Env} env
990 | * @param {Function} func
991 | * @param {jasmine.Spec} spec
992 | */
993 | jasmine.Block = function(env, func, spec) {
994 | this.env = env;
995 | this.func = func;
996 | this.spec = spec;
997 | };
998 |
999 | jasmine.Block.prototype.execute = function(onComplete) {
1000 | try {
1001 | this.func.apply(this.spec);
1002 | } catch (e) {
1003 | this.spec.fail(e);
1004 | }
1005 | onComplete();
1006 | };
1007 | /** JavaScript API reporter.
1008 | *
1009 | * @constructor
1010 | */
1011 | jasmine.JsApiReporter = function() {
1012 | this.started = false;
1013 | this.finished = false;
1014 | this.suites_ = [];
1015 | this.results_ = {};
1016 | };
1017 |
1018 | jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) {
1019 | this.started = true;
1020 | var suites = runner.topLevelSuites();
1021 | for (var i = 0; i < suites.length; i++) {
1022 | var suite = suites[i];
1023 | this.suites_.push(this.summarize_(suite));
1024 | }
1025 | };
1026 |
1027 | jasmine.JsApiReporter.prototype.suites = function() {
1028 | return this.suites_;
1029 | };
1030 |
1031 | jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) {
1032 | var isSuite = suiteOrSpec instanceof jasmine.Suite;
1033 | var summary = {
1034 | id: suiteOrSpec.id,
1035 | name: suiteOrSpec.description,
1036 | type: isSuite ? 'suite' : 'spec',
1037 | children: []
1038 | };
1039 |
1040 | if (isSuite) {
1041 | var children = suiteOrSpec.children();
1042 | for (var i = 0; i < children.length; i++) {
1043 | summary.children.push(this.summarize_(children[i]));
1044 | }
1045 | }
1046 | return summary;
1047 | };
1048 |
1049 | jasmine.JsApiReporter.prototype.results = function() {
1050 | return this.results_;
1051 | };
1052 |
1053 | jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) {
1054 | return this.results_[specId];
1055 | };
1056 |
1057 | //noinspection JSUnusedLocalSymbols
1058 | jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) {
1059 | this.finished = true;
1060 | };
1061 |
1062 | //noinspection JSUnusedLocalSymbols
1063 | jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) {
1064 | };
1065 |
1066 | //noinspection JSUnusedLocalSymbols
1067 | jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) {
1068 | this.results_[spec.id] = {
1069 | messages: spec.results().getItems(),
1070 | result: spec.results().failedCount > 0 ? "failed" : "passed"
1071 | };
1072 | };
1073 |
1074 | //noinspection JSUnusedLocalSymbols
1075 | jasmine.JsApiReporter.prototype.log = function(str) {
1076 | };
1077 |
1078 | jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){
1079 | var results = {};
1080 | for (var i = 0; i < specIds.length; i++) {
1081 | var specId = specIds[i];
1082 | results[specId] = this.summarizeResult_(this.results_[specId]);
1083 | }
1084 | return results;
1085 | };
1086 |
1087 | jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){
1088 | var summaryMessages = [];
1089 | var messagesLength = result.messages.length;
1090 | for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) {
1091 | var resultMessage = result.messages[messageIndex];
1092 | summaryMessages.push({
1093 | text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined,
1094 | passed: resultMessage.passed ? resultMessage.passed() : true,
1095 | type: resultMessage.type,
1096 | message: resultMessage.message,
1097 | trace: {
1098 | stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined
1099 | }
1100 | });
1101 | }
1102 |
1103 | return {
1104 | result : result.result,
1105 | messages : summaryMessages
1106 | };
1107 | };
1108 |
1109 | /**
1110 | * @constructor
1111 | * @param {jasmine.Env} env
1112 | * @param actual
1113 | * @param {jasmine.Spec} spec
1114 | */
1115 | jasmine.Matchers = function(env, actual, spec, opt_isNot) {
1116 | this.env = env;
1117 | this.actual = actual;
1118 | this.spec = spec;
1119 | this.isNot = opt_isNot || false;
1120 | this.reportWasCalled_ = false;
1121 | };
1122 |
1123 | // todo: @deprecated as of Jasmine 0.11, remove soon [xw]
1124 | jasmine.Matchers.pp = function(str) {
1125 | throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!");
1126 | };
1127 |
1128 | // todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw]
1129 | jasmine.Matchers.prototype.report = function(result, failing_message, details) {
1130 | throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs");
1131 | };
1132 |
1133 | jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) {
1134 | for (var methodName in prototype) {
1135 | if (methodName == 'report') continue;
1136 | var orig = prototype[methodName];
1137 | matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig);
1138 | }
1139 | };
1140 |
1141 | jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) {
1142 | return function() {
1143 | var matcherArgs = jasmine.util.argsToArray(arguments);
1144 | var result = matcherFunction.apply(this, arguments);
1145 |
1146 | if (this.isNot) {
1147 | result = !result;
1148 | }
1149 |
1150 | if (this.reportWasCalled_) return result;
1151 |
1152 | var message;
1153 | if (!result) {
1154 | if (this.message) {
1155 | message = this.message.apply(this, arguments);
1156 | if (jasmine.isArray_(message)) {
1157 | message = message[this.isNot ? 1 : 0];
1158 | }
1159 | } else {
1160 | var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); });
1161 | message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate;
1162 | if (matcherArgs.length > 0) {
1163 | for (var i = 0; i < matcherArgs.length; i++) {
1164 | if (i > 0) message += ",";
1165 | message += " " + jasmine.pp(matcherArgs[i]);
1166 | }
1167 | }
1168 | message += ".";
1169 | }
1170 | }
1171 | var expectationResult = new jasmine.ExpectationResult({
1172 | matcherName: matcherName,
1173 | passed: result,
1174 | expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0],
1175 | actual: this.actual,
1176 | message: message
1177 | });
1178 | this.spec.addMatcherResult(expectationResult);
1179 | return jasmine.undefined;
1180 | };
1181 | };
1182 |
1183 |
1184 |
1185 |
1186 | /**
1187 | * toBe: compares the actual to the expected using ===
1188 | * @param expected
1189 | */
1190 | jasmine.Matchers.prototype.toBe = function(expected) {
1191 | return this.actual === expected;
1192 | };
1193 |
1194 | /**
1195 | * toNotBe: compares the actual to the expected using !==
1196 | * @param expected
1197 | * @deprecated as of 1.0. Use not.toBe() instead.
1198 | */
1199 | jasmine.Matchers.prototype.toNotBe = function(expected) {
1200 | return this.actual !== expected;
1201 | };
1202 |
1203 | /**
1204 | * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc.
1205 | *
1206 | * @param expected
1207 | */
1208 | jasmine.Matchers.prototype.toEqual = function(expected) {
1209 | return this.env.equals_(this.actual, expected);
1210 | };
1211 |
1212 | /**
1213 | * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual
1214 | * @param expected
1215 | * @deprecated as of 1.0. Use not.toNotEqual() instead.
1216 | */
1217 | jasmine.Matchers.prototype.toNotEqual = function(expected) {
1218 | return !this.env.equals_(this.actual, expected);
1219 | };
1220 |
1221 | /**
1222 | * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes
1223 | * a pattern or a String.
1224 | *
1225 | * @param expected
1226 | */
1227 | jasmine.Matchers.prototype.toMatch = function(expected) {
1228 | return new RegExp(expected).test(this.actual);
1229 | };
1230 |
1231 | /**
1232 | * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch
1233 | * @param expected
1234 | * @deprecated as of 1.0. Use not.toMatch() instead.
1235 | */
1236 | jasmine.Matchers.prototype.toNotMatch = function(expected) {
1237 | return !(new RegExp(expected).test(this.actual));
1238 | };
1239 |
1240 | /**
1241 | * Matcher that compares the actual to jasmine.undefined.
1242 | */
1243 | jasmine.Matchers.prototype.toBeDefined = function() {
1244 | return (this.actual !== jasmine.undefined);
1245 | };
1246 |
1247 | /**
1248 | * Matcher that compares the actual to jasmine.undefined.
1249 | */
1250 | jasmine.Matchers.prototype.toBeUndefined = function() {
1251 | return (this.actual === jasmine.undefined);
1252 | };
1253 |
1254 | /**
1255 | * Matcher that compares the actual to null.
1256 | */
1257 | jasmine.Matchers.prototype.toBeNull = function() {
1258 | return (this.actual === null);
1259 | };
1260 |
1261 | /**
1262 | * Matcher that boolean not-nots the actual.
1263 | */
1264 | jasmine.Matchers.prototype.toBeTruthy = function() {
1265 | return !!this.actual;
1266 | };
1267 |
1268 |
1269 | /**
1270 | * Matcher that boolean nots the actual.
1271 | */
1272 | jasmine.Matchers.prototype.toBeFalsy = function() {
1273 | return !this.actual;
1274 | };
1275 |
1276 |
1277 | /**
1278 | * Matcher that checks to see if the actual, a Jasmine spy, was called.
1279 | */
1280 | jasmine.Matchers.prototype.toHaveBeenCalled = function() {
1281 | if (arguments.length > 0) {
1282 | throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith');
1283 | }
1284 |
1285 | if (!jasmine.isSpy(this.actual)) {
1286 | throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
1287 | }
1288 |
1289 | this.message = function() {
1290 | return [
1291 | "Expected spy " + this.actual.identity + " to have been called.",
1292 | "Expected spy " + this.actual.identity + " not to have been called."
1293 | ];
1294 | };
1295 |
1296 | return this.actual.wasCalled;
1297 | };
1298 |
1299 | /** @deprecated Use expect(xxx).toHaveBeenCalled() instead */
1300 | jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled;
1301 |
1302 | /**
1303 | * Matcher that checks to see if the actual, a Jasmine spy, was not called.
1304 | *
1305 | * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead
1306 | */
1307 | jasmine.Matchers.prototype.wasNotCalled = function() {
1308 | if (arguments.length > 0) {
1309 | throw new Error('wasNotCalled does not take arguments');
1310 | }
1311 |
1312 | if (!jasmine.isSpy(this.actual)) {
1313 | throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
1314 | }
1315 |
1316 | this.message = function() {
1317 | return [
1318 | "Expected spy " + this.actual.identity + " to not have been called.",
1319 | "Expected spy " + this.actual.identity + " to have been called."
1320 | ];
1321 | };
1322 |
1323 | return !this.actual.wasCalled;
1324 | };
1325 |
1326 | /**
1327 | * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters.
1328 | *
1329 | * @example
1330 | *
1331 | */
1332 | jasmine.Matchers.prototype.toHaveBeenCalledWith = function() {
1333 | var expectedArgs = jasmine.util.argsToArray(arguments);
1334 | if (!jasmine.isSpy(this.actual)) {
1335 | throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
1336 | }
1337 | this.message = function() {
1338 | if (this.actual.callCount === 0) {
1339 | // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw]
1340 | return [
1341 | "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.",
1342 | "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was."
1343 | ];
1344 | } else {
1345 | return [
1346 | "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall),
1347 | "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall)
1348 | ];
1349 | }
1350 | };
1351 |
1352 | return this.env.contains_(this.actual.argsForCall, expectedArgs);
1353 | };
1354 |
1355 | /** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */
1356 | jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith;
1357 |
1358 | /** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */
1359 | jasmine.Matchers.prototype.wasNotCalledWith = function() {
1360 | var expectedArgs = jasmine.util.argsToArray(arguments);
1361 | if (!jasmine.isSpy(this.actual)) {
1362 | throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
1363 | }
1364 |
1365 | this.message = function() {
1366 | return [
1367 | "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was",
1368 | "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was"
1369 | ];
1370 | };
1371 |
1372 | return !this.env.contains_(this.actual.argsForCall, expectedArgs);
1373 | };
1374 |
1375 | /**
1376 | * Matcher that checks that the expected item is an element in the actual Array.
1377 | *
1378 | * @param {Object} expected
1379 | */
1380 | jasmine.Matchers.prototype.toContain = function(expected) {
1381 | return this.env.contains_(this.actual, expected);
1382 | };
1383 |
1384 | /**
1385 | * Matcher that checks that the expected item is NOT an element in the actual Array.
1386 | *
1387 | * @param {Object} expected
1388 | * @deprecated as of 1.0. Use not.toNotContain() instead.
1389 | */
1390 | jasmine.Matchers.prototype.toNotContain = function(expected) {
1391 | return !this.env.contains_(this.actual, expected);
1392 | };
1393 |
1394 | jasmine.Matchers.prototype.toBeLessThan = function(expected) {
1395 | return this.actual < expected;
1396 | };
1397 |
1398 | jasmine.Matchers.prototype.toBeGreaterThan = function(expected) {
1399 | return this.actual > expected;
1400 | };
1401 |
1402 | /**
1403 | * Matcher that checks that the expected item is equal to the actual item
1404 | * up to a given level of decimal precision (default 2).
1405 | *
1406 | * @param {Number} expected
1407 | * @param {Number} precision
1408 | */
1409 | jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) {
1410 | if (!(precision === 0)) {
1411 | precision = precision || 2;
1412 | }
1413 | var multiplier = Math.pow(10, precision);
1414 | var actual = Math.round(this.actual * multiplier);
1415 | expected = Math.round(expected * multiplier);
1416 | return expected == actual;
1417 | };
1418 |
1419 | /**
1420 | * Matcher that checks that the expected exception was thrown by the actual.
1421 | *
1422 | * @param {String} expected
1423 | */
1424 | jasmine.Matchers.prototype.toThrow = function(expected) {
1425 | var result = false;
1426 | var exception;
1427 | if (typeof this.actual != 'function') {
1428 | throw new Error('Actual is not a function');
1429 | }
1430 | try {
1431 | this.actual();
1432 | } catch (e) {
1433 | exception = e;
1434 | }
1435 | if (exception) {
1436 | result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected));
1437 | }
1438 |
1439 | var not = this.isNot ? "not " : "";
1440 |
1441 | this.message = function() {
1442 | if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
1443 | return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' ');
1444 | } else {
1445 | return "Expected function to throw an exception.";
1446 | }
1447 | };
1448 |
1449 | return result;
1450 | };
1451 |
1452 | jasmine.Matchers.Any = function(expectedClass) {
1453 | this.expectedClass = expectedClass;
1454 | };
1455 |
1456 | jasmine.Matchers.Any.prototype.matches = function(other) {
1457 | if (this.expectedClass == String) {
1458 | return typeof other == 'string' || other instanceof String;
1459 | }
1460 |
1461 | if (this.expectedClass == Number) {
1462 | return typeof other == 'number' || other instanceof Number;
1463 | }
1464 |
1465 | if (this.expectedClass == Function) {
1466 | return typeof other == 'function' || other instanceof Function;
1467 | }
1468 |
1469 | if (this.expectedClass == Object) {
1470 | return typeof other == 'object';
1471 | }
1472 |
1473 | return other instanceof this.expectedClass;
1474 | };
1475 |
1476 | jasmine.Matchers.Any.prototype.toString = function() {
1477 | return '';
1478 | };
1479 |
1480 | /**
1481 | * @constructor
1482 | */
1483 | jasmine.MultiReporter = function() {
1484 | this.subReporters_ = [];
1485 | };
1486 | jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter);
1487 |
1488 | jasmine.MultiReporter.prototype.addReporter = function(reporter) {
1489 | this.subReporters_.push(reporter);
1490 | };
1491 |
1492 | (function() {
1493 | var functionNames = [
1494 | "reportRunnerStarting",
1495 | "reportRunnerResults",
1496 | "reportSuiteResults",
1497 | "reportSpecStarting",
1498 | "reportSpecResults",
1499 | "log"
1500 | ];
1501 | for (var i = 0; i < functionNames.length; i++) {
1502 | var functionName = functionNames[i];
1503 | jasmine.MultiReporter.prototype[functionName] = (function(functionName) {
1504 | return function() {
1505 | for (var j = 0; j < this.subReporters_.length; j++) {
1506 | var subReporter = this.subReporters_[j];
1507 | if (subReporter[functionName]) {
1508 | subReporter[functionName].apply(subReporter, arguments);
1509 | }
1510 | }
1511 | };
1512 | })(functionName);
1513 | }
1514 | })();
1515 | /**
1516 | * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults
1517 | *
1518 | * @constructor
1519 | */
1520 | jasmine.NestedResults = function() {
1521 | /**
1522 | * The total count of results
1523 | */
1524 | this.totalCount = 0;
1525 | /**
1526 | * Number of passed results
1527 | */
1528 | this.passedCount = 0;
1529 | /**
1530 | * Number of failed results
1531 | */
1532 | this.failedCount = 0;
1533 | /**
1534 | * Was this suite/spec skipped?
1535 | */
1536 | this.skipped = false;
1537 | /**
1538 | * @ignore
1539 | */
1540 | this.items_ = [];
1541 | };
1542 |
1543 | /**
1544 | * Roll up the result counts.
1545 | *
1546 | * @param result
1547 | */
1548 | jasmine.NestedResults.prototype.rollupCounts = function(result) {
1549 | this.totalCount += result.totalCount;
1550 | this.passedCount += result.passedCount;
1551 | this.failedCount += result.failedCount;
1552 | };
1553 |
1554 | /**
1555 | * Adds a log message.
1556 | * @param values Array of message parts which will be concatenated later.
1557 | */
1558 | jasmine.NestedResults.prototype.log = function(values) {
1559 | this.items_.push(new jasmine.MessageResult(values));
1560 | };
1561 |
1562 | /**
1563 | * Getter for the results: message & results.
1564 | */
1565 | jasmine.NestedResults.prototype.getItems = function() {
1566 | return this.items_;
1567 | };
1568 |
1569 | /**
1570 | * Adds a result, tracking counts (total, passed, & failed)
1571 | * @param {jasmine.ExpectationResult|jasmine.NestedResults} result
1572 | */
1573 | jasmine.NestedResults.prototype.addResult = function(result) {
1574 | if (result.type != 'log') {
1575 | if (result.items_) {
1576 | this.rollupCounts(result);
1577 | } else {
1578 | this.totalCount++;
1579 | if (result.passed()) {
1580 | this.passedCount++;
1581 | } else {
1582 | this.failedCount++;
1583 | }
1584 | }
1585 | }
1586 | this.items_.push(result);
1587 | };
1588 |
1589 | /**
1590 | * @returns {Boolean} True if everything below passed
1591 | */
1592 | jasmine.NestedResults.prototype.passed = function() {
1593 | return this.passedCount === this.totalCount;
1594 | };
1595 | /**
1596 | * Base class for pretty printing for expectation results.
1597 | */
1598 | jasmine.PrettyPrinter = function() {
1599 | this.ppNestLevel_ = 0;
1600 | };
1601 |
1602 | /**
1603 | * Formats a value in a nice, human-readable string.
1604 | *
1605 | * @param value
1606 | */
1607 | jasmine.PrettyPrinter.prototype.format = function(value) {
1608 | if (this.ppNestLevel_ > 40) {
1609 | throw new Error('jasmine.PrettyPrinter: format() nested too deeply!');
1610 | }
1611 |
1612 | this.ppNestLevel_++;
1613 | try {
1614 | if (value === jasmine.undefined) {
1615 | this.emitScalar('undefined');
1616 | } else if (value === null) {
1617 | this.emitScalar('null');
1618 | } else if (value === jasmine.getGlobal()) {
1619 | this.emitScalar('');
1620 | } else if (value instanceof jasmine.Matchers.Any) {
1621 | this.emitScalar(value.toString());
1622 | } else if (typeof value === 'string') {
1623 | this.emitString(value);
1624 | } else if (jasmine.isSpy(value)) {
1625 | this.emitScalar("spy on " + value.identity);
1626 | } else if (value instanceof RegExp) {
1627 | this.emitScalar(value.toString());
1628 | } else if (typeof value === 'function') {
1629 | this.emitScalar('Function');
1630 | } else if (typeof value.nodeType === 'number') {
1631 | this.emitScalar('HTMLNode');
1632 | } else if (value instanceof Date) {
1633 | this.emitScalar('Date(' + value + ')');
1634 | } else if (value.__Jasmine_been_here_before__) {
1635 | this.emitScalar('');
1636 | } else if (jasmine.isArray_(value) || typeof value == 'object') {
1637 | value.__Jasmine_been_here_before__ = true;
1638 | if (jasmine.isArray_(value)) {
1639 | this.emitArray(value);
1640 | } else {
1641 | this.emitObject(value);
1642 | }
1643 | delete value.__Jasmine_been_here_before__;
1644 | } else {
1645 | this.emitScalar(value.toString());
1646 | }
1647 | } finally {
1648 | this.ppNestLevel_--;
1649 | }
1650 | };
1651 |
1652 | jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) {
1653 | for (var property in obj) {
1654 | if (property == '__Jasmine_been_here_before__') continue;
1655 | fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined &&
1656 | obj.__lookupGetter__(property) !== null) : false);
1657 | }
1658 | };
1659 |
1660 | jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_;
1661 | jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_;
1662 | jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_;
1663 | jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_;
1664 |
1665 | jasmine.StringPrettyPrinter = function() {
1666 | jasmine.PrettyPrinter.call(this);
1667 |
1668 | this.string = '';
1669 | };
1670 | jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter);
1671 |
1672 | jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) {
1673 | this.append(value);
1674 | };
1675 |
1676 | jasmine.StringPrettyPrinter.prototype.emitString = function(value) {
1677 | this.append("'" + value + "'");
1678 | };
1679 |
1680 | jasmine.StringPrettyPrinter.prototype.emitArray = function(array) {
1681 | this.append('[ ');
1682 | for (var i = 0; i < array.length; i++) {
1683 | if (i > 0) {
1684 | this.append(', ');
1685 | }
1686 | this.format(array[i]);
1687 | }
1688 | this.append(' ]');
1689 | };
1690 |
1691 | jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) {
1692 | var self = this;
1693 | this.append('{ ');
1694 | var first = true;
1695 |
1696 | this.iterateObject(obj, function(property, isGetter) {
1697 | if (first) {
1698 | first = false;
1699 | } else {
1700 | self.append(', ');
1701 | }
1702 |
1703 | self.append(property);
1704 | self.append(' : ');
1705 | if (isGetter) {
1706 | self.append('');
1707 | } else {
1708 | self.format(obj[property]);
1709 | }
1710 | });
1711 |
1712 | this.append(' }');
1713 | };
1714 |
1715 | jasmine.StringPrettyPrinter.prototype.append = function(value) {
1716 | this.string += value;
1717 | };
1718 | jasmine.Queue = function(env) {
1719 | this.env = env;
1720 | this.blocks = [];
1721 | this.running = false;
1722 | this.index = 0;
1723 | this.offset = 0;
1724 | this.abort = false;
1725 | };
1726 |
1727 | jasmine.Queue.prototype.addBefore = function(block) {
1728 | this.blocks.unshift(block);
1729 | };
1730 |
1731 | jasmine.Queue.prototype.add = function(block) {
1732 | this.blocks.push(block);
1733 | };
1734 |
1735 | jasmine.Queue.prototype.insertNext = function(block) {
1736 | this.blocks.splice((this.index + this.offset + 1), 0, block);
1737 | this.offset++;
1738 | };
1739 |
1740 | jasmine.Queue.prototype.start = function(onComplete) {
1741 | this.running = true;
1742 | this.onComplete = onComplete;
1743 | this.next_();
1744 | };
1745 |
1746 | jasmine.Queue.prototype.isRunning = function() {
1747 | return this.running;
1748 | };
1749 |
1750 | jasmine.Queue.LOOP_DONT_RECURSE = true;
1751 |
1752 | jasmine.Queue.prototype.next_ = function() {
1753 | var self = this;
1754 | var goAgain = true;
1755 |
1756 | while (goAgain) {
1757 | goAgain = false;
1758 |
1759 | if (self.index < self.blocks.length && !this.abort) {
1760 | var calledSynchronously = true;
1761 | var completedSynchronously = false;
1762 |
1763 | var onComplete = function () {
1764 | if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
1765 | completedSynchronously = true;
1766 | return;
1767 | }
1768 |
1769 | if (self.blocks[self.index].abort) {
1770 | self.abort = true;
1771 | }
1772 |
1773 | self.offset = 0;
1774 | self.index++;
1775 |
1776 | var now = new Date().getTime();
1777 | if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
1778 | self.env.lastUpdate = now;
1779 | self.env.setTimeout(function() {
1780 | self.next_();
1781 | }, 0);
1782 | } else {
1783 | if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
1784 | goAgain = true;
1785 | } else {
1786 | self.next_();
1787 | }
1788 | }
1789 | };
1790 | self.blocks[self.index].execute(onComplete);
1791 |
1792 | calledSynchronously = false;
1793 | if (completedSynchronously) {
1794 | onComplete();
1795 | }
1796 |
1797 | } else {
1798 | self.running = false;
1799 | if (self.onComplete) {
1800 | self.onComplete();
1801 | }
1802 | }
1803 | }
1804 | };
1805 |
1806 | jasmine.Queue.prototype.results = function() {
1807 | var results = new jasmine.NestedResults();
1808 | for (var i = 0; i < this.blocks.length; i++) {
1809 | if (this.blocks[i].results) {
1810 | results.addResult(this.blocks[i].results());
1811 | }
1812 | }
1813 | return results;
1814 | };
1815 |
1816 |
1817 | /**
1818 | * Runner
1819 | *
1820 | * @constructor
1821 | * @param {jasmine.Env} env
1822 | */
1823 | jasmine.Runner = function(env) {
1824 | var self = this;
1825 | self.env = env;
1826 | self.queue = new jasmine.Queue(env);
1827 | self.before_ = [];
1828 | self.after_ = [];
1829 | self.suites_ = [];
1830 | };
1831 |
1832 | jasmine.Runner.prototype.execute = function() {
1833 | var self = this;
1834 | if (self.env.reporter.reportRunnerStarting) {
1835 | self.env.reporter.reportRunnerStarting(this);
1836 | }
1837 | self.queue.start(function () {
1838 | self.finishCallback();
1839 | });
1840 | };
1841 |
1842 | jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) {
1843 | beforeEachFunction.typeName = 'beforeEach';
1844 | this.before_.splice(0,0,beforeEachFunction);
1845 | };
1846 |
1847 | jasmine.Runner.prototype.afterEach = function(afterEachFunction) {
1848 | afterEachFunction.typeName = 'afterEach';
1849 | this.after_.splice(0,0,afterEachFunction);
1850 | };
1851 |
1852 |
1853 | jasmine.Runner.prototype.finishCallback = function() {
1854 | this.env.reporter.reportRunnerResults(this);
1855 | };
1856 |
1857 | jasmine.Runner.prototype.addSuite = function(suite) {
1858 | this.suites_.push(suite);
1859 | };
1860 |
1861 | jasmine.Runner.prototype.add = function(block) {
1862 | if (block instanceof jasmine.Suite) {
1863 | this.addSuite(block);
1864 | }
1865 | this.queue.add(block);
1866 | };
1867 |
1868 | jasmine.Runner.prototype.specs = function () {
1869 | var suites = this.suites();
1870 | var specs = [];
1871 | for (var i = 0; i < suites.length; i++) {
1872 | specs = specs.concat(suites[i].specs());
1873 | }
1874 | return specs;
1875 | };
1876 |
1877 | jasmine.Runner.prototype.suites = function() {
1878 | return this.suites_;
1879 | };
1880 |
1881 | jasmine.Runner.prototype.topLevelSuites = function() {
1882 | var topLevelSuites = [];
1883 | for (var i = 0; i < this.suites_.length; i++) {
1884 | if (!this.suites_[i].parentSuite) {
1885 | topLevelSuites.push(this.suites_[i]);
1886 | }
1887 | }
1888 | return topLevelSuites;
1889 | };
1890 |
1891 | jasmine.Runner.prototype.results = function() {
1892 | return this.queue.results();
1893 | };
1894 | /**
1895 | * Internal representation of a Jasmine specification, or test.
1896 | *
1897 | * @constructor
1898 | * @param {jasmine.Env} env
1899 | * @param {jasmine.Suite} suite
1900 | * @param {String} description
1901 | */
1902 | jasmine.Spec = function(env, suite, description) {
1903 | if (!env) {
1904 | throw new Error('jasmine.Env() required');
1905 | }
1906 | if (!suite) {
1907 | throw new Error('jasmine.Suite() required');
1908 | }
1909 | var spec = this;
1910 | spec.id = env.nextSpecId ? env.nextSpecId() : null;
1911 | spec.env = env;
1912 | spec.suite = suite;
1913 | spec.description = description;
1914 | spec.queue = new jasmine.Queue(env);
1915 |
1916 | spec.afterCallbacks = [];
1917 | spec.spies_ = [];
1918 |
1919 | spec.results_ = new jasmine.NestedResults();
1920 | spec.results_.description = description;
1921 | spec.matchersClass = null;
1922 | };
1923 |
1924 | jasmine.Spec.prototype.getFullName = function() {
1925 | return this.suite.getFullName() + ' ' + this.description + '.';
1926 | };
1927 |
1928 |
1929 | jasmine.Spec.prototype.results = function() {
1930 | return this.results_;
1931 | };
1932 |
1933 | /**
1934 | * All parameters are pretty-printed and concatenated together, then written to the spec's output.
1935 | *
1936 | * Be careful not to leave calls to jasmine.log in production code.
1937 | */
1938 | jasmine.Spec.prototype.log = function() {
1939 | return this.results_.log(arguments);
1940 | };
1941 |
1942 | jasmine.Spec.prototype.runs = function (func) {
1943 | var block = new jasmine.Block(this.env, func, this);
1944 | this.addToQueue(block);
1945 | return this;
1946 | };
1947 |
1948 | jasmine.Spec.prototype.addToQueue = function (block) {
1949 | if (this.queue.isRunning()) {
1950 | this.queue.insertNext(block);
1951 | } else {
1952 | this.queue.add(block);
1953 | }
1954 | };
1955 |
1956 | /**
1957 | * @param {jasmine.ExpectationResult} result
1958 | */
1959 | jasmine.Spec.prototype.addMatcherResult = function(result) {
1960 | this.results_.addResult(result);
1961 | };
1962 |
1963 | jasmine.Spec.prototype.expect = function(actual) {
1964 | var positive = new (this.getMatchersClass_())(this.env, actual, this);
1965 | positive.not = new (this.getMatchersClass_())(this.env, actual, this, true);
1966 | return positive;
1967 | };
1968 |
1969 | /**
1970 | * Waits a fixed time period before moving to the next block.
1971 | *
1972 | * @deprecated Use waitsFor() instead
1973 | * @param {Number} timeout milliseconds to wait
1974 | */
1975 | jasmine.Spec.prototype.waits = function(timeout) {
1976 | var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this);
1977 | this.addToQueue(waitsFunc);
1978 | return this;
1979 | };
1980 |
1981 | /**
1982 | * Waits for the latchFunction to return true before proceeding to the next block.
1983 | *
1984 | * @param {Function} latchFunction
1985 | * @param {String} optional_timeoutMessage
1986 | * @param {Number} optional_timeout
1987 | */
1988 | jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
1989 | var latchFunction_ = null;
1990 | var optional_timeoutMessage_ = null;
1991 | var optional_timeout_ = null;
1992 |
1993 | for (var i = 0; i < arguments.length; i++) {
1994 | var arg = arguments[i];
1995 | switch (typeof arg) {
1996 | case 'function':
1997 | latchFunction_ = arg;
1998 | break;
1999 | case 'string':
2000 | optional_timeoutMessage_ = arg;
2001 | break;
2002 | case 'number':
2003 | optional_timeout_ = arg;
2004 | break;
2005 | }
2006 | }
2007 |
2008 | var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this);
2009 | this.addToQueue(waitsForFunc);
2010 | return this;
2011 | };
2012 |
2013 | jasmine.Spec.prototype.fail = function (e) {
2014 | var expectationResult = new jasmine.ExpectationResult({
2015 | passed: false,
2016 | message: e ? jasmine.util.formatException(e) : 'Exception',
2017 | trace: { stack: e.stack }
2018 | });
2019 | this.results_.addResult(expectationResult);
2020 | };
2021 |
2022 | jasmine.Spec.prototype.getMatchersClass_ = function() {
2023 | return this.matchersClass || this.env.matchersClass;
2024 | };
2025 |
2026 | jasmine.Spec.prototype.addMatchers = function(matchersPrototype) {
2027 | var parent = this.getMatchersClass_();
2028 | var newMatchersClass = function() {
2029 | parent.apply(this, arguments);
2030 | };
2031 | jasmine.util.inherit(newMatchersClass, parent);
2032 | jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass);
2033 | this.matchersClass = newMatchersClass;
2034 | };
2035 |
2036 | jasmine.Spec.prototype.finishCallback = function() {
2037 | this.env.reporter.reportSpecResults(this);
2038 | };
2039 |
2040 | jasmine.Spec.prototype.finish = function(onComplete) {
2041 | this.removeAllSpies();
2042 | this.finishCallback();
2043 | if (onComplete) {
2044 | onComplete();
2045 | }
2046 | };
2047 |
2048 | jasmine.Spec.prototype.after = function(doAfter) {
2049 | if (this.queue.isRunning()) {
2050 | this.queue.add(new jasmine.Block(this.env, doAfter, this));
2051 | } else {
2052 | this.afterCallbacks.unshift(doAfter);
2053 | }
2054 | };
2055 |
2056 | jasmine.Spec.prototype.execute = function(onComplete) {
2057 | var spec = this;
2058 | if (!spec.env.specFilter(spec)) {
2059 | spec.results_.skipped = true;
2060 | spec.finish(onComplete);
2061 | return;
2062 | }
2063 |
2064 | this.env.reporter.reportSpecStarting(this);
2065 |
2066 | spec.env.currentSpec = spec;
2067 |
2068 | spec.addBeforesAndAftersToQueue();
2069 |
2070 | spec.queue.start(function () {
2071 | spec.finish(onComplete);
2072 | });
2073 | };
2074 |
2075 | jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() {
2076 | var runner = this.env.currentRunner();
2077 | var i;
2078 |
2079 | for (var suite = this.suite; suite; suite = suite.parentSuite) {
2080 | for (i = 0; i < suite.before_.length; i++) {
2081 | this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this));
2082 | }
2083 | }
2084 | for (i = 0; i < runner.before_.length; i++) {
2085 | this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this));
2086 | }
2087 | for (i = 0; i < this.afterCallbacks.length; i++) {
2088 | this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this));
2089 | }
2090 | for (suite = this.suite; suite; suite = suite.parentSuite) {
2091 | for (i = 0; i < suite.after_.length; i++) {
2092 | this.queue.add(new jasmine.Block(this.env, suite.after_[i], this));
2093 | }
2094 | }
2095 | for (i = 0; i < runner.after_.length; i++) {
2096 | this.queue.add(new jasmine.Block(this.env, runner.after_[i], this));
2097 | }
2098 | };
2099 |
2100 | jasmine.Spec.prototype.explodes = function() {
2101 | throw 'explodes function should not have been called';
2102 | };
2103 |
2104 | jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) {
2105 | if (obj == jasmine.undefined) {
2106 | throw "spyOn could not find an object to spy upon for " + methodName + "()";
2107 | }
2108 |
2109 | if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) {
2110 | throw methodName + '() method does not exist';
2111 | }
2112 |
2113 | if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) {
2114 | throw new Error(methodName + ' has already been spied upon');
2115 | }
2116 |
2117 | var spyObj = jasmine.createSpy(methodName);
2118 |
2119 | this.spies_.push(spyObj);
2120 | spyObj.baseObj = obj;
2121 | spyObj.methodName = methodName;
2122 | spyObj.originalValue = obj[methodName];
2123 |
2124 | obj[methodName] = spyObj;
2125 |
2126 | return spyObj;
2127 | };
2128 |
2129 | jasmine.Spec.prototype.removeAllSpies = function() {
2130 | for (var i = 0; i < this.spies_.length; i++) {
2131 | var spy = this.spies_[i];
2132 | spy.baseObj[spy.methodName] = spy.originalValue;
2133 | }
2134 | this.spies_ = [];
2135 | };
2136 |
2137 | /**
2138 | * Internal representation of a Jasmine suite.
2139 | *
2140 | * @constructor
2141 | * @param {jasmine.Env} env
2142 | * @param {String} description
2143 | * @param {Function} specDefinitions
2144 | * @param {jasmine.Suite} parentSuite
2145 | */
2146 | jasmine.Suite = function(env, description, specDefinitions, parentSuite) {
2147 | var self = this;
2148 | self.id = env.nextSuiteId ? env.nextSuiteId() : null;
2149 | self.description = description;
2150 | self.queue = new jasmine.Queue(env);
2151 | self.parentSuite = parentSuite;
2152 | self.env = env;
2153 | self.before_ = [];
2154 | self.after_ = [];
2155 | self.children_ = [];
2156 | self.suites_ = [];
2157 | self.specs_ = [];
2158 | };
2159 |
2160 | jasmine.Suite.prototype.getFullName = function() {
2161 | var fullName = this.description;
2162 | for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) {
2163 | fullName = parentSuite.description + ' ' + fullName;
2164 | }
2165 | return fullName;
2166 | };
2167 |
2168 | jasmine.Suite.prototype.finish = function(onComplete) {
2169 | this.env.reporter.reportSuiteResults(this);
2170 | this.finished = true;
2171 | if (typeof(onComplete) == 'function') {
2172 | onComplete();
2173 | }
2174 | };
2175 |
2176 | jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) {
2177 | beforeEachFunction.typeName = 'beforeEach';
2178 | this.before_.unshift(beforeEachFunction);
2179 | };
2180 |
2181 | jasmine.Suite.prototype.afterEach = function(afterEachFunction) {
2182 | afterEachFunction.typeName = 'afterEach';
2183 | this.after_.unshift(afterEachFunction);
2184 | };
2185 |
2186 | jasmine.Suite.prototype.results = function() {
2187 | return this.queue.results();
2188 | };
2189 |
2190 | jasmine.Suite.prototype.add = function(suiteOrSpec) {
2191 | this.children_.push(suiteOrSpec);
2192 | if (suiteOrSpec instanceof jasmine.Suite) {
2193 | this.suites_.push(suiteOrSpec);
2194 | this.env.currentRunner().addSuite(suiteOrSpec);
2195 | } else {
2196 | this.specs_.push(suiteOrSpec);
2197 | }
2198 | this.queue.add(suiteOrSpec);
2199 | };
2200 |
2201 | jasmine.Suite.prototype.specs = function() {
2202 | return this.specs_;
2203 | };
2204 |
2205 | jasmine.Suite.prototype.suites = function() {
2206 | return this.suites_;
2207 | };
2208 |
2209 | jasmine.Suite.prototype.children = function() {
2210 | return this.children_;
2211 | };
2212 |
2213 | jasmine.Suite.prototype.execute = function(onComplete) {
2214 | var self = this;
2215 | this.queue.start(function () {
2216 | self.finish(onComplete);
2217 | });
2218 | };
2219 | jasmine.WaitsBlock = function(env, timeout, spec) {
2220 | this.timeout = timeout;
2221 | jasmine.Block.call(this, env, null, spec);
2222 | };
2223 |
2224 | jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block);
2225 |
2226 | jasmine.WaitsBlock.prototype.execute = function (onComplete) {
2227 | if (jasmine.VERBOSE) {
2228 | this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...');
2229 | }
2230 | this.env.setTimeout(function () {
2231 | onComplete();
2232 | }, this.timeout);
2233 | };
2234 | /**
2235 | * A block which waits for some condition to become true, with timeout.
2236 | *
2237 | * @constructor
2238 | * @extends jasmine.Block
2239 | * @param {jasmine.Env} env The Jasmine environment.
2240 | * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true.
2241 | * @param {Function} latchFunction A function which returns true when the desired condition has been met.
2242 | * @param {String} message The message to display if the desired condition hasn't been met within the given time period.
2243 | * @param {jasmine.Spec} spec The Jasmine spec.
2244 | */
2245 | jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) {
2246 | this.timeout = timeout || env.defaultTimeoutInterval;
2247 | this.latchFunction = latchFunction;
2248 | this.message = message;
2249 | this.totalTimeSpentWaitingForLatch = 0;
2250 | jasmine.Block.call(this, env, null, spec);
2251 | };
2252 | jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block);
2253 |
2254 | jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10;
2255 |
2256 | jasmine.WaitsForBlock.prototype.execute = function(onComplete) {
2257 | if (jasmine.VERBOSE) {
2258 | this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen'));
2259 | }
2260 | var latchFunctionResult;
2261 | try {
2262 | latchFunctionResult = this.latchFunction.apply(this.spec);
2263 | } catch (e) {
2264 | this.spec.fail(e);
2265 | onComplete();
2266 | return;
2267 | }
2268 |
2269 | if (latchFunctionResult) {
2270 | onComplete();
2271 | } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) {
2272 | var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen');
2273 | this.spec.fail({
2274 | name: 'timeout',
2275 | message: message
2276 | });
2277 |
2278 | this.abort = true;
2279 | onComplete();
2280 | } else {
2281 | this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT;
2282 | var self = this;
2283 | this.env.setTimeout(function() {
2284 | self.execute(onComplete);
2285 | }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT);
2286 | }
2287 | };
2288 | // Mock setTimeout, clearTimeout
2289 | // Contributed by Pivotal Computer Systems, www.pivotalsf.com
2290 |
2291 | jasmine.FakeTimer = function() {
2292 | this.reset();
2293 |
2294 | var self = this;
2295 | self.setTimeout = function(funcToCall, millis) {
2296 | self.timeoutsMade++;
2297 | self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false);
2298 | return self.timeoutsMade;
2299 | };
2300 |
2301 | self.setInterval = function(funcToCall, millis) {
2302 | self.timeoutsMade++;
2303 | self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true);
2304 | return self.timeoutsMade;
2305 | };
2306 |
2307 | self.clearTimeout = function(timeoutKey) {
2308 | self.scheduledFunctions[timeoutKey] = jasmine.undefined;
2309 | };
2310 |
2311 | self.clearInterval = function(timeoutKey) {
2312 | self.scheduledFunctions[timeoutKey] = jasmine.undefined;
2313 | };
2314 |
2315 | };
2316 |
2317 | jasmine.FakeTimer.prototype.reset = function() {
2318 | this.timeoutsMade = 0;
2319 | this.scheduledFunctions = {};
2320 | this.nowMillis = 0;
2321 | };
2322 |
2323 | jasmine.FakeTimer.prototype.tick = function(millis) {
2324 | var oldMillis = this.nowMillis;
2325 | var newMillis = oldMillis + millis;
2326 | this.runFunctionsWithinRange(oldMillis, newMillis);
2327 | this.nowMillis = newMillis;
2328 | };
2329 |
2330 | jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) {
2331 | var scheduledFunc;
2332 | var funcsToRun = [];
2333 | for (var timeoutKey in this.scheduledFunctions) {
2334 | scheduledFunc = this.scheduledFunctions[timeoutKey];
2335 | if (scheduledFunc != jasmine.undefined &&
2336 | scheduledFunc.runAtMillis >= oldMillis &&
2337 | scheduledFunc.runAtMillis <= nowMillis) {
2338 | funcsToRun.push(scheduledFunc);
2339 | this.scheduledFunctions[timeoutKey] = jasmine.undefined;
2340 | }
2341 | }
2342 |
2343 | if (funcsToRun.length > 0) {
2344 | funcsToRun.sort(function(a, b) {
2345 | return a.runAtMillis - b.runAtMillis;
2346 | });
2347 | for (var i = 0; i < funcsToRun.length; ++i) {
2348 | try {
2349 | var funcToRun = funcsToRun[i];
2350 | this.nowMillis = funcToRun.runAtMillis;
2351 | funcToRun.funcToCall();
2352 | if (funcToRun.recurring) {
2353 | this.scheduleFunction(funcToRun.timeoutKey,
2354 | funcToRun.funcToCall,
2355 | funcToRun.millis,
2356 | true);
2357 | }
2358 | } catch(e) {
2359 | }
2360 | }
2361 | this.runFunctionsWithinRange(oldMillis, nowMillis);
2362 | }
2363 | };
2364 |
2365 | jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) {
2366 | this.scheduledFunctions[timeoutKey] = {
2367 | runAtMillis: this.nowMillis + millis,
2368 | funcToCall: funcToCall,
2369 | recurring: recurring,
2370 | timeoutKey: timeoutKey,
2371 | millis: millis
2372 | };
2373 | };
2374 |
2375 | /**
2376 | * @namespace
2377 | */
2378 | jasmine.Clock = {
2379 | defaultFakeTimer: new jasmine.FakeTimer(),
2380 |
2381 | reset: function() {
2382 | jasmine.Clock.assertInstalled();
2383 | jasmine.Clock.defaultFakeTimer.reset();
2384 | },
2385 |
2386 | tick: function(millis) {
2387 | jasmine.Clock.assertInstalled();
2388 | jasmine.Clock.defaultFakeTimer.tick(millis);
2389 | },
2390 |
2391 | runFunctionsWithinRange: function(oldMillis, nowMillis) {
2392 | jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis);
2393 | },
2394 |
2395 | scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) {
2396 | jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring);
2397 | },
2398 |
2399 | useMock: function() {
2400 | if (!jasmine.Clock.isInstalled()) {
2401 | var spec = jasmine.getEnv().currentSpec;
2402 | spec.after(jasmine.Clock.uninstallMock);
2403 |
2404 | jasmine.Clock.installMock();
2405 | }
2406 | },
2407 |
2408 | installMock: function() {
2409 | jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer;
2410 | },
2411 |
2412 | uninstallMock: function() {
2413 | jasmine.Clock.assertInstalled();
2414 | jasmine.Clock.installed = jasmine.Clock.real;
2415 | },
2416 |
2417 | real: {
2418 | setTimeout: jasmine.getGlobal().setTimeout,
2419 | clearTimeout: jasmine.getGlobal().clearTimeout,
2420 | setInterval: jasmine.getGlobal().setInterval,
2421 | clearInterval: jasmine.getGlobal().clearInterval
2422 | },
2423 |
2424 | assertInstalled: function() {
2425 | if (!jasmine.Clock.isInstalled()) {
2426 | throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()");
2427 | }
2428 | },
2429 |
2430 | isInstalled: function() {
2431 | return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer;
2432 | },
2433 |
2434 | installed: null
2435 | };
2436 | jasmine.Clock.installed = jasmine.Clock.real;
2437 |
2438 | //else for IE support
2439 | jasmine.getGlobal().setTimeout = function(funcToCall, millis) {
2440 | if (jasmine.Clock.installed.setTimeout.apply) {
2441 | return jasmine.Clock.installed.setTimeout.apply(this, arguments);
2442 | } else {
2443 | return jasmine.Clock.installed.setTimeout(funcToCall, millis);
2444 | }
2445 | };
2446 |
2447 | jasmine.getGlobal().setInterval = function(funcToCall, millis) {
2448 | if (jasmine.Clock.installed.setInterval.apply) {
2449 | return jasmine.Clock.installed.setInterval.apply(this, arguments);
2450 | } else {
2451 | return jasmine.Clock.installed.setInterval(funcToCall, millis);
2452 | }
2453 | };
2454 |
2455 | jasmine.getGlobal().clearTimeout = function(timeoutKey) {
2456 | if (jasmine.Clock.installed.clearTimeout.apply) {
2457 | return jasmine.Clock.installed.clearTimeout.apply(this, arguments);
2458 | } else {
2459 | return jasmine.Clock.installed.clearTimeout(timeoutKey);
2460 | }
2461 | };
2462 |
2463 | jasmine.getGlobal().clearInterval = function(timeoutKey) {
2464 | if (jasmine.Clock.installed.clearTimeout.apply) {
2465 | return jasmine.Clock.installed.clearInterval.apply(this, arguments);
2466 | } else {
2467 | return jasmine.Clock.installed.clearInterval(timeoutKey);
2468 | }
2469 | };
2470 |
2471 | jasmine.version_= {
2472 | "major": 1,
2473 | "minor": 1,
2474 | "build": 0,
2475 | "revision": 1315677058
2476 | };
2477 |
--------------------------------------------------------------------------------