46 |
47 |
48 |
--------------------------------------------------------------------------------
/grunt.js:
--------------------------------------------------------------------------------
1 | /*global module:false*/
2 | module.exports = function(grunt) {
3 |
4 | // Project configuration.
5 | grunt.initConfig({
6 | pkg: '',
7 | meta: {
8 | banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
9 | '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
10 | '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
11 | '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
12 | ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
13 | },
14 | concat: {
15 | dist: {
16 | src: ['', '.js>'],
17 | dest: 'dist/<%= pkg.name %>.js'
18 | }
19 | },
20 | min: {
21 | dist: {
22 | src: ['', ''],
23 | dest: 'dist/<%= pkg.name %>.min.js'
24 | }
25 | },
26 | qunit: {
27 | files: ['test/**/*.html']
28 | },
29 | lint: {
30 | files: ['grunt.js', 'src/**/!(ba-linkify)*.js', 'test/**/*.js']
31 | },
32 | watch: {
33 | files: '',
34 | tasks: 'lint qunit'
35 | },
36 | jshint: {
37 | options: {
38 | curly: true,
39 | eqeqeq: true,
40 | immed: true,
41 | latedef: true,
42 | newcap: true,
43 | noarg: true,
44 | sub: true,
45 | undef: true,
46 | boss: true,
47 | eqnull: true,
48 | browser: true
49 | },
50 | globals: {
51 | jQuery: true
52 | }
53 | },
54 | uglify: {}
55 | });
56 |
57 | // Default task.
58 | grunt.registerTask('default', 'lint qunit concat min');
59 |
60 | };
--------------------------------------------------------------------------------
/dist/jquery.twitter.min.js:
--------------------------------------------------------------------------------
1 | /*! jQuery Twitter Plugin - v0.3 - 2012-12-24
2 | * https://github.com/boazsender/jQuery-Twitter-Plugin
3 | * Copyright (c) 2012 Boaz Sender; Licensed MIT, GPL */
4 | var linkify=linkify||function(){};(function(a,b){var c=function(a){return a.replace(/[@]+[a-z0\-9-_]+/ig,function(a){return a.link("http://twitter.com/"+a.replace("@",""))})},d=function(a){return a.replace(/[#]+[a-z0\-9-_]+/ig,function(a){return a.link("http://search.twitter.com/search?q="+a.replace("#","%23"))})},e={media:function(a,b){return e.urls(a,b)},urls:function(a,b){return""+b.display_url+""},user_mentions:function(a,b){return"@"+b.screen_name+""},hashtags:function(a,b){return"#"+b.text+""}},f=function(b){var c=b.text,d=[];return a.each(b.entities,function(b,c){a.each(c,function(a,c){c.type=b}),d=d.concat(c)}),d.sort(function(a,b){return a.indices[0]"),l=0,m;if(e.results&&e.results.length){for(m in e.results){var n=e.results[m],o=!i.replies&&n.to_user_id?!1:!0,p=!i.retweets&&n.text.slice(0,2)==="RT"?!1:!0;if(!o)continue;if(!p)continue;if(j&&j.test(n.text))continue;var q=a("",{"class":"tweet"});i.avatar===!0&&q.append(a("",{href:"http://twitter.com/"+n.from_user,html:""}));var r="@"+n.from_user+": ";i.include_entities?r+=f(n):r+=c(d(b(n.text))),q.append(a("",{"class":"content",html:r})).appendTo(k),l++;if(l===i.limit)break}h.html(k),g&&g(!0)}else h.html(a("",{"class":"twitter-notFound",text:i.notFoundText})),g&&g(!1)})}):this},a.twitter.opts={limit:7,exclusions:"",notFoundText:"No results found on twitter",replies:!0,retweets:!0,ands:"",phrase:"",ors:"",nots:"",tag:"",lang:"",from:"",to:"",ref:"",near:"",within:"",units:"",since:"",until:"",tude:"",filter:"",include:"",rpp:5,q:"",avatar:!0,include_entities:!0}})(jQuery,linkify);
--------------------------------------------------------------------------------
/libs/qunit/qunit.css:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.7.0pre - A JavaScript Unit Testing Framework
3 | *
4 | * http://docs.jquery.com/QUnit
5 | *
6 | * Copyright (c) 2012 John Resig, Jörn Zaefferer
7 | * Dual licensed under the MIT (MIT-LICENSE.txt)
8 | * or GPL (GPL-LICENSE.txt) licenses.
9 | */
10 |
11 | /** Font Family and Sizes */
12 |
13 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
14 | font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
15 | }
16 |
17 | #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
18 | #qunit-tests { font-size: smaller; }
19 |
20 |
21 | /** Resets */
22 |
23 | #qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
24 | margin: 0;
25 | padding: 0;
26 | }
27 |
28 |
29 | /** Header */
30 |
31 | #qunit-header {
32 | padding: 0.5em 0 0.5em 1em;
33 |
34 | color: #8699a4;
35 | background-color: #0d3349;
36 |
37 | font-size: 1.5em;
38 | line-height: 1em;
39 | font-weight: normal;
40 |
41 | border-radius: 15px 15px 0 0;
42 | -moz-border-radius: 15px 15px 0 0;
43 | -webkit-border-top-right-radius: 15px;
44 | -webkit-border-top-left-radius: 15px;
45 | }
46 |
47 | #qunit-header a {
48 | text-decoration: none;
49 | color: #c2ccd1;
50 | }
51 |
52 | #qunit-header a:hover,
53 | #qunit-header a:focus {
54 | color: #fff;
55 | }
56 |
57 | #qunit-header label {
58 | display: inline-block;
59 | padding-left: 0.5em;
60 | }
61 |
62 | #qunit-banner {
63 | height: 5px;
64 | }
65 |
66 | #qunit-testrunner-toolbar {
67 | padding: 0.5em 0 0.5em 2em;
68 | color: #5E740B;
69 | background-color: #eee;
70 | }
71 |
72 | #qunit-userAgent {
73 | padding: 0.5em 0 0.5em 2.5em;
74 | background-color: #2b81af;
75 | color: #fff;
76 | text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
77 | }
78 |
79 |
80 | /** Tests: Pass/Fail */
81 |
82 | #qunit-tests {
83 | list-style-position: inside;
84 | }
85 |
86 | #qunit-tests li {
87 | padding: 0.4em 0.5em 0.4em 2.5em;
88 | border-bottom: 1px solid #fff;
89 | list-style-position: inside;
90 | }
91 |
92 | #qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running {
93 | display: none;
94 | }
95 |
96 | #qunit-tests li strong {
97 | cursor: pointer;
98 | }
99 |
100 | #qunit-tests li a {
101 | padding: 0.5em;
102 | color: #c2ccd1;
103 | text-decoration: none;
104 | }
105 | #qunit-tests li a:hover,
106 | #qunit-tests li a:focus {
107 | color: #000;
108 | }
109 |
110 | #qunit-tests ol {
111 | margin-top: 0.5em;
112 | padding: 0.5em;
113 |
114 | background-color: #fff;
115 |
116 | border-radius: 15px;
117 | -moz-border-radius: 15px;
118 | -webkit-border-radius: 15px;
119 |
120 | box-shadow: inset 0px 2px 13px #999;
121 | -moz-box-shadow: inset 0px 2px 13px #999;
122 | -webkit-box-shadow: inset 0px 2px 13px #999;
123 | }
124 |
125 | #qunit-tests table {
126 | border-collapse: collapse;
127 | margin-top: .2em;
128 | }
129 |
130 | #qunit-tests th {
131 | text-align: right;
132 | vertical-align: top;
133 | padding: 0 .5em 0 0;
134 | }
135 |
136 | #qunit-tests td {
137 | vertical-align: top;
138 | }
139 |
140 | #qunit-tests pre {
141 | margin: 0;
142 | white-space: pre-wrap;
143 | word-wrap: break-word;
144 | }
145 |
146 | #qunit-tests del {
147 | background-color: #e0f2be;
148 | color: #374e0c;
149 | text-decoration: none;
150 | }
151 |
152 | #qunit-tests ins {
153 | background-color: #ffcaca;
154 | color: #500;
155 | text-decoration: none;
156 | }
157 |
158 | /*** Test Counts */
159 |
160 | #qunit-tests b.counts { color: black; }
161 | #qunit-tests b.passed { color: #5E740B; }
162 | #qunit-tests b.failed { color: #710909; }
163 |
164 | #qunit-tests li li {
165 | margin: 0.5em;
166 | padding: 0.4em 0.5em 0.4em 0.5em;
167 | background-color: #fff;
168 | border-bottom: none;
169 | list-style-position: inside;
170 | }
171 |
172 | /*** Passing Styles */
173 |
174 | #qunit-tests li li.pass {
175 | color: #5E740B;
176 | background-color: #fff;
177 | border-left: 26px solid #C6E746;
178 | }
179 |
180 | #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
181 | #qunit-tests .pass .test-name { color: #366097; }
182 |
183 | #qunit-tests .pass .test-actual,
184 | #qunit-tests .pass .test-expected { color: #999999; }
185 |
186 | #qunit-banner.qunit-pass { background-color: #C6E746; }
187 |
188 | /*** Failing Styles */
189 |
190 | #qunit-tests li li.fail {
191 | color: #710909;
192 | background-color: #fff;
193 | border-left: 26px solid #EE5757;
194 | white-space: pre;
195 | }
196 |
197 | #qunit-tests > li:last-child {
198 | border-radius: 0 0 15px 15px;
199 | -moz-border-radius: 0 0 15px 15px;
200 | -webkit-border-bottom-right-radius: 15px;
201 | -webkit-border-bottom-left-radius: 15px;
202 | }
203 |
204 | #qunit-tests .fail { color: #000000; background-color: #EE5757; }
205 | #qunit-tests .fail .test-name,
206 | #qunit-tests .fail .module-name { color: #000000; }
207 |
208 | #qunit-tests .fail .test-actual { color: #EE5757; }
209 | #qunit-tests .fail .test-expected { color: green; }
210 |
211 | #qunit-banner.qunit-fail { background-color: #EE5757; }
212 |
213 |
214 | /** Result */
215 |
216 | #qunit-testresult {
217 | padding: 0.5em 0.5em 0.5em 2.5em;
218 |
219 | color: #2b81af;
220 | background-color: #D2E0E6;
221 |
222 | border-bottom: 1px solid white;
223 | }
224 | #qunit-testresult .module-name {
225 | font-weight: bold;
226 | }
227 |
228 | /** Fixture */
229 |
230 | #qunit-fixture {
231 | position: absolute;
232 | top: -10000px;
233 | left: -10000px;
234 | width: 1000px;
235 | height: 1000px;
236 | }
237 |
--------------------------------------------------------------------------------
/test/jquery.twitter_test.js:
--------------------------------------------------------------------------------
1 | /*global QUnit:true, module:true, test:true, asyncTest:true, expect:true*/
2 | /*global start:true, stop:true ok:true, equal:true, notEqual:true, deepEqual:true*/
3 | /*global notDeepEqual:true, strictEqual:true, notStrictEqual:true, raises:true*/
4 | (function($) {
5 |
6 | $(function(){
7 | var flags = [];
8 |
9 | $("#testlist1").twitter({
10 | from:"mediatemple",
11 | rpp: 2
12 | });
13 |
14 | $("#testlist2").twitter({
15 | from:"whatever",
16 | limit:0,
17 | notFoundText: "Whoops, no results"
18 | });
19 |
20 | $("#testlist3").twitter("ikjn gt oidfbgjldkfobnidfjoh;bikdjfkbhjfldldfj");
21 |
22 | $("#testlist4").twitter({
23 | ands : "", // All of these words
24 | phrase : "", // This exact phrase
25 | ors : "lol rotfl", // Any of these words
26 | nots : "dirty", // None of these words
27 | tag : "omg", // This hashtag
28 | rpp : 4 // Results per page
29 | });
30 |
31 | $("#testlist5").twitter({
32 | from : "rwaldron", // From this person
33 | replies: false,
34 | retweets: false,
35 | rpp : 4, // Results per page
36 | avatar : false
37 | });
38 |
39 | // Temporarily replace $.twitter with a mock version that returns a pre-defined result
40 | $.oTwitter = $.twitter;
41 | $.twitter = function( options, callback ) {
42 | var tweets = {
43 | "results" : [{
44 | "from_user": "mediatemple",
45 | "text": "This text contains a @mention and a #hashtag"
46 | }]
47 | };
48 | callback( tweets, {}, null );
49 | };
50 |
51 | $("#testlist6").twitter({ from: "mediatemple" });
52 |
53 | // Replace original $.twitter function
54 | $.twitter = $.oTwitter;
55 | delete $.oTwitter;
56 |
57 | module("$.twitter()");
58 | test("Test the async", function() {
59 |
60 | stop();
61 |
62 | $.twitter("foo", function(tweets){
63 | equal( (typeof tweets), "object", "$.twitter('foo') returns an object" );
64 |
65 | });
66 |
67 | $.twitter({from : "mediatemple"}, function(tweets){
68 | equal( tweets.results[0].from_user, "mediatemple", "$.twitter({from : 'mediatemple'}) returns tweets from @mediatemple" );
69 |
70 | });
71 |
72 | $.twitter({from : "mediatemple", replies: false}, function(tweets){
73 | equal( tweets.results[0].from_user, "mediatemple", "$.twitter({from : 'mediatemple'}) returns tweets from @mediatemple with replies set to false" );
74 |
75 | });
76 |
77 | $.twitter({from : "mediatemple", retweets: false}, function(tweets){
78 | equal( tweets.results[0].from_user, "mediatemple", "$.twitter({from : 'mediatemple'}) returns tweets from @mediatemple with retweets set to false" );
79 |
80 | });
81 |
82 | setTimeout(function(){
83 | start();
84 | }, 2000);
85 |
86 | });
87 |
88 |
89 | test("Test the signatures", function() {
90 |
91 | ok($.isFunction($.twitter), "$.twitter exists and is a function" );
92 |
93 | equal( $.twitter(), false, "$.twitter() returns false if you pass it nothing" );
94 |
95 | });
96 |
97 | module("$.fn.twitter()");
98 | test("Test the signatures", function() {
99 |
100 | ok($.isFunction($.fn.twitter), "$.fn.twitter exists and is a function" );
101 |
102 | equal( (typeof $.fn.twitter({})), "object", "$.fn.twitter({}) returns an object" );
103 | equal( (typeof $.fn.twitter({}).selector), "string", "$.fn.twitter({}) returns an object" );
104 |
105 | equal( (typeof $.fn.twitter("foo")), "object", "$.fn.twitter('foo') returns an object" );
106 | equal( (typeof $.fn.twitter("foo").selector), "string", "$.fn.twitter('foo') returns an object" );
107 |
108 | equal( (typeof $.fn.twitter()), "object", "$.fn.twitter() returns an object" );
109 | equal( (typeof $.fn.twitter().selector), "string", "$.fn.twitter() returns an object" );
110 |
111 | equal( (typeof $.fn.twitter(null)), "object", "$.fn.twitter(null) returns an object" );
112 | equal( (typeof $.fn.twitter(null).selector), "string", "$.fn.twitter(null) returns an object" );
113 |
114 | equal( (typeof $.fn.twitter(undefined)), "object", "$.fn.twitter(null) returns an object" );
115 | equal( (typeof $.fn.twitter(undefined).selector), "string", "$.fn.twitter(null) returns an object" );
116 |
117 | });
118 | test("Test twitter list that is built", function() {
119 |
120 |
121 | equal( $("#testlist1").children().length, 1, "Any element with $.fn.twitter() should have exactly one child" );
122 | equal( $("#testlist2").children().length, 1, "Any element with $.fn.twitter() should have exactly one child" );
123 | equal( $("#testlist3").children().length, 1, "Any element with $.fn.twitter() should have exactly one child" );
124 | equal( $("#testlist4").children().length, 1, "Any element with $.fn.twitter() should have exactly one child" );
125 |
126 |
127 | equal( $("#testlist1").children().children().length, 2, "The twitter list should have 2 children" );
128 | equal( $("#testlist4").children().children().length, 4, "The twitter list should have 4 children" );
129 |
130 | equal( $("#testlist1").text().match(/@/), "@", "The twitter list should have at least one @ symbol in it" );
131 |
132 | equal( $("#testlist2").text(), "Whoops, no results", "The failed search should say 'Whoops, no results'" );
133 |
134 | equal( $("#testlist3").text(), "No results found on twitter", "The failed search should default to 'No results found on twitter'" );
135 |
136 | ok($("#testlist1").children().find("a").find("img").length, "Make sure the user avatar is present and inside of an anchor" );
137 |
138 | equal( $("#testlist5").children().find("a").find("img").length, 0, "Make sure the user avatar is not present inside of an anchor when avatar option is set to false");
139 |
140 | ok($("#testlist1").children().find("span").length, "Make sure the tweet is there" );
141 |
142 | ok( $("#testlist6").children().find('a[href="http://twitter.com/mention"]').length, "Make sure @mentions are linked" );
143 |
144 | ok( $("#testlist6").children().find('a[href="http://search.twitter.com/search?q=%23hashtag"]').length, "Make sure #hashtags are linked" );
145 |
146 | });
147 | test("Test a few of the cases for the object style signature", function() {
148 |
149 | equal( $("#testlist4").text().match(/dirty/), null, "'dirty' should not show up" );
150 |
151 | equal( $("#testlist4").text().match(/o/), "o", "'I' should show up in testlist 4" );
152 |
153 | equal( $("#testlist4").text().toLowerCase().match(/omg/), "omg", "'omg' should show up in testlist 4" );
154 | });
155 |
156 | test("Test no replies, no retweets", function() {
157 |
158 | var $li = $("#testlist5 ul li"),
159 | tweets = [],
160 | replies = [],
161 | retweets = [];
162 |
163 | for ( var i = 0; i < $li.length; i++ ) {
164 | tweets.push( $.trim($( $li[i] ).text().split(":")[1]) );
165 |
166 | if ( tweets[i].indexOf("RT") === 0 ) {
167 | retweets.push(true);
168 | }
169 |
170 | if ( tweets[i].indexOf("@") === 0 ) {
171 | replies.push(true);
172 | }
173 | }
174 |
175 | equal( tweets.length, 4, "There are four tweets" );
176 | equal( retweets.length, 0, "There are no Retweets" );
177 | equal( replies.length, 0, "There are no Replies" );
178 |
179 | });
180 |
181 | asyncTest( "Test callback on the instance method", 1, function() {
182 |
183 | $("#testlist7").twitter({ from: "mediatemple" }, function( tweets ){
184 | ok( tweets, "tweets have been rendered in the dom" );
185 | start();
186 | });
187 |
188 | });
189 |
190 | });
191 |
192 | }(jQuery));
193 |
--------------------------------------------------------------------------------
/src/ba-linkify.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * JavaScript Linkify - v0.3 - 6/27/2009
3 | * http://benalman.com/projects/javascript-linkify/
4 | *
5 | * Copyright (c) 2009 "Cowboy" Ben Alman
6 | * Dual licensed under the MIT and GPL licenses.
7 | * http://benalman.com/about/license/
8 | *
9 | * Some regexps adapted from http://userscripts.org/scripts/review/7122
10 | */
11 |
12 | // Script: JavaScript Linkify: Process links in text!
13 | //
14 | // *Version: 0.3, Last updated: 6/27/2009*
15 | //
16 | // Project Home - http://benalman.com/projects/javascript-linkify/
17 | // GitHub - http://github.com/cowboy/javascript-linkify/
18 | // Source - http://github.com/cowboy/javascript-linkify/raw/master/ba-linkify.js
19 | // (Minified) - http://github.com/cowboy/javascript-linkify/raw/master/ba-linkify.min.js (2.8kb)
20 | //
21 | // About: License
22 | //
23 | // Copyright (c) 2009 "Cowboy" Ben Alman,
24 | // Dual licensed under the MIT and GPL licenses.
25 | // http://benalman.com/about/license/
26 | //
27 | // About: Examples
28 | //
29 | // This working example, complete with fully commented code, illustrates one way
30 | // in which this code can be used.
31 | //
32 | // Linkify - http://benalman.com/code/projects/javascript-linkify/examples/linkify/
33 | //
34 | // About: Support and Testing
35 | //
36 | // Information about what browsers this code has been tested in.
37 | //
38 | // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, Chrome, Opera 9.6-10.
39 | //
40 | // About: Release History
41 | //
42 | // 0.3 - (6/27/2009) Initial release
43 |
44 | // Function: linkify
45 | //
46 | // Turn text into linkified html.
47 | //
48 | // Usage:
49 | //
50 | // > var html = linkify( text [, options ] );
51 | //
52 | // Arguments:
53 | //
54 | // text - (String) Non-HTML text containing links to be parsed.
55 | // options - (Object) An optional object containing linkify parse options.
56 | //
57 | // Options:
58 | //
59 | // callback (Function) - If specified, this will be called once for each link-
60 | // or non-link-chunk with two arguments, text and href. If the chunk is
61 | // non-link, href will be omitted. If unspecified, the default linkification
62 | // callback is used.
63 | // punct_regexp (RegExp) - A RegExp that will be used to trim trailing
64 | // punctuation from links, instead of the default. If set to null, trailing
65 | // punctuation will not be trimmed.
66 | //
67 | // Returns:
68 | //
69 | // (String) An HTML string containing links.
70 |
71 | window.linkify = (function(){
72 | var
73 | SCHEME = "[a-z\\d.-]+://",
74 | IPV4 = "(?:(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])",
75 | HOSTNAME = "(?:(?:[^\\s!@#$%^&*()_=+[\\]{}\\\\|;:'\",.<>/?]+)\\.)+",
76 | TLD = "(?:ac|ad|aero|ae|af|ag|ai|al|am|an|ao|aq|arpa|ar|asia|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|biz|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|cat|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|coop|com|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|info|int|in|io|iq|ir|is|it|je|jm|jobs|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mobi|mo|mp|mq|mr|ms|mt|museum|mu|mv|mw|mx|my|mz|name|na|nc|net|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|travel|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|xn--0zwm56d|xn--11b5bs3a9aj6g|xn--80akhbyknj4f|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp|xn--kgbechtv|xn--zckzah|ye|yt|yu|za|zm|zw)",
77 | HOST_OR_IP = "(?:" + HOSTNAME + TLD + "|" + IPV4 + ")",
78 | PATH = "(?:[;/][^#?<>\\s]*)?",
79 | QUERY_FRAG = "(?:\\?[^#<>\\s]*)?(?:#[^<>\\s]*)?",
80 | URI1 = "\\b" + SCHEME + "[^<>\\s]+",
81 | URI2 = "\\b" + HOST_OR_IP + PATH + QUERY_FRAG + "(?!\\w)",
82 |
83 | MAILTO = "mailto:",
84 | EMAIL = "(?:" + MAILTO + ")?[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" + HOST_OR_IP + QUERY_FRAG + "(?!\\w)",
85 |
86 | URI_RE = new RegExp( "(?:" + URI1 + "|" + URI2 + "|" + EMAIL + ")", "ig" ),
87 | SCHEME_RE = new RegExp( "^" + SCHEME, "i" ),
88 |
89 | quotes = {
90 | "'": "`",
91 | '>': '<',
92 | ')': '(',
93 | ']': '[',
94 | '}': '{',
95 | '»': '«',
96 | '›': '‹'
97 | },
98 |
99 | default_options = {
100 | callback: function( text, href ) {
101 | return href ? '' + text + '' : text;
102 | },
103 | punct_regexp: /(?:[!?.,:;'"]|(?:&|&)(?:lt|gt|quot|apos|raquo|laquo|rsaquo|lsaquo);)$/
104 | };
105 |
106 | return function( txt, options ) {
107 | options = options || {};
108 |
109 | // Temp variables.
110 | var arr,
111 | i,
112 | link,
113 | href,
114 |
115 | // Output HTML.
116 | html = '',
117 |
118 | // Store text / link parts, in order, for re-combination.
119 | parts = [],
120 |
121 | // Used for keeping track of indices in the text.
122 | idx_prev,
123 | idx_last,
124 | idx,
125 | link_last,
126 |
127 | // Used for trimming trailing punctuation and quotes from links.
128 | matches_begin,
129 | matches_end,
130 | quote_begin,
131 | quote_end;
132 |
133 | // Initialize options.
134 | for ( i in default_options ) {
135 | if ( options[ i ] === undefined ) {
136 | options[ i ] = default_options[ i ];
137 | }
138 | }
139 |
140 | // Find links.
141 | while ( arr = URI_RE.exec( txt ) ) {
142 |
143 | link = arr[0];
144 | idx_last = URI_RE.lastIndex;
145 | idx = idx_last - link.length;
146 |
147 | // Not a link if preceded by certain characters.
148 | if ( /[\/:]/.test( txt.charAt( idx - 1 ) ) ) {
149 | continue;
150 | }
151 |
152 | // Trim trailing punctuation.
153 | do {
154 | // If no changes are made, we don't want to loop forever!
155 | link_last = link;
156 |
157 | quote_end = link.substr( -1 )
158 | quote_begin = quotes[ quote_end ];
159 |
160 | // Ending quote character?
161 | if ( quote_begin ) {
162 | matches_begin = link.match( new RegExp( '\\' + quote_begin + '(?!$)', 'g' ) );
163 | matches_end = link.match( new RegExp( '\\' + quote_end, 'g' ) );
164 |
165 | // If quotes are unbalanced, remove trailing quote character.
166 | if ( ( matches_begin ? matches_begin.length : 0 ) < ( matches_end ? matches_end.length : 0 ) ) {
167 | link = link.substr( 0, link.length - 1 );
168 | idx_last--;
169 | }
170 | }
171 |
172 | // Ending non-quote punctuation character?
173 | if ( options.punct_regexp ) {
174 | link = link.replace( options.punct_regexp, function(a){
175 | idx_last -= a.length;
176 | return '';
177 | });
178 | }
179 | } while ( link.length && link !== link_last );
180 |
181 | href = link;
182 |
183 | // Add appropriate protocol to naked links.
184 | if ( !SCHEME_RE.test( href ) ) {
185 | href = ( href.indexOf( '@' ) !== -1 ? ( !href.indexOf( MAILTO ) ? '' : MAILTO )
186 | : !href.indexOf( 'irc.' ) ? 'irc://'
187 | : !href.indexOf( 'ftp.' ) ? 'ftp://'
188 | : 'http://' )
189 | + href;
190 | }
191 |
192 | // Push preceding non-link text onto the array.
193 | if ( idx_prev != idx ) {
194 | parts.push([ txt.slice( idx_prev, idx ) ]);
195 | idx_prev = idx_last;
196 | }
197 |
198 | // Push massaged link onto the array
199 | parts.push([ link, href ]);
200 | };
201 |
202 | // Push remaining non-link text onto the array.
203 | parts.push([ txt.substr( idx_prev ) ]);
204 |
205 | // Process the array items.
206 | for ( i = 0; i < parts.length; i++ ) {
207 | html += options.callback.apply( window, parts[i] );
208 | }
209 |
210 | // In case of catastrophic failure, return the original text;
211 | return html || txt;
212 | };
213 |
214 | })();
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Warning
2 | This plugin was based on a now depricated version of the twitter API and is no longer maintained. This code doesn't work anymore. The original readme is below:
3 |
4 | # jQuery Twitter Plugin
5 | A jQuery plugin for working with the Twitter Search API to put twitter searches on websites. jQuery.twitter has a simple syntax that follows the Twitter Search API URL parameters.
6 |
7 | In addition to supporting the default Twitter Search API URL parameters, $.twitter() and $.fn.twitter() also support five options for filtering out mentions and retweets and for handling no results cases client side.
8 |
9 | ```$.fn.twitter``` creates a ```
``` of tweets for you, and puts it in the DOM. This plugin comes with a static ```$.twitter``` which ```$.fn.twitter``` uses under the hood for doing twitter searches.
10 |
11 | ## Demo
12 | We've got a handy demo up at http://bl.ocks.org/1813727
13 |
14 | ## Getting Started
15 | Download "Cowboy" Ben Alman's [JavaScript Linkify - v0.3](https://raw.github.com/cowboy/javascript-linkify/master/ba-linkify.min.js).
16 |
17 | Download the [production version][min] or the [development version][max] of jQuery.twitter.
18 |
19 | [min]: https://raw.github.com/boazsender/jQuery-Twitter-Plugin/master/dist/jquery.twitter.min.js
20 | [max]: https://raw.github.com/boazsender/jQuery-Twitter-Plugin/master/dist/jquery.twitter.js
21 |
22 | In the browser:
23 |
24 | ```
25 |
26 |
27 |
28 |
33 |
36 | ```
37 |
38 | ## Examples
39 | You can see a pretty thorough overview of this plugins usage from [this Gist](http://bl.ocks.org/1813727).
40 |
41 | ### Simple Syntax:
42 | Passing in a string to the plugin simply performs a search with that string.
43 |
44 | ```
45 | $('selector').twitter('search terms');
46 | ```
47 |
48 | ### Verbose Syntax:
49 | There are lots of options, so you could do something more like:
50 |
51 | ```
52 | $('selector').twitter({
53 | // From this person
54 | from : 'BoazSender',
55 | // Include @replies?
56 | replies : false,
57 | // All of these words
58 | ands : 'jquery bocoup',
59 | // Any of these words
60 | ors : 'gangster javascript',
61 | // None of these words
62 | nots : 'dirty words',
63 | // don't include user avatars in the list.
64 | avatar : false
65 | });
66 | ```
67 |
68 | ## Documentation
69 | The jQuery Twitter Plugin provides two methods and a public default options object:
70 |
71 | ### Static Method
72 | $.twitter(options, callback)
73 |
74 | _**options**: the string or object used to configure the search_
75 |
76 | _**callback**: the function to run when the results come back from twitter. Three arguments are passed to this callback(tweets, query, exclusionsExp)_
77 |
78 | This method allows you to get twitter results and work with the JSON response. Fore example:
79 |
80 | ```
81 | $.twitter({from: 'BoazSender', replies : false}, function(tweets){
82 | console.log(tweets);
83 | });
84 | ```
85 |
86 | ### jQuery Collection Method
87 | $.fn.twitter(options, callback)
88 |
89 | _**options**: the string or object used to configure the search_
90 |
91 | _**callback**: the function to run when the results come back from twitter. One boolean is passed to this callback. True if tweets were injected, False if no tweets were returned_
92 |
93 | This method uses $.twitter() internally to go and get the tweets you ask for, and render them in a ```
``` within each element in the jQuery collection you call it on. For example:
94 |
95 | ```
96 | $('selector').twitter('search terms', function(tweets){
97 | if(tweets){
98 | console.log('Tweets have been added');
99 | }else{
100 | console.log('Zero tweets retruned, no tweets added to the page');
101 | }
102 | });
103 | ```
104 |
105 | ### Default Options Object
106 | $.twitter.options
107 |
108 | This is the publicly available object that $.twitter() and $.fn.twitter() use to configure twitter searches. You can override it at the beginning of your code to prevent yourself from repeating configurations unnecessarily. For example:
109 |
110 | ```
111 | // Default all twitter lists to exclude @replies and dirty words
112 | $.twitter.options.replies = false;
113 |
114 | // Set a whole bunch of defaults at once
115 |
116 | $.extend($.twitter.options, {
117 | replies : false,
118 | retweets : false,
119 | limit : 20,
120 | nots : 'dirty words'
121 | });
122 | ```
123 |
124 | ### Standard Twitter Search API options
125 | You can pass the following default Twitter Search API Parameters to $.fn.twitter() as properties of the options object:
126 |
127 | * **q**: Default query
128 | * **ands**: All of these words
129 | * **phrase**: This exact phrase
130 | * **ors**: Any of these words
131 | * **nots**: None of these word
132 | * **tag**: This hashtag
133 | * **lang**: Written in language
134 | * **from**: From this person
135 | * **to**: To this person
136 | * **ref**: Referencing this person
137 | * **near**: Near this place
138 | * **within**: Within this distance
139 | * **units**: Distance unit (miles or kilometers)
140 | * **since**: Since this date
141 | * **until**: Until this date
142 | * **tude**: Attitude: '?' or ':)' or ':('
143 | * **filter**: Containing**: 'links'
144 | * **include**: Include retweet?**: 'retweets'
145 | * **rpp**: Results per page
146 | * **include_entities**: Intelligently expand media, hyperlinks, @mentions, and hashtags
147 |
148 | ### Non Standard Options
149 | In addition to supporting the default Twitter Search API URL parameters, $.fn.twitter() also supports five of it's own options for filtering out mentions and retweets and for handling no results cases client side.
150 |
151 | * **limit**: Number of tweets to get. Maps to and supersedes rpp (results per page).
152 | * **exclusions**: Space delimited list of strings (eg: '_ s gr @b'). Use this to exclude tweets containing strings that are part of a word
153 | * **avatar**: Include user avatars? true by default. (Boolean)
154 | * **notFoundText**: Text to display if no results are found
155 | * **replies**: Include replies? (Boolean)
156 | * **retweets**: Include retweets (Boolean)
157 |
158 | ## Contributing
159 | To get started contributing to jQuery.twitter.js, install [grunt](https://github.com/cowboy/grunt) globally (```$ npm install grunt -g ```).
160 |
161 | This project generally follows [Idiomatic.js](https://github.com/rwldrn/idiomatic.js) from Rick Waldron, take care to maintain the existing coding style. Add *unit tests* and *written documentation* for any new or changed functionality, and make sure all your code passes this project's grunt. This project's [gruntfile](https://github.com/boazsender/jQuery-Twitter-Plugin/blob/master/grunt.js) was generated with ```$ grunt init:jquery```.
162 |
163 | Do not edit files in the "dist" directory as they are generated via grunt. You'll find source code in the "src" subdirectory. Work inside of the src directory, and use grunt to concat/min/test/lint the code before making a pull request. Running ```$ grunt watch``` from the root of this project will do this for you as you go.
164 |
165 | ## Release History
166 |
167 | * 2012/01/22 - v0.2.1 - Added callback support to .fn.twitter, upgrading to grunt v0.3.9 and QUnit v1.7.0pre
168 | * 2012/01/22 - v0.2.0 - Moved to grunt based project organization and concat/min/lint/test, started passing lint.
169 | * 2012/01/21 - v0.1.1 - Upgraded to jQuery 1.7.1, fixed classname bug, got rid of all globals.
170 | * 2011/08/11 - v0.1.0 - Initial release.
171 |
172 | ## License
173 | Copyright (c) 2012 Boaz Sender
174 | Licensed under the MIT, GPL licenses.
175 | http://code.bocoup.com/license/
176 |
177 | jQuery-Twitter depends on [JavaScript Linkify - v0.3](https://github.com/cowboy/javascript-linkify) ([code](https://raw.github.com/cowboy/javascript-linkify/master/ba-linkify.min.js)) from "Cowboy" Ben Alman.
178 |
179 | Some of jQuery-Twitter's regexps adapted from http://userscripts.org/scripts/review/7122
180 |
181 | This project is built with "Cowboy" Ben Alman's [Grunt](https://github.com/cowboy/grunt).
182 |
183 | ## Authors
184 |
185 | * [Boaz Sender](http://github.com/boazsender)
186 | * [Rick Waldron](http://github.com/rwldrn)
187 | * [Nick Cammarata](http://github.com/ncammarata)
188 | * [Irene Ros](http://github.com/iros)
189 | * [Tyom Semonov](https://github.com/tyom)
190 | * [Adam Sontag](http://github.com/ajpiano)
191 | * [Tyler Craft](http://github.com/tylercraft)
192 |
--------------------------------------------------------------------------------
/dist/jquery.twitter.js:
--------------------------------------------------------------------------------
1 | /*! jQuery Twitter Plugin - v0.3 - 2012-12-24
2 | * https://github.com/boazsender/jQuery-Twitter-Plugin
3 | * Copyright (c) 2012 Boaz Sender; Licensed MIT, GPL */
4 |
5 | var linkify = linkify || function() {};
6 | ;(function($, linkify) {
7 |
8 | var
9 | mention = function( str ) {
10 | return str.replace(/[@]+[a-z0\-9-_]+/ig, function( username ) {
11 | return username.link("http://twitter.com/"+ username.replace("@","") );
12 | });
13 | },
14 | hashtags = function( str ) {
15 | return str.replace(/[#]+[a-z0\-9-_]+/ig, function( tag ) {
16 | return tag.link("http://search.twitter.com/search?q="+tag.replace("#","%23"));
17 | });
18 | },
19 | entityExpanders = {
20 | // Simply expand media entities as though they were hyperlinks
21 | media: function( text, mediaEntity ) {
22 | return entityExpanders.urls(text, mediaEntity);
23 | },
24 | urls: function( text, urlEntity ) {
25 | return "" +
27 | urlEntity.display_url +
28 | "";
29 | },
30 | user_mentions: function( text, userEntity ) {
31 | return "@" + userEntity.screen_name +
33 | "";
34 | },
35 | hashtags: function( text, hashtagEntity ) {
36 | return "#" + hashtagEntity.text + "";
38 | }
39 | },
40 | expandEntities = function( tweet ) {
41 | var expanded = tweet.text;
42 | var allEnts = [];
43 |
44 | // To facilitate an in-place replacement, create a flat list of all
45 | // entities, sorted in descending order according to index in the tweet.
46 | $.each(tweet.entities, function(entityType, entities) {
47 | $.each(entities, function(_, entity) {
48 | entity.type = entityType;
49 | });
50 | allEnts = allEnts.concat(entities);
51 | });
52 | allEnts.sort(function(a, b) {
53 | return a.indices[0] < b.indices[0];
54 | });
55 |
56 | $.each(allEnts, function(_, entity) {
57 | // Check for expander first in order to prevent future entities from
58 | // breaking the plugin
59 | if (entityExpanders[entity.type]) {
60 | expanded = expanded.slice(0, entity.indices[0]) +
61 | entityExpanders[entity.type](expanded, entity) +
62 | expanded.slice(entity.indices[1]);
63 | }
64 | });
65 |
66 | return expanded;
67 | };
68 |
69 | $.twitter = function (options, callback) {
70 | // Fail if the options arg is not set
71 | if ( !options ) {
72 | return false;
73 | }
74 |
75 | // Set a temporary default query object
76 | var query,
77 | // Set up a string to be used later in the case that exclusions have been set
78 | exclusionsStr = "",
79 | // Set up a regex to be used later in the case that exclusions have been set
80 | exclusionsExp = new RegExp(false);
81 |
82 | // If options is a string use it as standalone query
83 | if ( typeof options === "string" ) {
84 | query = $.extend({}, $.twitter.opts, {
85 | q: options
86 | });
87 | // Else prepare the options object to be serialized
88 | } else {
89 | // If a limit is set, add it to the query object
90 | options.rpp = options.limit ? options.limit : options.rpp;
91 |
92 | // If no limit is set, make the limit the rpp
93 | options.limit = options.limit ? options.limit : options.rpp;
94 |
95 | // If there are exlusions, turn them into a regex string
96 | exclusionsStr = options.exclusions ? options.exclusions.replace(" ", "|") : false;
97 |
98 | // If there are exlusions, turn the regex string we just made into a RegExp
99 | exclusionsExp = exclusionsStr ? new RegExp( exclusionsStr ) : false;
100 |
101 | // Make a new object that is a merger of the options passed in with the default $.twitter.opts object
102 | // and assign it to the query variable
103 | query = $.extend({}, $.twitter.opts, options);
104 |
105 | // If there are exclusions, or replies or retweets are set to false, multiply the results to ask for from twitter by ten
106 | // We need to do this so that we have some meat to work with if the exclusions are common
107 | query.rpp = query.exclusions || !query.replies || !query.retweets ? (query.rpp * 10) : query.rpp;
108 |
109 | }
110 |
111 |
112 | // Call Twitter JSONP
113 | $.getJSON("http://search.twitter.com/search.json?callback=?", query, function(tweets){
114 | callback(tweets, query, exclusionsExp);
115 | });
116 | };
117 |
118 | $.fn.twitter = function( options, callback ) {
119 | // Fail gracefully if the options arg is not set
120 | // return the jQuery obj so that chaining does not break
121 | if ( !options ) {
122 | return this;
123 | }
124 |
125 | // Begin to iterate over the jQuery collection that the method was called on
126 | return this.each(function () {
127 | // Cache `this`
128 | var $this = $(this);
129 |
130 | $.twitter(options, function( tweets, query, exclusionsExp ) {
131 | //Create and cache a new UL
132 | var $tweets = $("
"),
133 | // Create a counter variable to count up how many tweets we have rendered
134 | // unfortunately we have to do this, because exclusions, retweet booleans and replies booleans
135 | // are not supported by the Twitter Search API
136 | limitInt = 0,
137 | i;
138 |
139 | // If there are results to work with
140 | if ( tweets.results && tweets.results.length ) {
141 |
142 | // Iterate over returned tweets
143 | for ( i in tweets.results ) {
144 |
145 | // Cache tweet content
146 | var tweet = tweets.results[i],
147 | // Set a variable to determine weather replies are set to false, and if so, weather the tweet starts with a reply
148 | allowReply = !query.replies && tweet.to_user_id ? false : true,
149 | // Set a variable to determine weather retweets are set to false, and if so, weather the tweet starts with a retweet
150 | allowRetweet = !query.retweets && tweet.text.slice(0,2) === "RT" ? false : true;
151 |
152 | // Only proceed if allow reply is false
153 | if ( !allowReply ) {
154 | continue;
155 | }
156 |
157 | // Only proceed if allow retweet is false
158 | if ( !allowRetweet ) {
159 | continue;
160 | }
161 |
162 | // If exlusions set and none of the exlusions is found in the tweet then add it to the DOM
163 | if ( exclusionsExp && exclusionsExp.test(tweet.text) ) {
164 | continue;
165 | }
166 |
167 | // Create and cache new LI
168 | var $tweet = $("", {
169 | "class": "tweet"
170 | });
171 |
172 | // Make the avatar, and append it to the $tweet
173 | if ( query.avatar === true ) {
174 | $tweet.append($("", {
175 | href: "http://twitter.com/" + tweet.from_user,
176 | html: ""
177 | }));
178 | }
179 |
180 | // Make the tweet HTML
181 | var tweetHtml = "@" + tweet.from_user + ": ";
183 | if (query.include_entities) {
184 | tweetHtml += expandEntities(tweet);
185 | } else {
186 | tweetHtml += mention(hashtags(linkify(tweet.text)));
187 | }
188 |
189 | // Append the HTML to the $tweet, then to the parent
190 | $tweet.append($("", {
191 | "class": "content",
192 | html: tweetHtml
193 | }))
194 | // Append tweet to the $tweets ul
195 | .appendTo($tweets);
196 |
197 | // Count up our counter variable
198 | limitInt++;
199 |
200 | // If the counter is equal to the limit, stop rendering tweets
201 | if ( limitInt === query.limit ) {
202 | break;
203 | }
204 | }
205 |
206 | // Inject the $tweets into the DOM
207 | $this.html($tweets);
208 |
209 | if(callback){
210 | callback(true);
211 | }
212 |
213 | // Else there are no results to work with
214 | } else {
215 | // Update the DOM to reflect that no results were found
216 | $this.html($("", {
217 | "class": "twitter-notFound",
218 | text: query.notFoundText
219 | }));
220 |
221 | if(callback){
222 | callback(false);
223 | }
224 | }
225 | });
226 | });
227 | };
228 |
229 | $.twitter.opts = {
230 | // Number of tweets to get
231 | // not in twitter search api, maps to and supersedes rpp (results per page)
232 | limit: 7,
233 | // Space delimited list of strings to exclude (eg: "_ s gr @b")
234 | // not in twitter search api, done in plugin
235 | exclusions: "",
236 | // Text to display if no results are found
237 | // not in twitter search api, done in plugin
238 | notFoundText: "No results found on twitter",
239 | // Include replies?
240 | // not in twitter search api, done in plugin
241 | replies: true,
242 | // Include replies?
243 | // not in twitter search api, done in plugin
244 | retweets: true,
245 | // All of these words
246 | ands: "",
247 | // This exact phrase
248 | phrase: "",
249 | // Any of these words
250 | ors : "",
251 | // None of these words
252 | nots: "",
253 | // This hashtag
254 | tag : "",
255 | // Written in language
256 | lang: "",
257 | // From this person
258 | from: "",
259 | // To this person
260 | to: "",
261 | // Referencing this person
262 | ref: "",
263 | // Near this place
264 | near: "",
265 | // Within this distance
266 | within: "",
267 | // Distance unit (miles or kilometers)
268 | units: "",
269 | // Since this date
270 | since: "",
271 | // Until this date
272 | until: "",
273 | // Attitude: "?" or :)" or ":)"
274 | tude: "",
275 | // Containing: "links"
276 | filter: "",
277 | // Include retweet?: "retweets"
278 | include: "",
279 | // Results per page
280 | rpp: 5,
281 | // Default query
282 | q: "",
283 | // Add an avatar image of the user
284 | avatar: true,
285 | // Retrieve and replace entities
286 | include_entities: true
287 | };
288 | }(jQuery, linkify));
289 |
--------------------------------------------------------------------------------
/src/jquery.twitter.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Twitter Search Plugin jquery.twitter.js
3 | * http://code.bocoup.com/jquery-twitter-plugin/
4 | *
5 | * Copyright (c) 2010 Bocoup, LLC
6 | * Authors: Boaz Sender, Rick Waldron, Nick Cammarata
7 | * Dual licensed under the MIT and GPL licenses.
8 | * http://code.bocoup.com/license/
9 | *
10 | */
11 | var linkify = linkify || function() {};
12 | ;(function($, linkify) {
13 |
14 | var
15 | mention = function( str ) {
16 | return str.replace(/[@]+[a-z0\-9-_]+/ig, function( username ) {
17 | return username.link("http://twitter.com/"+ username.replace("@","") );
18 | });
19 | },
20 | hashtags = function( str ) {
21 | return str.replace(/[#]+[a-z0\-9-_]+/ig, function( tag ) {
22 | return tag.link("http://search.twitter.com/search?q="+tag.replace("#","%23"));
23 | });
24 | },
25 | entityExpanders = {
26 | // Simply expand media entities as though they were hyperlinks
27 | media: function( text, mediaEntity ) {
28 | return entityExpanders.urls(text, mediaEntity);
29 | },
30 | urls: function( text, urlEntity ) {
31 | return "" +
33 | urlEntity.display_url +
34 | "";
35 | },
36 | user_mentions: function( text, userEntity ) {
37 | return "@" + userEntity.screen_name +
39 | "";
40 | },
41 | hashtags: function( text, hashtagEntity ) {
42 | return "#" + hashtagEntity.text + "";
44 | }
45 | },
46 | expandEntities = function( tweet ) {
47 | var expanded = tweet.text;
48 | var allEnts = [];
49 |
50 | // To facilitate an in-place replacement, create a flat list of all
51 | // entities, sorted in descending order according to index in the tweet.
52 | $.each(tweet.entities, function(entityType, entities) {
53 | $.each(entities, function(_, entity) {
54 | entity.type = entityType;
55 | });
56 | allEnts = allEnts.concat(entities);
57 | });
58 | allEnts.sort(function(a, b) {
59 | return a.indices[0] < b.indices[0];
60 | });
61 |
62 | $.each(allEnts, function(_, entity) {
63 | // Check for expander first in order to prevent future entities from
64 | // breaking the plugin
65 | if (entityExpanders[entity.type]) {
66 | expanded = expanded.slice(0, entity.indices[0]) +
67 | entityExpanders[entity.type](expanded, entity) +
68 | expanded.slice(entity.indices[1]);
69 | }
70 | });
71 |
72 | return expanded;
73 | };
74 |
75 | $.twitter = function (options, callback) {
76 | // Fail if the options arg is not set
77 | if ( !options ) {
78 | return false;
79 | }
80 |
81 | // Set a temporary default query object
82 | var query,
83 | // Set up a string to be used later in the case that exclusions have been set
84 | exclusionsStr = "",
85 | // Set up a regex to be used later in the case that exclusions have been set
86 | exclusionsExp = new RegExp(false);
87 |
88 | // If options is a string use it as standalone query
89 | if ( typeof options === "string" ) {
90 | query = $.extend({}, $.twitter.opts, {
91 | q: options
92 | });
93 | // Else prepare the options object to be serialized
94 | } else {
95 | // If a limit is set, add it to the query object
96 | options.rpp = options.limit ? options.limit : options.rpp;
97 |
98 | // If no limit is set, make the limit the rpp
99 | options.limit = options.limit ? options.limit : options.rpp;
100 |
101 | // If there are exlusions, turn them into a regex string
102 | exclusionsStr = options.exclusions ? options.exclusions.replace(" ", "|") : false;
103 |
104 | // If there are exlusions, turn the regex string we just made into a RegExp
105 | exclusionsExp = exclusionsStr ? new RegExp( exclusionsStr ) : false;
106 |
107 | // Make a new object that is a merger of the options passed in with the default $.twitter.opts object
108 | // and assign it to the query variable
109 | query = $.extend({}, $.twitter.opts, options);
110 |
111 | // If there are exclusions, or replies or retweets are set to false, multiply the results to ask for from twitter by ten
112 | // We need to do this so that we have some meat to work with if the exclusions are common
113 | query.rpp = query.exclusions || !query.replies || !query.retweets ? (query.rpp * 10) : query.rpp;
114 |
115 | }
116 |
117 |
118 | // Call Twitter JSONP
119 | $.getJSON("http://search.twitter.com/search.json?callback=?", query, function(tweets){
120 | callback(tweets, query, exclusionsExp);
121 | });
122 | };
123 |
124 | $.fn.twitter = function( options, callback ) {
125 | // Fail gracefully if the options arg is not set
126 | // return the jQuery obj so that chaining does not break
127 | if ( !options ) {
128 | return this;
129 | }
130 |
131 | // Begin to iterate over the jQuery collection that the method was called on
132 | return this.each(function () {
133 | // Cache `this`
134 | var $this = $(this);
135 |
136 | $.twitter(options, function( tweets, query, exclusionsExp ) {
137 | //Create and cache a new UL
138 | var $tweets = $("
"),
139 | // Create a counter variable to count up how many tweets we have rendered
140 | // unfortunately we have to do this, because exclusions, retweet booleans and replies booleans
141 | // are not supported by the Twitter Search API
142 | limitInt = 0,
143 | i;
144 |
145 | // If there are results to work with
146 | if ( tweets.results && tweets.results.length ) {
147 |
148 | // Iterate over returned tweets
149 | for ( i in tweets.results ) {
150 |
151 | // Cache tweet content
152 | var tweet = tweets.results[i],
153 | // Set a variable to determine weather replies are set to false, and if so, weather the tweet starts with a reply
154 | allowReply = !query.replies && tweet.to_user_id ? false : true,
155 | // Set a variable to determine weather retweets are set to false, and if so, weather the tweet starts with a retweet
156 | allowRetweet = !query.retweets && tweet.text.slice(0,2) === "RT" ? false : true;
157 |
158 | // Only proceed if allow reply is false
159 | if ( !allowReply ) {
160 | continue;
161 | }
162 |
163 | // Only proceed if allow retweet is false
164 | if ( !allowRetweet ) {
165 | continue;
166 | }
167 |
168 | // If exlusions set and none of the exlusions is found in the tweet then add it to the DOM
169 | if ( exclusionsExp && exclusionsExp.test(tweet.text) ) {
170 | continue;
171 | }
172 |
173 | // Create and cache new LI
174 | var $tweet = $("", {
175 | "class": "tweet"
176 | });
177 |
178 | // Make the avatar, and append it to the $tweet
179 | if ( query.avatar === true ) {
180 | $tweet.append($("", {
181 | href: "http://twitter.com/" + tweet.from_user,
182 | html: ""
183 | }));
184 | }
185 |
186 | // Make the tweet HTML
187 | var tweetHtml = "@" + tweet.from_user + ": ";
189 | if (query.include_entities) {
190 | tweetHtml += expandEntities(tweet);
191 | } else {
192 | tweetHtml += mention(hashtags(linkify(tweet.text)));
193 | }
194 |
195 | // Append the HTML to the $tweet, then to the parent
196 | $tweet.append($("", {
197 | "class": "content",
198 | html: tweetHtml
199 | }))
200 | // Append tweet to the $tweets ul
201 | .appendTo($tweets);
202 |
203 | // Count up our counter variable
204 | limitInt++;
205 |
206 | // If the counter is equal to the limit, stop rendering tweets
207 | if ( limitInt === query.limit ) {
208 | break;
209 | }
210 | }
211 |
212 | // Inject the $tweets into the DOM
213 | $this.html($tweets);
214 |
215 | if(callback){
216 | callback(true);
217 | }
218 |
219 | // Else there are no results to work with
220 | } else {
221 | // Update the DOM to reflect that no results were found
222 | $this.html($("", {
223 | "class": "twitter-notFound",
224 | text: query.notFoundText
225 | }));
226 |
227 | if(callback){
228 | callback(false);
229 | }
230 | }
231 | });
232 | });
233 | };
234 |
235 | $.twitter.opts = {
236 | // Number of tweets to get
237 | // not in twitter search api, maps to and supersedes rpp (results per page)
238 | limit: 7,
239 | // Space delimited list of strings to exclude (eg: "_ s gr @b")
240 | // not in twitter search api, done in plugin
241 | exclusions: "",
242 | // Text to display if no results are found
243 | // not in twitter search api, done in plugin
244 | notFoundText: "No results found on twitter",
245 | // Include replies?
246 | // not in twitter search api, done in plugin
247 | replies: true,
248 | // Include replies?
249 | // not in twitter search api, done in plugin
250 | retweets: true,
251 | // All of these words
252 | ands: "",
253 | // This exact phrase
254 | phrase: "",
255 | // Any of these words
256 | ors : "",
257 | // None of these words
258 | nots: "",
259 | // This hashtag
260 | tag : "",
261 | // Written in language
262 | lang: "",
263 | // From this person
264 | from: "",
265 | // To this person
266 | to: "",
267 | // Referencing this person
268 | ref: "",
269 | // Near this place
270 | near: "",
271 | // Within this distance
272 | within: "",
273 | // Distance unit (miles or kilometers)
274 | units: "",
275 | // Since this date
276 | since: "",
277 | // Until this date
278 | until: "",
279 | // Attitude: "?" or :)" or ":)"
280 | tude: "",
281 | // Containing: "links"
282 | filter: "",
283 | // Include retweet?: "retweets"
284 | include: "",
285 | // Results per page
286 | rpp: 5,
287 | // Default query
288 | q: "",
289 | // Add an avatar image of the user
290 | avatar: true,
291 | // Retrieve and replace entities
292 | include_entities: true
293 | };
294 | }(jQuery, linkify));
295 |
--------------------------------------------------------------------------------
/LICENSE-GPL:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
--------------------------------------------------------------------------------
/libs/qunit/qunit.js:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.7.0pre - A JavaScript Unit Testing Framework
3 | *
4 | * http://docs.jquery.com/QUnit
5 | *
6 | * Copyright (c) 2012 John Resig, Jörn Zaefferer
7 | * Dual licensed under the MIT (MIT-LICENSE.txt)
8 | * or GPL (GPL-LICENSE.txt) licenses.
9 | */
10 |
11 | (function( window ) {
12 |
13 | var QUnit,
14 | config,
15 | testId = 0,
16 | toString = Object.prototype.toString,
17 | hasOwn = Object.prototype.hasOwnProperty,
18 | defined = {
19 | setTimeout: typeof window.setTimeout !== "undefined",
20 | sessionStorage: (function() {
21 | var x = "qunit-test-string";
22 | try {
23 | sessionStorage.setItem( x, x );
24 | sessionStorage.removeItem( x );
25 | return true;
26 | } catch( e ) {
27 | return false;
28 | }
29 | }())
30 | };
31 |
32 | function Test( settings ) {
33 | extend( this, settings );
34 | this.assertions = [];
35 | this.testNumber = ++Test.count;
36 | }
37 |
38 | Test.count = 0;
39 |
40 | Test.prototype = {
41 | init: function() {
42 | var a, b, li,
43 | tests = id( "qunit-tests" );
44 |
45 | if ( tests ) {
46 | b = document.createElement( "strong" );
47 | b.innerHTML = this.name;
48 |
49 | // `a` initialized at top of scope
50 | a = document.createElement( "a" );
51 | a.innerHTML = "Rerun";
52 | a.href = QUnit.url({ testNumber: this.testNumber });
53 |
54 | li = document.createElement( "li" );
55 | li.appendChild( b );
56 | li.appendChild( a );
57 | li.className = "running";
58 | li.id = this.id = "qunit-test-output" + testId++;
59 |
60 | tests.appendChild( li );
61 | }
62 | },
63 | setup: function() {
64 | if ( this.module !== config.previousModule ) {
65 | if ( config.previousModule ) {
66 | runLoggingCallbacks( "moduleDone", QUnit, {
67 | name: config.previousModule,
68 | failed: config.moduleStats.bad,
69 | passed: config.moduleStats.all - config.moduleStats.bad,
70 | total: config.moduleStats.all
71 | });
72 | }
73 | config.previousModule = this.module;
74 | config.moduleStats = { all: 0, bad: 0 };
75 | runLoggingCallbacks( "moduleStart", QUnit, {
76 | name: this.module
77 | });
78 | } else if ( config.autorun ) {
79 | runLoggingCallbacks( "moduleStart", QUnit, {
80 | name: this.module
81 | });
82 | }
83 |
84 | config.current = this;
85 |
86 | this.testEnvironment = extend({
87 | setup: function() {},
88 | teardown: function() {}
89 | }, this.moduleTestEnvironment );
90 |
91 | runLoggingCallbacks( "testStart", QUnit, {
92 | name: this.testName,
93 | module: this.module
94 | });
95 |
96 | // allow utility functions to access the current test environment
97 | // TODO why??
98 | QUnit.current_testEnvironment = this.testEnvironment;
99 |
100 | if ( !config.pollution ) {
101 | saveGlobal();
102 | }
103 | if ( config.notrycatch ) {
104 | this.testEnvironment.setup.call( this.testEnvironment );
105 | return;
106 | }
107 | try {
108 | this.testEnvironment.setup.call( this.testEnvironment );
109 | } catch( e ) {
110 | QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
111 | }
112 | },
113 | run: function() {
114 | config.current = this;
115 |
116 | var running = id( "qunit-testresult" );
117 |
118 | if ( running ) {
119 | running.innerHTML = "Running: " + this.name;
120 | }
121 |
122 | if ( this.async ) {
123 | QUnit.stop();
124 | }
125 |
126 | if ( config.notrycatch ) {
127 | this.callback.call( this.testEnvironment, QUnit.assert );
128 | return;
129 | }
130 |
131 | try {
132 | this.callback.call( this.testEnvironment, QUnit.assert );
133 | } catch( e ) {
134 | QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + ": " + e.message, extractStacktrace( e, 1 ) );
135 | // else next test will carry the responsibility
136 | saveGlobal();
137 |
138 | // Restart the tests if they're blocking
139 | if ( config.blocking ) {
140 | QUnit.start();
141 | }
142 | }
143 | },
144 | teardown: function() {
145 | config.current = this;
146 | if ( config.notrycatch ) {
147 | this.testEnvironment.teardown.call( this.testEnvironment );
148 | return;
149 | } else {
150 | try {
151 | this.testEnvironment.teardown.call( this.testEnvironment );
152 | } catch( e ) {
153 | QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
154 | }
155 | }
156 | checkPollution();
157 | },
158 | finish: function() {
159 | config.current = this;
160 | if ( this.expected != null && this.expected != this.assertions.length ) {
161 | QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack );
162 | } else if ( this.expected == null && !this.assertions.length ) {
163 | QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack );
164 | }
165 |
166 | var assertion, a, b, i, li, ol,
167 | test = this,
168 | good = 0,
169 | bad = 0,
170 | tests = id( "qunit-tests" );
171 |
172 | config.stats.all += this.assertions.length;
173 | config.moduleStats.all += this.assertions.length;
174 |
175 | if ( tests ) {
176 | ol = document.createElement( "ol" );
177 |
178 | for ( i = 0; i < this.assertions.length; i++ ) {
179 | assertion = this.assertions[i];
180 |
181 | li = document.createElement( "li" );
182 | li.className = assertion.result ? "pass" : "fail";
183 | li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" );
184 | ol.appendChild( li );
185 |
186 | if ( assertion.result ) {
187 | good++;
188 | } else {
189 | bad++;
190 | config.stats.bad++;
191 | config.moduleStats.bad++;
192 | }
193 | }
194 |
195 | // store result when possible
196 | if ( QUnit.config.reorder && defined.sessionStorage ) {
197 | if ( bad ) {
198 | sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad );
199 | } else {
200 | sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName );
201 | }
202 | }
203 |
204 | if ( bad === 0 ) {
205 | ol.style.display = "none";
206 | }
207 |
208 | // `b` initialized at top of scope
209 | b = document.createElement( "strong" );
210 | b.innerHTML = this.name + " (" + bad + ", " + good + ", " + this.assertions.length + ")";
211 |
212 | addEvent(b, "click", function() {
213 | var next = b.nextSibling.nextSibling,
214 | display = next.style.display;
215 | next.style.display = display === "none" ? "block" : "none";
216 | });
217 |
218 | addEvent(b, "dblclick", function( e ) {
219 | var target = e && e.target ? e.target : window.event.srcElement;
220 | if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
221 | target = target.parentNode;
222 | }
223 | if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
224 | window.location = QUnit.url({ testNumber: test.testNumber });
225 | }
226 | });
227 |
228 | // `li` initialized at top of scope
229 | li = id( this.id );
230 | li.className = bad ? "fail" : "pass";
231 | li.removeChild( li.firstChild );
232 | a = li.firstChild;
233 | li.appendChild( b );
234 | li.appendChild ( a );
235 | li.appendChild( ol );
236 |
237 | } else {
238 | for ( i = 0; i < this.assertions.length; i++ ) {
239 | if ( !this.assertions[i].result ) {
240 | bad++;
241 | config.stats.bad++;
242 | config.moduleStats.bad++;
243 | }
244 | }
245 | }
246 |
247 | runLoggingCallbacks( "testDone", QUnit, {
248 | name: this.testName,
249 | module: this.module,
250 | failed: bad,
251 | passed: this.assertions.length - bad,
252 | total: this.assertions.length
253 | });
254 |
255 | QUnit.reset();
256 | },
257 |
258 | queue: function() {
259 | var bad,
260 | test = this;
261 |
262 | synchronize(function() {
263 | test.init();
264 | });
265 | function run() {
266 | // each of these can by async
267 | synchronize(function() {
268 | test.setup();
269 | });
270 | synchronize(function() {
271 | test.run();
272 | });
273 | synchronize(function() {
274 | test.teardown();
275 | });
276 | synchronize(function() {
277 | test.finish();
278 | });
279 | }
280 |
281 | // `bad` initialized at top of scope
282 | // defer when previous test run passed, if storage is available
283 | bad = QUnit.config.reorder && defined.sessionStorage &&
284 | +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName );
285 |
286 | if ( bad ) {
287 | run();
288 | } else {
289 | synchronize( run, true );
290 | }
291 | }
292 | };
293 |
294 | // Root QUnit object.
295 | // `QUnit` initialized at top of scope
296 | QUnit = {
297 |
298 | // call on start of module test to prepend name to all tests
299 | module: function( name, testEnvironment ) {
300 | config.currentModule = name;
301 | config.currentModuleTestEnviroment = testEnvironment;
302 | },
303 |
304 | asyncTest: function( testName, expected, callback ) {
305 | if ( arguments.length === 2 ) {
306 | callback = expected;
307 | expected = null;
308 | }
309 |
310 | QUnit.test( testName, expected, callback, true );
311 | },
312 |
313 | test: function( testName, expected, callback, async ) {
314 | var test,
315 | name = "" + escapeInnerText( testName ) + "";
316 |
317 | if ( arguments.length === 2 ) {
318 | callback = expected;
319 | expected = null;
320 | }
321 |
322 | if ( config.currentModule ) {
323 | name = "" + config.currentModule + ": " + name;
324 | }
325 |
326 | test = new Test({
327 | name: name,
328 | testName: testName,
329 | expected: expected,
330 | async: async,
331 | callback: callback,
332 | module: config.currentModule,
333 | moduleTestEnvironment: config.currentModuleTestEnviroment,
334 | stack: sourceFromStacktrace( 2 )
335 | });
336 |
337 | if ( !validTest( test ) ) {
338 | return;
339 | }
340 |
341 | test.queue();
342 | },
343 |
344 | // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
345 | expect: function( asserts ) {
346 | config.current.expected = asserts;
347 | },
348 |
349 | start: function( count ) {
350 | config.semaphore -= count || 1;
351 | // don't start until equal number of stop-calls
352 | if ( config.semaphore > 0 ) {
353 | return;
354 | }
355 | // ignore if start is called more often then stop
356 | if ( config.semaphore < 0 ) {
357 | config.semaphore = 0;
358 | }
359 | // A slight delay, to avoid any current callbacks
360 | if ( defined.setTimeout ) {
361 | window.setTimeout(function() {
362 | if ( config.semaphore > 0 ) {
363 | return;
364 | }
365 | if ( config.timeout ) {
366 | clearTimeout( config.timeout );
367 | }
368 |
369 | config.blocking = false;
370 | process( true );
371 | }, 13);
372 | } else {
373 | config.blocking = false;
374 | process( true );
375 | }
376 | },
377 |
378 | stop: function( count ) {
379 | config.semaphore += count || 1;
380 | config.blocking = true;
381 |
382 | if ( config.testTimeout && defined.setTimeout ) {
383 | clearTimeout( config.timeout );
384 | config.timeout = window.setTimeout(function() {
385 | QUnit.ok( false, "Test timed out" );
386 | config.semaphore = 1;
387 | QUnit.start();
388 | }, config.testTimeout );
389 | }
390 | }
391 | };
392 |
393 | // Asssert helpers
394 | // All of these must call either QUnit.push() or manually do:
395 | // - runLoggingCallbacks( "log", .. );
396 | // - config.current.assertions.push({ .. });
397 | QUnit.assert = {
398 | /**
399 | * Asserts rough true-ish result.
400 | * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
401 | */
402 | ok: function( result, msg ) {
403 | if ( !config.current ) {
404 | throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) );
405 | }
406 | result = !!result;
407 |
408 | var source,
409 | details = {
410 | result: result,
411 | message: msg
412 | };
413 |
414 | msg = escapeInnerText( msg || (result ? "okay" : "failed" ) );
415 | msg = "" + msg + "";
416 |
417 | if ( !result ) {
418 | source = sourceFromStacktrace( 2 );
419 | if ( source ) {
420 | details.source = source;
421 | msg += "
Source:
" + escapeInnerText( source ) + "
";
422 | }
423 | }
424 | runLoggingCallbacks( "log", QUnit, details );
425 | config.current.assertions.push({
426 | result: result,
427 | message: msg
428 | });
429 | },
430 |
431 | /**
432 | * Assert that the first two arguments are equal, with an optional message.
433 | * Prints out both actual and expected values.
434 | * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" );
435 | */
436 | equal: function( actual, expected, message ) {
437 | QUnit.push( expected == actual, actual, expected, message );
438 | },
439 |
440 | notEqual: function( actual, expected, message ) {
441 | QUnit.push( expected != actual, actual, expected, message );
442 | },
443 |
444 | deepEqual: function( actual, expected, message ) {
445 | QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
446 | },
447 |
448 | notDeepEqual: function( actual, expected, message ) {
449 | QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
450 | },
451 |
452 | strictEqual: function( actual, expected, message ) {
453 | QUnit.push( expected === actual, actual, expected, message );
454 | },
455 |
456 | notStrictEqual: function( actual, expected, message ) {
457 | QUnit.push( expected !== actual, actual, expected, message );
458 | },
459 |
460 | raises: function( block, expected, message ) {
461 | var actual,
462 | ok = false;
463 |
464 | if ( typeof expected === "string" ) {
465 | message = expected;
466 | expected = null;
467 | }
468 |
469 | try {
470 | block.call( config.current.testEnvironment );
471 | } catch (e) {
472 | actual = e;
473 | }
474 |
475 | if ( actual ) {
476 | // we don't want to validate thrown error
477 | if ( !expected ) {
478 | ok = true;
479 | // expected is a regexp
480 | } else if ( QUnit.objectType( expected ) === "regexp" ) {
481 | ok = expected.test( actual );
482 | // expected is a constructor
483 | } else if ( actual instanceof expected ) {
484 | ok = true;
485 | // expected is a validation function which returns true is validation passed
486 | } else if ( expected.call( {}, actual ) === true ) {
487 | ok = true;
488 | }
489 | }
490 |
491 | QUnit.push( ok, actual, null, message );
492 | }
493 | };
494 |
495 | // @deprecated: Kept assertion helpers in root for backwards compatibility
496 | extend( QUnit, QUnit.assert );
497 |
498 | /**
499 | * @deprecated: Kept for backwards compatibility
500 | * next step: remove entirely
501 | */
502 | QUnit.equals = function() {
503 | QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" );
504 | };
505 | QUnit.same = function() {
506 | QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" );
507 | };
508 |
509 | // We want access to the constructor's prototype
510 | (function() {
511 | function F() {}
512 | F.prototype = QUnit;
513 | QUnit = new F();
514 | // Make F QUnit's constructor so that we can add to the prototype later
515 | QUnit.constructor = F;
516 | }());
517 |
518 | /**
519 | * Config object: Maintain internal state
520 | * Later exposed as QUnit.config
521 | * `config` initialized at top of scope
522 | */
523 | config = {
524 | // The queue of tests to run
525 | queue: [],
526 |
527 | // block until document ready
528 | blocking: true,
529 |
530 | // when enabled, show only failing tests
531 | // gets persisted through sessionStorage and can be changed in UI via checkbox
532 | hidepassed: false,
533 |
534 | // by default, run previously failed tests first
535 | // very useful in combination with "Hide passed tests" checked
536 | reorder: true,
537 |
538 | // by default, modify document.title when suite is done
539 | altertitle: true,
540 |
541 | urlConfig: [ "noglobals", "notrycatch" ],
542 |
543 | // logging callback queues
544 | begin: [],
545 | done: [],
546 | log: [],
547 | testStart: [],
548 | testDone: [],
549 | moduleStart: [],
550 | moduleDone: []
551 | };
552 |
553 | // Initialize more QUnit.config and QUnit.urlParams
554 | (function() {
555 | var i,
556 | location = window.location || { search: "", protocol: "file:" },
557 | params = location.search.slice( 1 ).split( "&" ),
558 | length = params.length,
559 | urlParams = {},
560 | current;
561 |
562 | if ( params[ 0 ] ) {
563 | for ( i = 0; i < length; i++ ) {
564 | current = params[ i ].split( "=" );
565 | current[ 0 ] = decodeURIComponent( current[ 0 ] );
566 | // allow just a key to turn on a flag, e.g., test.html?noglobals
567 | current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
568 | urlParams[ current[ 0 ] ] = current[ 1 ];
569 | }
570 | }
571 |
572 | QUnit.urlParams = urlParams;
573 | config.filter = urlParams.filter;
574 | config.testNumber = parseInt( urlParams.testNumber, 10 ) || null;
575 |
576 | // Figure out if we're running the tests from a server or not
577 | QUnit.isLocal = location.protocol === "file:";
578 | }());
579 |
580 | // Export global variables, unless an 'exports' object exists,
581 | // in that case we assume we're in CommonJS (dealt with on the bottom of the script)
582 | if ( typeof exports === "undefined" ) {
583 | extend( window, QUnit );
584 |
585 | // Expose QUnit object
586 | window.QUnit = QUnit;
587 | }
588 |
589 | // Extend QUnit object,
590 | // these after set here because they should not be exposed as global functions
591 | extend( QUnit, {
592 | config: config,
593 |
594 | // Initialize the configuration options
595 | init: function() {
596 | extend( config, {
597 | stats: { all: 0, bad: 0 },
598 | moduleStats: { all: 0, bad: 0 },
599 | started: +new Date(),
600 | updateRate: 1000,
601 | blocking: false,
602 | autostart: true,
603 | autorun: false,
604 | filter: "",
605 | queue: [],
606 | semaphore: 0
607 | });
608 |
609 | var tests, banner, result,
610 | qunit = id( "qunit" );
611 |
612 | if ( qunit ) {
613 | qunit.innerHTML =
614 | "