Browse Source

commit

master
Steve Saldivar 12 years ago
commit
ec2e35c117
  1. 22
      .gitattributes
  2. 176
      .gitignore
  3. 50
      License.md
  4. 140
      README.md
  5. 80
      lib/commands.js
  6. 1354
      lib/currency.js
  7. 21
      lib/dashboard/404.html
  8. 191
      lib/dashboard/css/dashboard.css
  9. 208
      lib/dashboard/css/jquery.mCustomScrollbar.css
  10. 85
      lib/dashboard/dashboard.html
  11. 175
      lib/dashboard/dashboard.js
  12. BIN
      lib/dashboard/images/archonbot.png
  13. BIN
      lib/dashboard/images/background.jpg
  14. BIN
      lib/dashboard/images/icons.png
  15. 0
      lib/dashboard/images/transparent_pxl_white-90.png
  16. BIN
      lib/dashboard/images/vector-web-icons.png
  17. 167
      lib/dashboard/js/actions.js
  18. 874
      lib/dashboard/js/jquery.mCustomScrollbar.js
  19. 12
      lib/dashboard/js/jquery.mousewheel.min.js
  20. BIN
      lib/dashboard/webfonts/22AE77_0_0.eot
  21. 3
      lib/dashboard/webfonts/22AE77_0_0.ttf
  22. 3
      lib/dashboard/webfonts/22AE77_0_0.woff
  23. BIN
      lib/dashboard/webfonts/scoolar_tfb.eot
  24. BIN
      lib/dashboard/webfonts/scoolar_tfb.ttf
  25. 59
      lib/initialize.js
  26. 368
      lib/irc.js
  27. 81
      lib/mysql.js
  28. 15
      lib/utils.js
  29. 5
      node_modules/mustache/.jshintrc
  30. 10
      node_modules/mustache/.npmignore
  31. 4
      node_modules/mustache/.travis.yml
  32. 34
      node_modules/mustache/CHANGES
  33. 10
      node_modules/mustache/LICENSE
  34. 400
      node_modules/mustache/README.md
  35. 68
      node_modules/mustache/Rakefile
  36. 610
      node_modules/mustache/mustache.js
  37. 14
      node_modules/mustache/mustache.js.nuspec
  38. 32
      node_modules/mustache/package.json
  39. 3
      node_modules/mustache/test/_files/ampersand_escape.js
  40. 1
      node_modules/mustache/test/_files/ampersand_escape.mustache
  41. 1
      node_modules/mustache/test/_files/ampersand_escape.txt
  42. 4
      node_modules/mustache/test/_files/apostrophe.js
  43. 1
      node_modules/mustache/test/_files/apostrophe.mustache
  44. 1
      node_modules/mustache/test/_files/apostrophe.txt
  45. 3
      node_modules/mustache/test/_files/array_of_strings.js
  46. 1
      node_modules/mustache/test/_files/array_of_strings.mustache
  47. 1
      node_modules/mustache/test/_files/array_of_strings.txt
  48. 3
      node_modules/mustache/test/_files/backslashes.js
  49. 7
      node_modules/mustache/test/_files/backslashes.mustache
  50. 7
      node_modules/mustache/test/_files/backslashes.txt
  51. 3
      node_modules/mustache/test/_files/bug_11_eating_whitespace.js
  52. 1
      node_modules/mustache/test/_files/bug_11_eating_whitespace.mustache
  53. 1
      node_modules/mustache/test/_files/bug_11_eating_whitespace.txt
  54. 4
      node_modules/mustache/test/_files/changing_delimiters.js
  55. 1
      node_modules/mustache/test/_files/changing_delimiters.mustache
  56. 1
      node_modules/mustache/test/_files/changing_delimiters.txt
  57. 7
      node_modules/mustache/test/_files/check_falsy.js
  58. 1
      node_modules/mustache/test/_files/check_falsy.mustache
  59. 1
      node_modules/mustache/test/_files/check_falsy.txt
  60. 5
      node_modules/mustache/test/_files/comments.js
  61. 1
      node_modules/mustache/test/_files/comments.mustache
  62. 1
      node_modules/mustache/test/_files/comments.txt
  63. 19
      node_modules/mustache/test/_files/complex.js
  64. 16
      node_modules/mustache/test/_files/complex.mustache
  65. 6
      node_modules/mustache/test/_files/complex.txt
  66. 8
      node_modules/mustache/test/_files/context_lookup.js
  67. 1
      node_modules/mustache/test/_files/context_lookup.mustache
  68. 1
      node_modules/mustache/test/_files/context_lookup.txt
  69. 6
      node_modules/mustache/test/_files/delimiters.js
  70. 7
      node_modules/mustache/test/_files/delimiters.mustache
  71. 5
      node_modules/mustache/test/_files/delimiters.txt
  72. 4
      node_modules/mustache/test/_files/disappearing_whitespace.js
  73. 1
      node_modules/mustache/test/_files/disappearing_whitespace.mustache
  74. 1
      node_modules/mustache/test/_files/disappearing_whitespace.txt
  75. 23
      node_modules/mustache/test/_files/dot_notation.js
  76. 9
      node_modules/mustache/test/_files/dot_notation.mustache
  77. 9
      node_modules/mustache/test/_files/dot_notation.txt
  78. 5
      node_modules/mustache/test/_files/double_render.js
  79. 1
      node_modules/mustache/test/_files/double_render.mustache
  80. 1
      node_modules/mustache/test/_files/double_render.txt
  81. 3
      node_modules/mustache/test/_files/empty_list.js
  82. 4
      node_modules/mustache/test/_files/empty_list.mustache
  83. 1
      node_modules/mustache/test/_files/empty_list.txt
  84. 1
      node_modules/mustache/test/_files/empty_sections.js
  85. 1
      node_modules/mustache/test/_files/empty_sections.mustache
  86. 1
      node_modules/mustache/test/_files/empty_sections.txt
  87. 6
      node_modules/mustache/test/_files/empty_string.js
  88. 1
      node_modules/mustache/test/_files/empty_string.mustache
  89. 1
      node_modules/mustache/test/_files/empty_string.txt
  90. 1
      node_modules/mustache/test/_files/empty_template.js
  91. 1
      node_modules/mustache/test/_files/empty_template.mustache
  92. 1
      node_modules/mustache/test/_files/empty_template.txt
  93. 3
      node_modules/mustache/test/_files/error_not_found.js
  94. 1
      node_modules/mustache/test/_files/error_not_found.mustache
  95. 0
      node_modules/mustache/test/_files/error_not_found.txt
  96. 6
      node_modules/mustache/test/_files/escaped.js
  97. 2
      node_modules/mustache/test/_files/escaped.mustache
  98. 2
      node_modules/mustache/test/_files/escaped.txt
  99. 8
      node_modules/mustache/test/_files/falsy.js
  100. 12
      node_modules/mustache/test/_files/falsy.mustache

22
.gitattributes

@ -0,0 +1,22 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

176
.gitignore

@ -0,0 +1,176 @@
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.vspscc
.builds
*.dotCover
## TODO: If you have NuGet Package Restore enabled, uncomment this
#packages/
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
# Visual Studio profiler
*.psess
*.vsp
# ReSharper is a .NET coding add-in
_ReSharper*
# Installshield output folder
[Ee]xpress
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish
# Others
[Bb]in
[Oo]bj
sql
TestResults
*.Cache
ClientBin
stylecop.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
############
## Windows
############
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
# batch files
*.bat
#############
## Python
#############
*.py[co]
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg
# Mac crap
.DS_Store
###################
## Project Specific
###################
twitch.css
tools/
logs/*
bitly.js
update.js
users/

50
License.md

@ -0,0 +1,50 @@
Software license for LoyaltyBot
===============================
SUMMARY
-------
- Can be used on unlimited sites, servers
- Source-code cannot be resold
- Non-commercial use only
- Can modify source-code and distribute modifications (derivative works) authorized 3rd Parties
- Any code deemed awesome across any fork will be merged into the main branch
TERMS AND CONDITIONS
--------------------
1. **Preamble:** This Agreement, signed on Feb 20, 2013 [hereinafter: Effective Date] governs the relationship between User, a private person, (hereinafter: Licensee) and LoyaltyBot, a private person whose principal place of business is CA, United States (Hereinafter: Licensor). This Agreement sets the terms, rights, restrictions and obligations on using [LoyaltyBot] (hereinafter: The Software) created and owned by Licensor, as detailed herein
2. **License Grant:** Licensor hereby grants Licensee a Personal, Non-assignable & non-transferable, Non-commercial, Including the rights to distribute derivative works, Non-exclusive license, all with accordance with the terms set forth and other legal restrictions set forth in 3rd party software used while running Software
* 2.1. **Limited:** Licensee may use Software for the purpose of:
- 2.1.1. Running Software on Licensee's Website[s] and Server[s];
- 2.1.2. Allowing authorized 3rd Parties to run Software on Licensee's Website[s] and Server[s];
- 2.1.3. Publishing Software's output to Licensee and authorized 3rd Parties;
- 2.1.4. Distribute verbatim copies of Software's output (including compiled binaries) to authorized 3rd Parties;
- 2.1.5. Modify Software to suit Licensee's needs and specifications.
* 2.2. **Non Assignable & Non-Transferable:** Licensee may not assign or transfer his rights and duties under this license.
* 2.3. **Non-Commercial:** Licensee may not use Software for commercial purposes. for the purpose of this license, commercial purposes means that a 3rd party has to pay in order to access Software or that the Website that runs Software is behind a paywall.
* 2.4. **Including the Right to Create Derivative Works:** Licensee may create derivative works based on Software, including amending Software's source code, modifying it, integrating it into a larger work or removing portions of Software, as long as no distribution of the derivative works is made
* 2.5. **Including the right to Distribute Derivative Works:** Licensee may create and distribute derivative works based on Software, including amending Software's source code, modifying it, integrating it into a larger work or removing portions of Software, as long as credit to the Licensor is granted and that redistribution is made under the terms of this license.
* 2.6. **[Multi-]Site:** Licensee may use Software on unlimited server[s] and unlimited website[s], for Licensee's websites only
3. **Term & Termination:** The Term of this license shall be until terminated. Licensor may terminate this Agreement, including Licensee's license in the case where Licensee :
* 3.1. became insolvent or otherwise entered into any liquidation process; or
* 3.2. exported The Software to any jurisdiction where licensor may not enforce his rights under this agreements in; or
* 3.3. Licenee was in breach of any of this license's terms and conditions and such breach was not cured, immediately upon notification; or
* 3.4. Licensee in breach of any of the terms of clause 2 to this license; or
* 3.5. Licensee otherwise entered into any arrangement which caused Licensor to be unable to enforce his rights under this License.
4. **Payment:** In consideration of the License granted under clause 2, Licensee may be required to pay the Licensor, via PayPal or any other mean which Licensor may deem adequate. Failure to perform payment shall construe as material breach of this Agreement.
5. **Upgrades, Updates and Fixes:** Licensor may provide Licensee, from time to time, with Upgrades, Updates or Fixes, as detailed herein and according to his sole discretion. Licensee hereby warrants to keep The Software up-to-date and install all relevant updates and fixes, and may, at his sole discretion, purchase upgrades, according to the rates set by Licensor. Licensor shall provide any update or Fix free of charge; however, nothing in this Agreement shall require Licensor to provide Updates or Fixes.
* 5.1. **Upgrades:** for the purpose of this license, an Upgrade shall be a material amendment in The Software, which contains new features and or major performance improvements which can and will be pulled from any of the given forks into the main code branch. For example, should Licensee make an upgrade that is beneficial to the main code branch, the Licensor reserves the right to merge the Licensee's ugraded code into the main branch.
* 5.2. **Updates:** for the purpose of this license, an update shall be a minor amendment in The Software, which may contain new features or minor improvements. For example, should Licensee make an update that is beneficial to the main code branch, the Licensor reserves the right to merge the Licensee's update into the main code branch.
* 5.3. **Fix:** for the purpose of this license, a fix shall be a minor amendment in The Software, intended to remove bugs or alter minor features which impair the The Software's functionality. For example, should Licensee make fix that is beneficial to the main code branch, the Licensor reserves the right to merge the Licensee's fix into the main code branch.
6. **Support:** Software is provided under an AS-IS basis and without any support, updates or maintenance. Nothing in this Agreement shall require Licensor to provide Licensee with support or fixes to any bug, failure, mis-performance or other defect in The Software.
* 6.1. **Bug Notification:** Licensee may provide Licensor of details regarding any bug, defect or failure in The Software promptly and with no delay from such event; Licensee shall comply with Licensor's request for information regarding bugs, defects or failures and furnish him with information, screenshots and try to reproduce such bugs, defects or failures.
* 6.2. **Feature Request:** Licensee may request additional features in Software, provided, however, that (i) Licesee shall waive any claim or right in such feature should feature be developed by Licensor; (ii) Licensee shall be prohibited from developing the feature, or disclose such feature request, or feature, to any 3rd party directly competing with Licensor or any 3rd party which may be, following the development of such feature, in direct competition with Licensor; (iii) Licensee warrants that feature does not infringe any 3rd party patent, trademark, trade-secret or any other intellectual property right; and (iv) Licensee developed, envisioned or created the feature solely by himself.
7. **Liability:** To the extent permitted under Law, The Software is provided under an AS-IS basis. Licensor shall never, and without any limit, be liable for any damage, cost, expense or any other payment incurred by Licesee as a result of Software's actions, failure, bugs and/or any other interaction between The Software and Licesee's end-equipment, computers, other software or any 3rd party, end-equipment, computer or services. Moreover, Licensor shall never be liable for any defect in source code written by Licensee when relying on The Software or using The Software's source code.
8. **Warranty:**
* 8.1. **Intellectual Property:** Licensor hereby warrants that The Software does not violate or infringe any 3rd party claims in regards to intellectual property, patents and/or trademarks and that to the best of its knowledge no legal action has been taken against it for any infringement or violation of any 3rd party intellectual property rights.
* 8.2. **No-Warranty:** The Software is provided without any warranty; Licensor hereby disclaims any warranty that The Software shall be error free, without defects or code which may cause damage to Licensee's computers or to Licensee, and that Software shall be functional. Licensee shall be solely liable to any damage, defect or loss incurred as a result of operating software and undertake the risks contained in running The Software on License's Server[s] and Website[s].
* 8.3. **Prior Inspection:** Licensee hereby states that he inspected The Software thoroughly and found it satisfactory and adequate to his needs, that it does not interfere with his regular operation and that it does meet the standards and scope of his computer systems and architecture. Licensee found that The Software interacts with his development, website and server environment and that it does not infringe any of End User License Agreement of any software Licensee may use in performing his services. Licensee hereby waives any claims regarding The Software's incompatibility, performance, results and features, and warrants that he inspected the The Software.
9. **No Refunds:** Licensee warrants that he inspected The Software according to clause 7(c) and that it is adequate to his needs. Accordingly, as The Software is intangible goods, Licensee shall not be, ever, entitled to any refund, rebate, compensation or restitution for any reason whatsoever, even if The Software contains material flaws.
10. **Indemnification:** Licensee hereby warrants to hold Licensor harmless and indemnify Licensor for any lawsuit brought against it in regards to Licensee's use of The Software in means that violate, breach or otherwise circumvent this license, Licensor's intellectual property rights or Licensor's title in The Software. Licensor shall promptly notify Licensee in case of such legal action and request Licensee's consent prior to any settlement in relation to such lawsuit or claim.
11. **Governing Law, Jurisdiction:** Licensee hereby agrees not to initiate class-action lawsuits against Licensor in relation to this license and to compensate Licensor for any legal fees, cost or attorney fees should any claim brought by Licensee against Licensor be denied, in part or in full.

140
README.md

@ -0,0 +1,140 @@
LoyaltyBot
=========
A TwitchTV viewer reward system
Written in Node and JavaScript
*By having access to this repository you and any authorized 3rd Parties agree to the [software license](https://github.com/SupremoRTD/LoyaltyBot/blob/master/License.md#software-license-for-loyaltybot)*
Overview
--------
LoyaltyBot is a chat bot that allows you to reward viewers with loyalty points for hanging out on your stream. It's
main purpose is to allow you, the broadcaster, to reward the viewers that are dedicated to watching your stream as
opposed to the viewers that just stop by for a quick giveaway and leave.
####Features
- Fully functioning auction and raffle systems
- Double loyalty points for subscribers/loyal viewers
####Extras
- Moderator commands (currently in development, semi functional)
####Future Features/Extras
- Free subscriber/paid non-subscriber Jukebox (still in development)
- Stream title updates posted to twitter (still in development)
Basic Setup
-----------
example.js
````javascript
var LoyaltyBot = require('./lib/initialize.js');
LoyaltyBot.initialize({
// twitch info
twitch : {
channel : 'loyalty',
bot : {name: 'LoyaltyBot', password: 'loyalty!loyalty!loyalty!'},
subscribers : 'https://spreadsheets.google.com/feeds/list/****/od6/public/basic?alt=json'
},
// currency system
currency : {
name : 'LoyaltyPoints',
payrate : 15,
host : '127.0.0.1',
user : 'mysql_user',
password : 'mysql_password',
database : 'mysql_database',
website : 'http://www.loyaltypoints.com'
},
// optional
commands: true
});
````
Configuration Options
---------------------
Twitch
- ````channel````: the channel name (in lower case)
- ````bot.name````: the account name of the bot
- ````bot.password````: the password for the bot
- ````subscribers````: a google doc that contains subscriber names (more info on this later)
Currency
- ````name````: custom name for the loyalty points
- ````payrate````: how often to hand out loyalty points (in minutes)
- ````host````: mysql database hostname/ip
- ````user````: username for the mysql database
- ````password````: password for the mysql database
- ````database````: mysql database name
- ````website````: provides loyalty bot with an offsite location for checking currency. can also be and be an empty ````string````
Optional
- ````commands````: enable/disable the ability to use moderator commands. boolean: accepts ````true```` or ````false````
Preparing to Setup Your Channel's Bot
-------------------------------------
####Create a new bot account
In order to use LoyaltyBot's features you will need to create a new [TwitchTV Account](http://www.twitch.tv/signup). You can name it anything
you wish, all you need to do is pass the username/password to ````bot.name```` and ````bot.password````
####Create the subscriber/loyal viewer list on Google Docs
Since TwitchTV does not have subscriber information in their api, LoyaltyBot needs a way to obtain that information.
That's where [Google Docs](http://docs.google.com/) comes in.
In the following order:
- Create a new spreadsheet
- Set cell A1 as the header "Username"
- Subscriber names (must be lower case) will then be in column A starting in cell A2 and below (Fig. 1)
- Set the subscriber list to public and change the type to json (Fig. 2)
Side Notes:
- Even if you do not have a subscription button, you can still add loyal viewers to this list for the double loyalty point benefits.
- Why Google Docs and not the MySQL database? Simplicity. It's easier to manually update a google doc spreadsheet daily
then it is to update a MySQL table.
*Figure 1:*
![Column Setup](http://i.imgur.com/eyQOwGz.jpg)
*Figure 2:*
![Create Link](http://i.imgur.com/jDU9xOR.jpg)
####Setting up MySQL tables
LoyaltyBot stores all of the viewer info and moderator commands in a MySQL database and requires specifc table/field names.
LoyaltyBot takes care of all table creation, however if by some chance you need to manually setup the tables the following
contains information about them:
Viewer
- Table Name: ````viewers````
- Field Names: ````user```` [primary key, not null, varchar], ````points```` [not null, integer]
Commands
- Table Name: ````commands````
- Field Names: ````id```` [primary key, autoincrement, not null, integer], ````command```` [not null, text], ````text```` [not null, longtext], ````auth```` [default: 1, integer]
LoyaltyBot In Action
--------------------
ArchonBot - [ArchonTheWizard](http://www.twitch.tv/archonthewizard)
BingBongBot - [CDXLIV](http://www.twitch.tv/cdxliv)
If you're using LoyaltyBot send me a [twitch message](http://www.twitch.tv/message/compose?to=rvca18) so I can add you to this list!

80
lib/commands.js

@ -0,0 +1,80 @@
/**
* api:
* Commands(irc object, database object);
*
* example:
* commands = require('./mysql/commands.js')(irc, db, {
* bot_name : 'bot name',
* currency: 'currency name'
* });
*/
//-------- Construct ---------
function Commands(irc, db, options) {
var __self = this;
__self.irc = irc;
__self.db = db;
// config
__self.config = options || {};
__self.config.bot_name = options.bot_name || '';
__self.config.currency = options.currency || 'coins';
__self.command_list = [];
}
//-------- Methods --------
Commands.prototype.start = function() {
var __self = this,
sql = 'SELECT * FROM commands';
__self.db.execute(sql, function(rows) {
for (var i = 0; i < rows.length; i++) {
__self.command_list.push(rows[i].command);
}
});
};
Commands.prototype.commands = function(data) {
var __self = this,
command_check = data[3].slice(1).charAt(0),
command = data[3].slice(2);
// check if potential command was called and match it with stored commands
// if the bots name is used as a command, then display all of the available commands
if(command_check === '!' && __self.command_list.indexOf(command) >= 0) {
var sql = 'SELECT * FROM commands WHERE command = \'' + command + '\'';
// get command info from database
__self.db.execute(sql, function(rows) {
// filter through command results
for (var i = 0; i < rows.length; i++) {
// match db command with called command
if (rows[i].command = command) {
// display based on viewer auth
if (rows[i].auth === 1) {
__self.irc.emit('message',{message:rows[i].text, options:{caller: __self.irc.caller(data[0]), auth: 1}});
break;
} else if (rows[i].auth === 0) {
__self.irc.emit('message',{message:rows[i].text, options:null});
break;
}
}
}
});
} else if (command_check === '!' && command === __self.config.bot_name.toLowerCase()) {
var commands = '> Commands: !' + __self.config.currency.toLowerCase() + ', ';
for (var i = 0; i < __self.command_list.length; i++) {
if (i !== __self.command_list.length - 1) {
commands += '!' + __self.command_list[i] + ', ';
} else {
commands += '!' + __self.command_list[i];
}
}
__self.irc.emit('message',{message:commands, options:{caller: __self.irc.caller(data[0]), auth: 1}});
}
};
module.exports = function(irc, db, options) {
return new Commands(irc, db, options);
};

1354
lib/currency.js
File diff suppressed because it is too large
View File

21
lib/dashboard/404.html

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>ArchonBot 404</title>
<link href="http://www.twitch.tv/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<style>
@font-face{font-family: orangejuice;src:url('/webfonts/scoolar_tfb.ttf'),url('/webfonts/scoolar_tfb.eot');}
body{background:url('/images/background.jpg');}
*{margin:0px; padding:0px;}
#container{padding:20px}
#wrapper{width:800px;margin:0 auto;}
#robot{background:url('/images/archonbot.png');width:126px;height:175px;float:right;margin-right:30px}
#status{width:500px;margin:0 auto;}
.error{font-family:orangejuice;font-size:62pt;color:#FFF;}
.fourohfour{font-size:135pt;color:#8266B6;}
</style>
</head>
<body>
<div id="container"><div id="wrapper"><div id="status" class="error"><span class="fourohfour">404</span><div id="robot"></div></div><div class="error">Whatever it is you are looking for, ArchonBot has not created.</div></div></div>
</body>
</html>

191
lib/dashboard/css/dashboard.css

@ -0,0 +1,191 @@
@font-face{font-family:"Korolev-Bold";
src:url("/webfonts/22AE77_0_0.eot");
src:url("/webfonts/22AE77_0_0.eot?#iefix") format("embedded-opentype"), url("/webfonts/22AE77_0_0.woff") format("woff"), url("/webfonts/22AE77_0_0.ttf") format("truetype");}
*{margin:0;
padding:0;}
html{overflow-y:scroll;}
body{color:#000;
font:12px "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height:1.5;
text-rendering:optimizeLegibility;
background:#262626;
background-image:url('/images/background.jpg');}
a{text-decoration:none;}
a:hover{text-decoration:underline;}
img{border:0;
vertical-align:top;}
li{list-style-position:inside;}
h4{font-size:16px;
line-height:1.25;
font-weight:bold;}
h5{font-size:14px;
line-height:1.286;
font-weight:bold;}
button:focus{outline:none;}
input[type="submit"]:focus, input[type="button"]:focus, input[type="cancel"]:focus, input[type="reset"]:focus{outline:none;}
.bar{height:35px;
line-height:35px;
padding:0 10px 0 40px;
color:#666;
font-size:13px;
text-shadow:1px 1px 0 rgba(255, 255, 255, .8);
box-shadow:inset 0 -1px 0 rgba(0, 0, 0, .1);
background:url('/images/icons.png') no-repeat -4px -408px #e9e9e9;}
.bar h4{float:left;
width:130px;
margin:0;
padding:0;
font-size:13px;
line-height:35px;
text-overflow:ellipsis;
overflow:hidden;}
.bar span{float:right;
font-style:italic;
opacity:.7;}
.clear{clear:both;}
.nick{text-transform:capitalize;}
.main, .footer{width:980px;}
.main{margin:40px auto 20px;
padding:20px 0;
border:1px solid #fff;
border-bottom:1px solid #fff;
background:transparent url(/images/transparent_pxl_white-90.png);
background:rgba(255, 255, 255, 0.9);
box-shadow:0 0 5px rgba(0, 0, 0, 0.35);
-moz-box-shadow:0 0 5px rgba(0, 0, 0, 0.35);
-webkit-box-shadow:0 0 5px rgba(0, 0, 0, 0.35);}
.wrapper{width:940px;
margin:0 auto;
padding:0 20px;
position:relative;}
.primary_button, .normal_button{border-radius:3px;
-moz-border-radius:3px;
-webkit-border-radius:3px;
display:inline-block;
position:relative;
vertical-align:baseline;
font-size:inherit;
font-weight:500;
border:1px solid #000;
background:none;
cursor:pointer;
font-family:inherit;
font-weight:bold;
width:1;
overflow:visible;}
.primary_button span, .normal_button span{display:inline-block;
height:18px;
padding:5px 9px;
white-space:nowrap;
line-height:18px;}
.primary_button{background:-webkit-gradient(linear, left top, left bottom, from(#8266b6), to(#533787));
background:-moz-linear-gradient(top, #8266b6, #533787);
background:-o-linear-gradient(top, #8266b6, #533787);
background:linear-gradient(top, #8266b6, #533787);
background-color:#6a4e9e;
border-top:1px solid #5b3f8f;
border-left:1px solid #412771;
border-right:1px solid #412771;
border-bottom:1px solid #2a1453;
box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(0, 0, 0, 0.15);
-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(0, 0, 0, 0.15);
-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(0, 0, 0, 0.15);
text-shadow:0 1px 0 rgba(0, 0, 0, 0.75);
-moz-text-shadow:0 1px 0 rgba(0, 0, 0, 0.75);
-webkit-text-shadow:0 1px 0 rgba(0, 0, 0, 0.75);
color:#fff;}
.normal_button{background:-webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#ddd));
background:-moz-linear-gradient(top, #f5f5f5, #ddd);
background:-o-linear-gradient(top, #f5f5f5, #ddd);
background:linear-gradient(top, #f5f5f5, #ddd);
background-color:#e9e9e9;
border-top:1px solid rgba(0, 0, 0, 0.2);
border-left:1px solid rgba(0, 0, 0, 0.3);
border-right:1px solid rgba(0, 0, 0, 0.3);
border-bottom:1px solid rgba(0, 0, 0, 0.35);
box-shadow:inset 0 1px 0 #fff, 0 1px 0 rgba(0, 0, 0, 0.07);
-moz-box-shadow:inset 0 1px 0 #fff, 0 1px 0 rgba(0, 0, 0, 0.07);
-webkit-box-shadow:inset 0 1px 0 #fff, 0 1px 0 rgba(0, 0, 0, 0.07);
text-shadow:0 1px 0 rgba(255, 255, 255, 0.75);
-moz-text-shadow:0 1px 0 rgba(255, 255, 255, 0.75);
-webkit-text-shadow:0 1px 0 rgba(255, 255, 255, 0.75);}
a.button:hover, a.primary_button:hover, a.normal_button:hover{text-decoration:none;}
.form_submit{float:right;
margin-top:0;
margin-right:5px}
.auction_status{display:block;
float:right;
margin:-8px -8px 5px 0;
padding:0;
width:55px;
height:50px;
font-size:12px;
line-height:40px;
color:#E3DAF2;
background:url('/images/vector-web-icons.png') no-repeat 0 0 transparent;
border:0;
opacity:.2;
text-indent:100%;
overflow:hidden;
background-position:-160px -268px;}
.section_header{margin-bottom:10px;
color:#666;}
.bottom_box{border:1px solid #ccc;
border-top:none;
border-radius:0;
-moz-border-radius:0;
-webkit-border-radius:0;
background:#f1f1f1;}
#mantle_skin{z-index:-1000;}
#site_footer{margin:0 auto;
padding-bottom:60px;}
#site_footer a{color:#fff;
font-weight:500;
text-shadow:0 1px 0 #000;}
#footer_archonbot{float:left;
vertical-align:top;}
#footer_links{float:left;}
#footer_links li{display:inline;
display:inline-block;
margin:0 6px;}
#copyright_and_languages{float:right;
color:#666;}
#copyright_and_languages #copyright{margin-left:10px;}
#chat_lines{height:346px;
padding:10px 5px 10px 10px}
#twitch_chat{margin-bottom:10px;
border:1px solid #ccc;
border-radius:4px;}
#chat_line_list li{list-style:none;}
#chat_line_list li p{margin-bottom:5px;}
#chat_line_list li .nick{font-weight:bold;
text-transform:capitalize;}
#auction_submit_buttons{margin:0 -5px 0 0;
height:25px}
#auction_lines{height:173px;
margin-bottom:10px;
border:1px solid #ccc;
border-radius:4px;}
#irc_submit{float:right;
margin-top:-37px;}
#auction_box{width:325px;
margin-bottom:10px;}
#auction_box, #chat{position:relative;
padding:15px;
border:1px solid #CCC;
border-radius:0;
-moz-border-radius:0;
-webkit-border-radius:0;
border-top-right-radius:5px;
border-top-left-radius:5px;
-moz-border-radius-topright:5px;
-moz-border-radius-topleft:5px;
-webkit-border-top-left-radius:5px;
-webkit-border-top-right-radius:5px;
border-bottom-right-radius:5px;
border-bottom-left-radius:5px;
-moz-border-radius-bottomright:5px;
-moz-border-radius-bottomleft:5px;
-webkit-border-bottom-left-radius:5px;
-webkit-border-bottom-right-radius:5px;
background:#F1F1F1;}

208
lib/dashboard/css/jquery.mCustomScrollbar.css

@ -0,0 +1,208 @@
/* basic scrollbar styling */
/* vertical scrollbar */
.mCSB_container{
width:auto;
margin-right:30px;
overflow:hidden;
}
.mCSB_container.mCS_no_scrollbar{
margin-right:0;
}
.mCS_disabled .mCSB_container.mCS_no_scrollbar,
.mCS_destroyed .mCSB_container.mCS_no_scrollbar{
margin-right:30px;
}
.mCustomScrollBox .mCSB_scrollTools{
width:16px;
height:100%;
top:0;
right:-5px;
}
.mCSB_scrollTools .mCSB_draggerContainer{
height:100%;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
}
.mCSB_scrollTools .mCSB_buttonUp+.mCSB_draggerContainer{
padding-bottom:40px;
}
.mCSB_scrollTools .mCSB_draggerRail{
width:5px;
height:100%;
margin:0 auto;
-webkit-border-radius:10px;
-moz-border-radius:10px;
border-radius:10px;
}
.mCSB_scrollTools .mCSB_dragger{
cursor:pointer;
width:100%;
height:30px;
}
.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{
width:5px;
height:100%;
margin:0 auto;
-webkit-border-radius:10px;
-moz-border-radius:10px;
border-radius:10px;
text-align:center;
}
.mCSB_scrollTools .mCSB_buttonUp,
.mCSB_scrollTools .mCSB_buttonDown{
height:20px;
overflow:hidden;
margin:0 auto;
cursor:pointer;
}
.mCSB_scrollTools .mCSB_buttonDown{
bottom:0;
margin-top:-40px;
}
/* horizontal scrollbar */
.mCSB_horizontal .mCSB_container{
height:auto;
margin-right:0;
margin-bottom:30px;
overflow:hidden;
}
.mCSB_horizontal .mCSB_container.mCS_no_scrollbar{
margin-bottom:0;
}
.mCS_disabled .mCSB_horizontal .mCSB_container.mCS_no_scrollbar,
.mCS_destroyed .mCSB_horizontal .mCSB_container.mCS_no_scrollbar{
margin-right:0;
margin-bottom:30px;
}
.mCSB_horizontal.mCustomScrollBox .mCSB_scrollTools{
width:100%;
height:16px;
top:auto;
right:auto;
bottom:0;
left:0;
overflow:hidden;
}
.mCSB_horizontal .mCSB_scrollTools .mCSB_draggerContainer{
height:100%;
width:auto;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
overflow:hidden;
}
.mCSB_horizontal .mCSB_scrollTools .mCSB_buttonLeft+.mCSB_draggerContainer{
padding-bottom:0;
padding-right:20px;
}
.mCSB_horizontal .mCSB_scrollTools .mCSB_draggerRail{
width:100%;
height:2px;
margin:7px 0;
-webkit-border-radius:10px;
-moz-border-radius:10px;
border-radius:10px;
}
.mCSB_horizontal .mCSB_scrollTools .mCSB_dragger{
width:30px;
height:100%;
}
.mCSB_horizontal .mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{
width:100%;
height:4px;
margin:6px auto;
-webkit-border-radius:10px;
-moz-border-radius:10px;
border-radius:10px;
}
.mCSB_horizontal .mCSB_scrollTools .mCSB_buttonLeft,
.mCSB_horizontal .mCSB_scrollTools .mCSB_buttonRight{
width:20px;
height:100%;
overflow:hidden;
margin:0 auto;
cursor:pointer;
float:left;
}
.mCSB_horizontal .mCSB_scrollTools .mCSB_buttonRight{
right:0;
bottom:auto;
margin-left:-40px;
margin-top:-16px;
float:right;
}
/* default scrollbar colors and backgrounds */
.mCustomScrollBox .mCSB_scrollTools{
opacity:0.75;
}
.mCustomScrollBox:hover .mCSB_scrollTools{
opacity:1;
}
.mCSB_scrollTools .mCSB_draggerRail{
background:#000; /* rgba fallback */
background:rgba(0,0,0,0.4);
filter:"alpha(opacity=40)"; -ms-filter:"alpha(opacity=40)"; /* old ie */
}
.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{
background:#fff; /* rgba fallback */
background:rgba(42,255,0,0.75);
filter:"alpha(opacity=75)"; -ms-filter:"alpha(opacity=75)"; /* old ie */
}
.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{
background:rgba(42,255,0,0.85);
filter:"alpha(opacity=85)"; -ms-filter:"alpha(opacity=85)"; /* old ie */
}
.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar,
.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{
background:rgba(42,255,0,0.9);
filter:"alpha(opacity=90)"; -ms-filter:"alpha(opacity=90)"; /* old ie */
}
.mCSB_scrollTools .mCSB_buttonUp,
.mCSB_scrollTools .mCSB_buttonDown,
.mCSB_scrollTools .mCSB_buttonLeft,
.mCSB_scrollTools .mCSB_buttonRight{
background-image:url(mCSB_buttons.png);
background-repeat:no-repeat;
opacity:0.4;
filter:"alpha(opacity=40)"; -ms-filter:"alpha(opacity=40)"; /* old ie */
}
.mCSB_scrollTools .mCSB_buttonUp{
background-position:0 0;
/*
sprites locations are 0 0/-16px 0/-32px 0/-48px 0 (light) and -80px 0/-96px 0/-112px 0/-128px 0 (dark)
*/
}
.mCSB_scrollTools .mCSB_buttonDown{
background-position:0 -20px;
/*
sprites locations are 0 -20px/-16px -20px/-32px -20px/-48px -20px (light) and -80px -20px/-96px -20px/-112px -20px/-128px -20px (dark)
*/
}
.mCSB_scrollTools .mCSB_buttonLeft{
background-position:0 -40px;
/*
sprites locations are 0 -40px/-20px -40px/-40px -40px/-60px -40px (light) and -80px -40px/-100px -40px/-120px -40px/-140px -40px (dark)
*/
}
.mCSB_scrollTools .mCSB_buttonRight{
background-position:0 -56px;
/*
sprites locations are 0 -56px/-20px -56px/-40px -56px/-60px -56px (light) and -80px -56px/-100px -56px/-120px -56px/-140px -56px (dark)
*/
}
.mCSB_scrollTools .mCSB_buttonUp:hover,
.mCSB_scrollTools .mCSB_buttonDown:hover,
.mCSB_scrollTools .mCSB_buttonLeft:hover,
.mCSB_scrollTools .mCSB_buttonRight:hover{
opacity:0.75;
filter:"alpha(opacity=75)"; -ms-filter:"alpha(opacity=75)"; /* old ie */
}
.mCSB_scrollTools .mCSB_buttonUp:active,
.mCSB_scrollTools .mCSB_buttonDown:active,
.mCSB_scrollTools .mCSB_buttonLeft:active,
.mCSB_scrollTools .mCSB_buttonRight:active{
opacity:0.9;
filter:"alpha(opacity=90)"; -ms-filter:"alpha(opacity=90)"; /* old ie */
}

85
lib/dashboard/dashboard.html

@ -0,0 +1,85 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>#{{channelname}} Dashboard - {{botname}}</title>
<link href="http://www.twitch.tv/favicon.ico" rel="shortcut icon" type="image/x-icon"/>
<link href="/css/dashboard.css" media="screen" rel="stylesheet"/>
<link href="/css/jquery.mCustomScrollbar.css" media="screen" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="/js/jquery.mousewheel.min.js"></script>
<script src="/js/jquery.mCustomScrollbar.js"></script>
<script src="/js/actions.js"></script>
</head>
<body>
<div id="mantle_skin">
<div class="main" id="container">
<div class="wrapper" id="dash_main">
<div id="auction_box">
<div class="auction_status">Close</div>
<h4 class="section_header">Arcoins Auction</h4>
<h5 class="section_header" id="auction_highest_bid">Status: <span style="color:blueviolet">Closed</span></h5>
<div id="auction_lines" class="auction-scroll clear">
<div class="bar">
<h4>Messages</h4>
<span>updating in real time</span>
</div>
<ul id="auction_line_list"></ul>
<div id="auction_line_end"></div>
</div>
<div id="auction_submit_buttons">
<form id="auction_open" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="authenticity_token" type="hidden" value=""/>
<input name="user" type="hidden" value="{{user}}"/>
</div>
<div class="form_submit">
<button class="primary_button" tabindex="5" type="submit"><span>Open Auction</span></button>
</div>
</form>
<form id="auction_close" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="authenticity_token" type="hidden" value=""/>
<input name="user" type="hidden" value="{{user}}"/>
</div>
<div class="form_submit">
<button class="primary_button" tabindex="4" type="submit"><span>Close Auction</span></button>
</div>
</form>
</div>
</div>
<div class="clear" id="chat">
<h4 class="section_header">Twitch IRC Raw Chat</h4>
<form id="irc_reconnect" class="simple_form clearfix" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="authenticity_token" type="hidden" value=""/>
</div>
<div id="irc_submit">
<button class="normal_button" tabindex="5" type="submit"><span>Reconnect</span></button>
</div>
</form>
<div id="twitch_chat" class="chat_box">
<div class="bar">
<h4>Messages</h4>
<span>updating in real time</span>
</div>
<div id="chat_lines" class="chat-scroll">
<ul id="chat_line_list"></ul>
<div id="chat_line_end"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="footer clearfix" id="site_footer">
<p id="copyright_and_languages">
<span id="copyright">© ArchonBot 2013, © Justin.tv Inc. 2013</span>
</p>
<img alt="ArchonBot" id="footer_archonbot" src="/images/archonbot.png" width="126" height="175"/>
<ul id="footer_links">
<li><a href="https://github.com/SupremoRTD/ArchonBot">ArchonBot on GitHub</a></li>
</ul>
</div>
</body>
</html>

175
lib/dashboard/dashboard.js

@ -0,0 +1,175 @@
var file = require('fs'),
http = require('http'),
querystring = require('querystring'),
mustache = require('mustache');
function Server(irc, options) {
var __self = this;
__self.options = options || {};
__self.irc = irc;
//config
__self.root = __self.options.root || '';
__self.channel = __self.options.channel.toLowerCase() || '';
__self.bot = __self.options.bot_name || '';
__self.port = __self.options.dashboard_id || '';
}
Server.prototype.start = function () {
var __self = this;
http.createServer(function (request, response) {
var handle, patterns, rest_uri, match, mimes;
mimes = [
{css: 'text/css', encoding: 'utf8'},
{js: 'application/javascript', encoding: 'utf8'},
{html: 'text/html', encoding: 'utf8'},
{jpg: 'image/jpeg', encoding: 'binary'},
{png: 'image/png', encoding: 'binary'},
{gif: 'image/gif', encoding: 'binary'},
{eot: 'application/vnd.ms-fontobject', encoding: 'binary'},
{otf: 'application/octet-stream', encoding: 'binary'},
{ttf: 'application/octet-stream', encoding: 'binary'},
{woff: 'application/x-font-woff', encoding: 'binary'}
];
// remove start and end slashes
rest_uri = request.url.replace(/^\/|\/$/i, '');
// reg patterns
patterns = {
realtimechat: /get\/chat$/i,
dashboard: /v1\/dashboard$/i,
actions: /actions$/i,
all: /(.*\/)(.*)\.(\w+)$|(.*)\.(\w+)$/i
};
// match with patterns
for (var key in patterns) {
if (patterns[key].test(rest_uri)) {
match = rest_uri.match(patterns[key]);
handle = key;
break;
}
}
// organize requests
if (handle == 'realtimechat') {
response.writeHead(200, {'Content-Type': 'application/json'});
file.exists(__self.log, function (exists) {
if (exists) {
file.readFile(__self.log, 'utf8', function (err, data) {
if (data !== null) {
var json = [];
data = data.split('\r\n');
for (var i = 0; i < data.length - 1; i++) {
json[i] = {id: i, text: data[i]};
}
response.end(JSON.stringify(json));
}
// TODO: fix up the json request so it takes less memory
/*if (data !== null) {
var json = [], max_length;
data = data.split('\r\n');
max_length = data.length > 200 ? 200 : data.length;
for (var i = 0; i < max_length; i++) {
var check_length = data.length > 200 ? (data.length - 200) + i : i;
json[i] = {id: check_length, text: data[check_length]};
}
response.end(JSON.stringify(json));
}*/
});
} else {
response.end('{"Error":"Chat does not exist"}');
}
});
}
if (handle == 'dashboard') {
file.readFile(__self.root + '/dashboard.html', 'utf8', function (err, data) {
var template = {botname: __self.bot, channelname: __self.channel, user: __self.channel.charAt(0).toUpperCase() + __self.channel.slice(0).toLowerCase()};
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(mustache.render(data, template));
});
}
if (handle == 'actions') {
if (request.method == 'POST') {
var post_header = '';
request.on('data', function (chunk) {
post_header += chunk.toString();
});
request.on('end', function () {
var decoded_header = querystring.parse(post_header);
response.writeHead(200, {'Content-Type': 'text/html'});
switch(decoded_header._method) {
case 'reconnect':
__self.irc.reconnect();
response.end();
break;
case 'auction_open':
__self.irc.msg('!arcoins auction open');
response.end();
break;
case 'auction_close':
__self.irc.msg('!arcoins auction close');
response.end();
break;
default:
response.end();
}
});
}
}
if (handle == 'all') {
file.exists(__self.root + '/' + match[0], function (exists) {
if (exists) {
var mime, encoding;
for (var i = 0; i < mimes.length; i++) {
for (var key in mimes[i]) {
if (match[3] == key || match[5] == key) {
mime = mimes[i][key];
encoding = mimes[i].encoding;
break;
}
}
}
file.readFile(__self.root + '/' + match[0], encoding, function (err, data) {
response.writeHead(200, {'Content-Type': mime});
if (encoding == 'binary') {
response.end(data, 'binary');
} else {
response.end(data);
}
});
} else {
fourohfour();
}
});
}
if (handle === undefined) {
fourohfour();
}
function fourohfour() {
file.readFile(__self.root + '/404.html', 'utf8', function (err, data) {
response.writeHead(404, {'Content-Type': 'text/html'});
response.end(data);
});
}
}).listen(__self.port);
console.log('> Dashboard for ' + __self.bot + ' running on http://localhost:' + __self.port + '/v1/dashboard');
};
module.exports = function (irc, options) {
return new Server(irc, options);
};

BIN
lib/dashboard/images/archonbot.png

After

Width: 126  |  Height: 175  |  Size: 14 KiB

BIN
lib/dashboard/images/background.jpg

After

Width: 1000  |  Height: 1000  |  Size: 80 KiB

BIN
lib/dashboard/images/icons.png

After

Width: 100  |  Height: 700  |  Size: 18 KiB

0
lib/dashboard/images/transparent_pxl_white-90.png

BIN
lib/dashboard/images/vector-web-icons.png

After

Width: 600  |  Height: 493  |  Size: 195 KiB

167
lib/dashboard/js/actions.js

@ -0,0 +1,167 @@
//-------- Realtime Chat --------
(function ($) {
var previous_chat = [], origin = window.location.origin;
function get_chat() {
$.ajax({
url: origin + '/get/chat',
success: function (data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
if (data[key].id !== undefined || data[key].text !== undefined) {
if (previous_chat.indexOf(data[key].id) < 0) {
// add line id to array
previous_chat.push(data[key].id);
// separate words
var data_split = data[key].text.split(' ');
//-------- Raw IRC Module --------
update_raw_irc_module(data_split);
update_scrollbar();
//-------- Auction Module --------
update_auction_module(data_split);
}
}
}
}
get_chat();
},
error: function (x, t) {
if (t === 'timeout') {
$('#chat_line_list').append('<li class="line jtv"><p><span class="chat_line">Server: Request timed out, trying to reconnect (server may be offline)</span></p></li>');
update_scrollbar();
}
get_chat();
}, dataType: "json", timeout: 30000
});
}
// start "realtime" chat
get_chat();
function update_scrollbar () {
// update scrollbar
$('.chat-scroll').mCustomScrollbar("update");
$('.chat-scroll').mCustomScrollbar("scrollTo","#chat_line_end");
}
function update_raw_irc_module (data) {
// raw irc status colors
switch(data[0]) {
case 'SENT':
data.splice(0, 1, '<span class="nick" style="color:dodgerblue">' + data[0] + '&nbsp;</span>');
break;
case 'RECV':
data.splice(0, 1, '<span class="nick" style="color:red">' + data[0] + '&nbsp;</span>');
break;
}
// raw irc message / server response colors
if (data[3] === 'PRIVMSG') {
var user = data[2].split('!');
if (user.length > 1) {
data.splice(2, 1, '<span style="color:blueviolet;font-style:italic;font-weight:bold">' + user[0].slice(1).charAt(0).toUpperCase() + user[0].slice(2).toLowerCase() + '</span>');
} else {
data.splice(2, 1, '<span style="color:blueviolet;font-style:italic;font-weight:bold">' + user + '</span>');
}
data.splice(3, 1, '<span style="color:blueviolet;font-style:italic;font-weight:bold">' + data[3] + '</span>');
data.splice(4, 1, '<span style="color:#666;font-style:italic">' + data[4] + '</span>');
data.splice(5, 1, data[5].slice(1));
} else {
for (var i = 2; i < data.length; i++) {
if (i === 2) {
data.splice(i, 1, '<span style="color:#666;font-style:italic">' + data[i]);
} else if (i === data.length - 1) {
data.splice(i, 1, data[i] + '</span>');
}
}
}
// add chat line to view
if (data[3] !== '352') {
$('#chat_line_list').append('<li class="line jtv"><p><span class="chat_line">' + data.join(' ') + '</span></p></li>');
}
// remove first chat line if over limit
if (previous_chat.length > 200 && $('#chat_line_list li').length > 200) {
$('#chat_line_list li').first().remove();
previous_chat = previous_chat.slice(1);
}
}
function update_auction_module (data) {
var data_text = '';
for (var i = 6; i < data.length; i++) {
data_text += i !== data.length - 1 ? data[i] + ' ' : data[i];
}
// set auction info
if (data_text === 'Auction opened, accepting bids') {
$('.auction_status').css({'opacity':'1', 'background-position': '-230px -268px'}).text('Opened');
$('#auction_highest_bid').html('').text('Status: ').append('<span style="color: blueviolet">Checking Bids...</span>');
}
if (data[6] + ' ' + data[7] === 'Highest bid,') {
$('#auction_highest_bid').html('').text('Highest Bid: ').append('<span style="color: blueviolet">' + data[8] + ' @ ' + data[10] + '</span>');
}
if (data[6] + ' ' + data[7] + ' ' + data[8] == 'Auction closed, Winner:') {
$('.auction_status').css({'opacity': '.2', 'background-position': '-160px -268px'}).text('Closed');
$('#auction_highest_bid').html('').text('Winner: ').append('<span style="color: blueviolet">' + data[9] + ' @ ' + data[11] + '</span>');
}
if (data_text === 'Auction closed, no bidders to pick a winner') {
$('.auction_status').css({'opacity': '.2', 'background-position': '-160px -268px'}).text('Closed');
$('#auction_highest_bid').html('').text('Status: ').append('<span style="color: blueviolet">Closed</span>');
}
}
})(jQuery);
//-------- Scrollbars --------
(function ($) {
$(document).ready(function () {
$('.auction-scroll').mCustomScrollbar({
scrollInertia:0,
advanced:{
updateOnContentResize: true
}
});
$('.chat-scroll').mCustomScrollbar({
scrollInertia:0,
advanced:{
updateOnContentResize: true
}
});
});
})(jQuery);
//-------- Form Actions --------
(function ($) {
$(document).ready(function () {
// reconnect to irc
$('#irc_reconnect').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: window.location.origin + '/actions',
data: {_method: 'reconnect', auth_token: $(this).find('input[name="authenticity_token"]').val()}
});
});
// open / close auction
$('#auction_open').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: window.location.origin + '/actions',
data: {_method: 'auction_open', auth_token: $(this).find('input[name="authenticity_token"]').val(), user: $(this).find('input[name="user"]').val()}
});
});
$('#auction_close').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: window.location.origin + '/actions',
data: {_method: 'auction_close', auth_token: $(this).find('input[name="authenticity_token"]').val(), user: $(this).find('input[name="user"]').val()}
});
});
});
})(jQuery);

874
lib/dashboard/js/jquery.mCustomScrollbar.js

@ -0,0 +1,874 @@
/*
== malihu jquery custom scrollbars plugin ==
version: 2.3.2
author: malihu (http://manos.malihu.gr)
plugin home: http://manos.malihu.gr/jquery-custom-content-scroller
*/
(function($){
var methods={
init:function(options){
var defaults={
set_width:false, /*optional element width: boolean, pixels, percentage*/
set_height:false, /*optional element height: boolean, pixels, percentage*/
horizontalScroll:false, /*scroll horizontally: boolean*/
scrollInertia:550, /*scrolling inertia: integer (milliseconds)*/
scrollEasing:"easeOutCirc", /*scrolling easing: string*/
mouseWheel:"pixels", /*mousewheel support and velocity: boolean, "auto", integer, "pixels"*/
mouseWheelPixels:60, /*mousewheel pixels amount: integer*/
autoDraggerLength:true, /*auto-adjust scrollbar dragger length: boolean*/
scrollButtons:{ /*scroll buttons*/
enable:false, /*scroll buttons support: boolean*/
scrollType:"continuous", /*scroll buttons scrolling type: "continuous", "pixels"*/
scrollSpeed:20, /*scroll buttons continuous scrolling speed: integer*/
scrollAmount:40 /*scroll buttons pixels scroll amount: integer (pixels)*/
},
advanced:{
updateOnBrowserResize:true, /*update scrollbars on browser resize (for layouts based on percentages): boolean*/
updateOnContentResize:false, /*auto-update scrollbars on content resize (for dynamic content): boolean*/
autoExpandHorizontalScroll:false, /*auto-expand width for horizontal scrolling: boolean*/
autoScrollOnFocus:true /*auto-scroll on focused elements: boolean*/
},
callbacks:{
onScrollStart:function(){}, /*user custom callback function on scroll start event*/
onScroll:function(){}, /*user custom callback function on scroll event*/
onTotalScroll:function(){}, /*user custom callback function on scroll end reached event*/
onTotalScrollBack:function(){}, /*user custom callback function on scroll begin reached event*/
onTotalScrollOffset:0, /*scroll end reached offset: integer (pixels)*/
whileScrolling:false, /*user custom callback function on scrolling event*/
whileScrollingInterval:30 /*interval for calling whileScrolling callback: integer (milliseconds)*/
}
},
options=$.extend(true,defaults,options);
/*check for touch device*/
$(document).data("mCS-is-touch-device",false);
if(is_touch_device()){
$(document).data("mCS-is-touch-device",true);
}
function is_touch_device(){
return !!("ontouchstart" in window) ? 1 : 0;
}
return this.each(function(){
var $this=$(this);
/*set element width/height, create markup for custom scrollbars, add classes*/
if(options.set_width){
$this.css("width",options.set_width);
}
if(options.set_height){
$this.css("height",options.set_height);
}
if(!$(document).data("mCustomScrollbar-index")){
$(document).data("mCustomScrollbar-index","1");
}else{
var mCustomScrollbarIndex=parseInt($(document).data("mCustomScrollbar-index"));
$(document).data("mCustomScrollbar-index",mCustomScrollbarIndex+1);
}
$this.wrapInner("<div class='mCustomScrollBox' id='mCSB_"+$(document).data("mCustomScrollbar-index")+"' style='position:relative; height:100%; overflow:hidden; max-width:100%;' />").addClass("mCustomScrollbar _mCS_"+$(document).data("mCustomScrollbar-index"));
var mCustomScrollBox=$this.children(".mCustomScrollBox");
if(options.horizontalScroll){
mCustomScrollBox.addClass("mCSB_horizontal").wrapInner("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />");
var mCSB_h_wrapper=mCustomScrollBox.children(".mCSB_h_wrapper");
mCSB_h_wrapper.wrapInner("<div class='mCSB_container' style='position:absolute; left:0;' />").children(".mCSB_container").css({"width":mCSB_h_wrapper.children().outerWidth(),"position":"relative"}).unwrap();
}else{
mCustomScrollBox.wrapInner("<div class='mCSB_container' style='position:relative; top:0;' />");
}
var mCSB_container=mCustomScrollBox.children(".mCSB_container");
if($(document).data("mCS-is-touch-device")){
mCSB_container.addClass("mCS_touch");
}
mCSB_container.after("<div class='mCSB_scrollTools' style='position:absolute;'><div class='mCSB_draggerContainer' style='position:relative;'><div class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' style='position:relative;'></div></div><div class='mCSB_draggerRail'></div></div></div>");
var mCSB_scrollTools=mCustomScrollBox.children(".mCSB_scrollTools"),
mCSB_draggerContainer=mCSB_scrollTools.children(".mCSB_draggerContainer"),
mCSB_dragger=mCSB_draggerContainer.children(".mCSB_dragger");
if(options.horizontalScroll){
mCSB_dragger.data("minDraggerWidth",mCSB_dragger.width());
}else{
mCSB_dragger.data("minDraggerHeight",mCSB_dragger.height());
}
if(options.scrollButtons.enable){
if(options.horizontalScroll){
mCSB_scrollTools.prepend("<a class='mCSB_buttonLeft' style='display:block; position:relative;'></a>").append("<a class='mCSB_buttonRight' style='display:block; position:relative;'></a>");
}else{
mCSB_scrollTools.prepend("<a class='mCSB_buttonUp' style='display:block; position:relative;'></a>").append("<a class='mCSB_buttonDown' style='display:block; position:relative;'></a>");
}
}
/*mCustomScrollBox scrollTop and scrollLeft is always 0 to prevent browser focus scrolling*/
mCustomScrollBox.bind("scroll",function(){
if(!$this.is(".mCS_disabled")){ /*native focus scrolling for disabled scrollbars*/
mCustomScrollBox.scrollTop(0).scrollLeft(0);
}
});
/*store options, global vars/states, intervals and update element*/
$this.data({
/*init state*/
"mCS_Init":true,
/*option parameters*/
"horizontalScroll":options.horizontalScroll,
"scrollInertia":options.scrollInertia,
"scrollEasing":options.scrollEasing,
"mouseWheel":options.mouseWheel,
"mouseWheelPixels":options.mouseWheelPixels,
"autoDraggerLength":options.autoDraggerLength,
"scrollButtons_enable":options.scrollButtons.enable,
"scrollButtons_scrollType":options.scrollButtons.scrollType,
"scrollButtons_scrollSpeed":options.scrollButtons.scrollSpeed,
"scrollButtons_scrollAmount":options.scrollButtons.scrollAmount,
"autoExpandHorizontalScroll":options.advanced.autoExpandHorizontalScroll,
"autoScrollOnFocus":options.advanced.autoScrollOnFocus,
"onScrollStart_Callback":options.callbacks.onScrollStart,
"onScroll_Callback":options.callbacks.onScroll,
"onTotalScroll_Callback":options.callbacks.onTotalScroll,
"onTotalScrollBack_Callback":options.callbacks.onTotalScrollBack,
"onTotalScroll_Offset":options.callbacks.onTotalScrollOffset,
"whileScrolling_Callback":options.callbacks.whileScrolling,
"whileScrolling_Interval":options.callbacks.whileScrollingInterval,
/*events binding state*/
"bindEvent_scrollbar_click":false,
"bindEvent_mousewheel":false,
"bindEvent_focusin":false,
"bindEvent_buttonsContinuous_y":false,
"bindEvent_buttonsContinuous_x":false,
"bindEvent_buttonsPixels_y":false,
"bindEvent_buttonsPixels_x":false,
"bindEvent_scrollbar_touch":false,
"bindEvent_content_touch":false,
/*buttons intervals*/
"mCSB_buttonScrollRight":false,
"mCSB_buttonScrollLeft":false,
"mCSB_buttonScrollDown":false,
"mCSB_buttonScrollUp":false,
/*callback intervals*/
"whileScrolling":false
}).mCustomScrollbar("update");
/*detect max-width*/
if(options.horizontalScroll){
if($this.css("max-width")!=="none"){
if(!options.advanced.updateOnContentResize){ /*needs updateOnContentResize*/
options.advanced.updateOnContentResize=true;
}
$this.data({"mCS_maxWidth":parseInt($this.css("max-width")),"mCS_maxWidth_Interval":setInterval(function(){
if(mCSB_container.outerWidth()>$this.data("mCS_maxWidth")){
clearInterval($this.data("mCS_maxWidth_Interval"));
$this.mCustomScrollbar("update");
}
},150)});
}
}else{
/*detect max-height*/
if($this.css("max-height")!=="none"){
$this.data({"mCS_maxHeight":parseInt($this.css("max-height")),"mCS_maxHeight_Interval":setInterval(function(){
mCustomScrollBox.css("max-height",$this.data("mCS_maxHeight"));
if(mCSB_container.outerHeight()>$this.data("mCS_maxHeight")){
clearInterval($this.data("mCS_maxHeight_Interval"));
$this.mCustomScrollbar("update");
}
},150)});
}
}
/*window resize fn (for layouts based on percentages)*/
if(options.advanced.updateOnBrowserResize){
var mCSB_resizeTimeout;
$(window).resize(function(){
if(mCSB_resizeTimeout){
clearTimeout(mCSB_resizeTimeout);
}
mCSB_resizeTimeout=setTimeout(function(){
if(!$this.is(".mCS_disabled") && !$this.is(".mCS_destroyed")){
$this.mCustomScrollbar("update");
}
},150);
});
}
/*content resize fn (for dynamically generated content)*/
if(options.advanced.updateOnContentResize){
var mCSB_onContentResize;
if(options.horizontalScroll){
var mCSB_containerOldSize=mCSB_container.outerWidth();
}else{
var mCSB_containerOldSize=mCSB_container.outerHeight();
}
mCSB_onContentResize=setInterval(function(){
if(options.horizontalScroll){
if(options.advanced.autoExpandHorizontalScroll){
mCSB_container.css({"position":"absolute","width":"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({"width":mCSB_container.outerWidth(),"position":"relative"}).unwrap();
}
var mCSB_containerNewSize=mCSB_container.outerWidth();
}else{
var mCSB_containerNewSize=mCSB_container.outerHeight();
}
if(mCSB_containerNewSize!=mCSB_containerOldSize){
$this.mCustomScrollbar("update");
mCSB_containerOldSize=mCSB_containerNewSize;
}
},300);
}
});
},
update:function(){
var $this=$(this),
mCustomScrollBox=$this.children(".mCustomScrollBox"),
mCSB_container=mCustomScrollBox.children(".mCSB_container");
mCSB_container.removeClass("mCS_no_scrollbar");
$this.removeClass("mCS_disabled mCS_destroyed");
mCustomScrollBox.scrollTop(0).scrollLeft(0); /*reset scrollTop/scrollLeft to prevent browser focus scrolling*/
var mCSB_scrollTools=mCustomScrollBox.children(".mCSB_scrollTools"),
mCSB_draggerContainer=mCSB_scrollTools.children(".mCSB_draggerContainer"),
mCSB_dragger=mCSB_draggerContainer.children(".mCSB_dragger");
if($this.data("horizontalScroll")){
var mCSB_buttonLeft=mCSB_scrollTools.children(".mCSB_buttonLeft"),
mCSB_buttonRight=mCSB_scrollTools.children(".mCSB_buttonRight"),
mCustomScrollBoxW=mCustomScrollBox.width();
if($this.data("autoExpandHorizontalScroll")){
mCSB_container.css({"position":"absolute","width":"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({"width":mCSB_container.outerWidth(),"position":"relative"}).unwrap();
}
var mCSB_containerW=mCSB_container.outerWidth();
}else{
var mCSB_buttonUp=mCSB_scrollTools.children(".mCSB_buttonUp"),
mCSB_buttonDown=mCSB_scrollTools.children(".mCSB_buttonDown"),
mCustomScrollBoxH=mCustomScrollBox.height(),
mCSB_containerH=mCSB_container.outerHeight();
}
if(mCSB_containerH>mCustomScrollBoxH && !$this.data("horizontalScroll")){ /*content needs vertical scrolling*/
mCSB_scrollTools.css("display","block");
var mCSB_draggerContainerH=mCSB_draggerContainer.height();
/*auto adjust scrollbar dragger length analogous to content*/
if($this.data("autoDraggerLength")){
var draggerH=Math.round(mCustomScrollBoxH/mCSB_containerH*mCSB_draggerContainerH),
minDraggerH=mCSB_dragger.data("minDraggerHeight");
if(draggerH<=minDraggerH){ /*min dragger height*/
mCSB_dragger.css({"height":minDraggerH});
}else if(draggerH>=mCSB_draggerContainerH-10){ /*max dragger height*/
var mCSB_draggerContainerMaxH=mCSB_draggerContainerH-10;
mCSB_dragger.css({"height":mCSB_draggerContainerMaxH});
}else{
mCSB_dragger.css({"height":draggerH});
}
mCSB_dragger.children(".mCSB_dragger_bar").css({"line-height":mCSB_dragger.height()+"px"});
}
var mCSB_draggerH=mCSB_dragger.height(),
/*calculate and store scroll amount, add scrolling*/
scrollAmount=(mCSB_containerH-mCustomScrollBoxH)/(mCSB_draggerContainerH-mCSB_draggerH);
$this.data("scrollAmount",scrollAmount).mCustomScrollbar("scrolling",mCustomScrollBox,mCSB_container,mCSB_draggerContainer,mCSB_dragger,mCSB_buttonUp,mCSB_buttonDown,mCSB_buttonLeft,mCSB_buttonRight);
/*scroll*/
var mCSB_containerP=Math.abs(Math.round(mCSB_container.position().top));
$this.mCustomScrollbar("scrollTo",mCSB_containerP,{callback:false});
}else if(mCSB_containerW>mCustomScrollBoxW && $this.data("horizontalScroll")){ /*content needs horizontal scrolling*/
mCSB_scrollTools.css("display","block");
var mCSB_draggerContainerW=mCSB_draggerContainer.width();
/*auto adjust scrollbar dragger length analogous to content*/
if($this.data("autoDraggerLength")){
var draggerW=Math.round(mCustomScrollBoxW/mCSB_containerW*mCSB_draggerContainerW),
minDraggerW=mCSB_dragger.data("minDraggerWidth");
if(draggerW<=minDraggerW){ /*min dragger height*/
mCSB_dragger.css({"width":minDraggerW});
}else if(draggerW>=mCSB_draggerContainerW-10){ /*max dragger height*/
var mCSB_draggerContainerMaxW=mCSB_draggerContainerW-10;
mCSB_dragger.css({"width":mCSB_draggerContainerMaxW});
}else{
mCSB_dragger.css({"width":draggerW});
}
}
var mCSB_draggerW=mCSB_dragger.width(),
/*calculate and store scroll amount, add scrolling*/
scrollAmount=(mCSB_containerW-mCustomScrollBoxW)/(mCSB_draggerContainerW-mCSB_draggerW);
$this.data("scrollAmount",scrollAmount).mCustomScrollbar("scrolling",mCustomScrollBox,mCSB_container,mCSB_draggerContainer,mCSB_dragger,mCSB_buttonUp,mCSB_buttonDown,mCSB_buttonLeft,mCSB_buttonRight);
/*scroll*/
var mCSB_containerP=Math.abs(Math.round(mCSB_container.position().left));
$this.mCustomScrollbar("scrollTo",mCSB_containerP,{callback:false});
}else{ /*content does not need scrolling*/
/*unbind events, reset content position, hide scrollbars, remove classes*/
mCustomScrollBox.unbind("mousewheel focusin");
if($this.data("horizontalScroll")){
mCSB_dragger.add(mCSB_container).css("left",0);
}else{
mCSB_dragger.add(mCSB_container).css("top",0);
}
mCSB_scrollTools.css("display","none");
mCSB_container.addClass("mCS_no_scrollbar");
$this.data({"bindEvent_mousewheel":false,"bindEvent_focusin":false});
}
},
scrolling:function(mCustomScrollBox,mCSB_container,mCSB_draggerContainer,mCSB_dragger,mCSB_buttonUp,mCSB_buttonDown,mCSB_buttonLeft,mCSB_buttonRight){
var $this=$(this);
/*while scrolling callback*/
$this.mCustomScrollbar("callbacks","whileScrolling");
/*drag scrolling*/
if(!mCSB_dragger.hasClass("ui-draggable")){ /*apply drag function once*/
if($this.data("horizontalScroll")){
var draggableAxis="x";
}else{
var draggableAxis="y";
}
mCSB_dragger.draggable({
axis:draggableAxis,
containment:"parent",
drag:function(event,ui){
$this.mCustomScrollbar("scroll");
mCSB_dragger.addClass("mCSB_dragger_onDrag");
},
stop:function(event,ui){
mCSB_dragger.removeClass("mCSB_dragger_onDrag");
}
});
}
if(!$this.data("bindEvent_scrollbar_click")){ /*bind once*/
mCSB_draggerContainer.bind("click",function(e){
if($this.data("horizontalScroll")){
var mouseCoord=(e.pageX-mCSB_draggerContainer.offset().left);
if(mouseCoord<mCSB_dragger.position().left || mouseCoord>(mCSB_dragger.position().left+mCSB_dragger.width())){
var scrollToPos=mouseCoord;
if(scrollToPos>=mCSB_draggerContainer.width()-mCSB_dragger.width()){ /*max dragger position is bottom*/
scrollToPos=mCSB_draggerContainer.width()-mCSB_dragger.width();
}
mCSB_dragger.css("left",scrollToPos);
$this.mCustomScrollbar("scroll");
}
}else{
var mouseCoord=(e.pageY-mCSB_draggerContainer.offset().top);
if(mouseCoord<mCSB_dragger.position().top || mouseCoord>(mCSB_dragger.position().top+mCSB_dragger.height())){
var scrollToPos=mouseCoord;
if(scrollToPos>=mCSB_draggerContainer.height()-mCSB_dragger.height()){ /*max dragger position is bottom*/
scrollToPos=mCSB_draggerContainer.height()-mCSB_dragger.height();
}
mCSB_dragger.css("top",scrollToPos);
$this.mCustomScrollbar("scroll");
}
}
});
$this.data({"bindEvent_scrollbar_click":true});
}
/*mousewheel scrolling*/
if($this.data("mouseWheel")){
var mousewheelVel=$this.data("mouseWheel");
if($this.data("mouseWheel")==="auto"){
mousewheelVel=8; /*default mousewheel velocity*/
/*check for safari browser on mac osx to lower mousewheel velocity*/
var os=navigator.userAgent;
if(os.indexOf("Mac")!=-1 && os.indexOf("Safari")!=-1 && os.indexOf("AppleWebKit")!=-1 && os.indexOf("Chrome")==-1){
mousewheelVel=1;
}
}
if(!$this.data("bindEvent_mousewheel")){ /*bind once*/
mCustomScrollBox.bind("mousewheel",function(event,delta){
event.preventDefault();
var vel=Math.abs(delta*mousewheelVel);
if($this.data("horizontalScroll")){
if($this.data("mouseWheel")==="pixels"){
if(delta<0){
delta=-1;
}else{
delta=1;
}
var scrollTo=Math.abs(Math.round(mCSB_container.position().left))-(delta*$this.data("mouseWheelPixels"));
$this.mCustomScrollbar("scrollTo",scrollTo);
}else{
var posX=mCSB_dragger.position().left-(delta*vel);
mCSB_dragger.css("left",posX);
if(mCSB_dragger.position().left<0){
mCSB_dragger.css("left",0);
}
var mCSB_draggerContainerW=mCSB_draggerContainer.width(),
mCSB_draggerW=mCSB_dragger.width();
if(mCSB_dragger.position().left>mCSB_draggerContainerW-mCSB_draggerW){
mCSB_dragger.css("left",mCSB_draggerContainerW-mCSB_draggerW);
}
$this.mCustomScrollbar("scroll");
}
}else{
if($this.data("mouseWheel")==="pixels"){
if(delta<0){
delta=-1;
}else{
delta=1;
}
var scrollTo=Math.abs(Math.round(mCSB_container.position().top))-(delta*$this.data("mouseWheelPixels"));
$this.mCustomScrollbar("scrollTo",scrollTo);
}else{
var posY=mCSB_dragger.position().top-(delta*vel);
mCSB_dragger.css("top",posY);
if(mCSB_dragger.position().top<0){
mCSB_dragger.css("top",0);
}
var mCSB_draggerContainerH=mCSB_draggerContainer.height(),
mCSB_draggerH=mCSB_dragger.height();
if(mCSB_dragger.position().top>mCSB_draggerContainerH-mCSB_draggerH){
mCSB_dragger.css("top",mCSB_draggerContainerH-mCSB_draggerH);
}
$this.mCustomScrollbar("scroll");
}
}
});
$this.data({"bindEvent_mousewheel":true});
}
}
/*buttons scrolling*/
if($this.data("scrollButtons_enable")){
if($this.data("scrollButtons_scrollType")==="pixels"){ /*scroll by pixels*/
var pixelsScrollTo;
if($.browser.msie && parseInt($.browser.version)<9){ /*stupid ie8*/
$this.data("scrollInertia",0);
}
if($this.data("horizontalScroll")){
mCSB_buttonRight.add(mCSB_buttonLeft).unbind("mousedown touchstart onmsgesturestart mouseup mouseout touchend onmsgestureend",mCSB_buttonRight_stop,mCSB_buttonLeft_stop);
$this.data({"bindEvent_buttonsContinuous_x":false});
if(!$this.data("bindEvent_buttonsPixels_x")){ /*bind once*/
/*scroll right*/
mCSB_buttonRight.bind("click",function(e){
e.preventDefault();
if(!mCSB_container.is(":animated")){
pixelsScrollTo=Math.abs(mCSB_container.position().left)+$this.data("scrollButtons_scrollAmount");
$this.mCustomScrollbar("scrollTo",pixelsScrollTo);
}
});
/*scroll left*/
mCSB_buttonLeft.bind("click",function(e){
e.preventDefault();
if(!mCSB_container.is(":animated")){
pixelsScrollTo=Math.abs(mCSB_container.position().left)-$this.data("scrollButtons_scrollAmount");
if(mCSB_container.position().left>=-$this.data("scrollButtons_scrollAmount")){
pixelsScrollTo="left";
}
$this.mCustomScrollbar("scrollTo",pixelsScrollTo);
}
});
$this.data({"bindEvent_buttonsPixels_x":true});
}
}else{
mCSB_buttonDown.add(mCSB_buttonUp).unbind("mousedown touchstart onmsgesturestart mouseup mouseout touchend onmsgestureend",mCSB_buttonRight_stop,mCSB_buttonLeft_stop);
$this.data({"bindEvent_buttonsContinuous_y":false});
if(!$this.data("bindEvent_buttonsPixels_y")){ /*bind once*/
/*scroll down*/
mCSB_buttonDown.bind("click",function(e){
e.preventDefault();
if(!mCSB_container.is(":animated")){
pixelsScrollTo=Math.abs(mCSB_container.position().top)+$this.data("scrollButtons_scrollAmount");
$this.mCustomScrollbar("scrollTo",pixelsScrollTo);
}
});
/*scroll up*/
mCSB_buttonUp.bind("click",function(e){
e.preventDefault();
if(!mCSB_container.is(":animated")){
pixelsScrollTo=Math.abs(mCSB_container.position().top)-$this.data("scrollButtons_scrollAmount");
if(mCSB_container.position().top>=-$this.data("scrollButtons_scrollAmount")){
pixelsScrollTo="top";
}
$this.mCustomScrollbar("scrollTo",pixelsScrollTo);
}
});
$this.data({"bindEvent_buttonsPixels_y":true});
}
}
}else{ /*continuous scrolling*/
if($this.data("horizontalScroll")){
mCSB_buttonRight.add(mCSB_buttonLeft).unbind("click");
$this.data({"bindEvent_buttonsPixels_x":false});
if(!$this.data("bindEvent_buttonsContinuous_x")){ /*bind once*/
/*scroll right*/
mCSB_buttonRight.bind("mousedown touchstart onmsgesturestart",function(e){
e.preventDefault();
e.stopPropagation();
$this.data({"mCSB_buttonScrollRight":setInterval(function(){
var scrollTo=Math.round((Math.abs(Math.round(mCSB_container.position().left))+$this.data("scrollButtons_scrollSpeed"))/$this.data("scrollAmount"));
$this.mCustomScrollbar("scrollTo",scrollTo,{moveDragger:true});
},30)});
});
var mCSB_buttonRight_stop=function(e){
e.preventDefault();
e.stopPropagation();
clearInterval($this.data("mCSB_buttonScrollRight"));
}
mCSB_buttonRight.bind("mouseup touchend onmsgestureend mouseout",mCSB_buttonRight_stop);
/*scroll left*/
mCSB_buttonLeft.bind("mousedown touchstart onmsgesturestart",function(e){
e.preventDefault();
e.stopPropagation();
$this.data({"mCSB_buttonScrollLeft":setInterval(function(){
var scrollTo=Math.round((Math.abs(Math.round(mCSB_container.position().left))-$this.data("scrollButtons_scrollSpeed"))/$this.data("scrollAmount"));
$this.mCustomScrollbar("scrollTo",scrollTo,{moveDragger:true});
},30)});
});
var mCSB_buttonLeft_stop=function(e){
e.preventDefault();
e.stopPropagation();
clearInterval($this.data("mCSB_buttonScrollLeft"));
}
mCSB_buttonLeft.bind("mouseup touchend onmsgestureend mouseout",mCSB_buttonLeft_stop);
$this.data({"bindEvent_buttonsContinuous_x":true});
}
}else{
mCSB_buttonDown.add(mCSB_buttonUp).unbind("click");
$this.data({"bindEvent_buttonsPixels_y":false});
if(!$this.data("bindEvent_buttonsContinuous_y")){ /*bind once*/
/*scroll down*/
mCSB_buttonDown.bind("mousedown touchstart onmsgesturestart",function(e){
e.preventDefault();
e.stopPropagation();
$this.data({"mCSB_buttonScrollDown":setInterval(function(){
var scrollTo=Math.round((Math.abs(Math.round(mCSB_container.position().top))+$this.data("scrollButtons_scrollSpeed"))/$this.data("scrollAmount"));
$this.mCustomScrollbar("scrollTo",scrollTo,{moveDragger:true});
},30)});
});
var mCSB_buttonDown_stop=function(e){
e.preventDefault();
e.stopPropagation();
clearInterval($this.data("mCSB_buttonScrollDown"));
}
mCSB_buttonDown.bind("mouseup touchend onmsgestureend mouseout",mCSB_buttonDown_stop);
/*scroll up*/
mCSB_buttonUp.bind("mousedown touchstart onmsgesturestart",function(e){
e.preventDefault();
e.stopPropagation();
$this.data({"mCSB_buttonScrollUp":setInterval(function(){
var scrollTo=Math.round((Math.abs(Math.round(mCSB_container.position().top))-$this.data("scrollButtons_scrollSpeed"))/$this.data("scrollAmount"));
$this.mCustomScrollbar("scrollTo",scrollTo,{moveDragger:true});
},30)});
});
var mCSB_buttonUp_stop=function(e){
e.preventDefault();
e.stopPropagation();
clearInterval($this.data("mCSB_buttonScrollUp"));
}
mCSB_buttonUp.bind("mouseup touchend onmsgestureend mouseout",mCSB_buttonUp_stop);
$this.data({"bindEvent_buttonsContinuous_y":true});
}
}
}
}
/*scrolling on element focus (e.g. via TAB key)*/
if($this.data("autoScrollOnFocus")){
if(!$this.data("bindEvent_focusin")){ /*bind once*/
mCustomScrollBox.bind("focusin",function(){
mCustomScrollBox.scrollTop(0).scrollLeft(0);
var focusedElem=$(document.activeElement);
if(focusedElem.is("input,textarea,select,button,a[tabindex],area,object")){
if($this.data("horizontalScroll")){
var mCSB_containerX=mCSB_container.position().left,
focusedElemX=focusedElem.position().left,
mCustomScrollBoxW=mCustomScrollBox.width(),
focusedElemW=focusedElem.outerWidth();
if(mCSB_containerX+focusedElemX>=0 && mCSB_containerX+focusedElemX<=mCustomScrollBoxW-focusedElemW){
/*just focus...*/
}else{ /*scroll, then focus*/
var moveDragger=focusedElemX/$this.data("scrollAmount");
if(moveDragger>=mCSB_draggerContainer.width()-mCSB_dragger.width()){ /*max dragger position is bottom*/
moveDragger=mCSB_draggerContainer.width()-mCSB_dragger.width();
}
mCSB_dragger.css("left",moveDragger);
$this.mCustomScrollbar("scroll");
}
}else{
var mCSB_containerY=mCSB_container.position().top,
focusedElemY=focusedElem.position().top,
mCustomScrollBoxH=mCustomScrollBox.height(),
focusedElemH=focusedElem.outerHeight();
if(mCSB_containerY+focusedElemY>=0 && mCSB_containerY+focusedElemY<=mCustomScrollBoxH-focusedElemH){
/*just focus...*/
}else{ /*scroll, then focus*/
var moveDragger=focusedElemY/$this.data("scrollAmount");
if(moveDragger>=mCSB_draggerContainer.height()-mCSB_dragger.height()){ /*max dragger position is bottom*/
moveDragger=mCSB_draggerContainer.height()-mCSB_dragger.height();
}
mCSB_dragger.css("top",moveDragger);
$this.mCustomScrollbar("scroll");
}
}
}
});
$this.data({"bindEvent_focusin":true});
}
}
/*touch events*/
if($(document).data("mCS-is-touch-device")){
/*scrollbar touch-drag*/
if(!$this.data("bindEvent_scrollbar_touch")){ /*bind once*/
var mCSB_draggerTouchY,
mCSB_draggerTouchX;
mCSB_dragger.bind("touchstart onmsgesturestart",function(e){
e.preventDefault();
e.stopPropagation();
var touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0],
elem=$(this),
elemOffset=elem.offset(),
x=touch.pageX-elemOffset.left,
y=touch.pageY-elemOffset.top;
if(x<elem.width() && x>0 && y<elem.height() && y>0){
mCSB_draggerTouchY=y;
mCSB_draggerTouchX=x;
}
});
mCSB_dragger.bind("touchmove onmsgesturechange",function(e){
e.preventDefault();
e.stopPropagation();
var touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0],
elem=$(this),
elemOffset=elem.offset(),
x=touch.pageX-elemOffset.left,
y=touch.pageY-elemOffset.top;
if($this.data("horizontalScroll")){
$this.mCustomScrollbar("scrollTo",(mCSB_dragger.position().left-(mCSB_draggerTouchX))+x,{moveDragger:true});
}else{
$this.mCustomScrollbar("scrollTo",(mCSB_dragger.position().top-(mCSB_draggerTouchY))+y,{moveDragger:true});
}
});
$this.data({"bindEvent_scrollbar_touch":true});
}
/*content touch-drag*/
if(!$this.data("bindEvent_content_touch")){ /*bind once*/
var touch,
elem,
elemOffset,
x,
y,
mCSB_containerTouchY,
mCSB_containerTouchX;
mCSB_container.bind("touchstart onmsgesturestart",function(e){
touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
elem=$(this);
elemOffset=elem.offset();
x=touch.pageX-elemOffset.left;
y=touch.pageY-elemOffset.top;
mCSB_containerTouchY=y;
mCSB_containerTouchX=x;
});
mCSB_container.bind("touchmove onmsgesturechange",function(e){
e.preventDefault();
e.stopPropagation();
touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
elem=$(this).parent();
elemOffset=elem.offset();
x=touch.pageX-elemOffset.left;
y=touch.pageY-elemOffset.top;
if($this.data("horizontalScroll")){
$this.mCustomScrollbar("scrollTo",mCSB_containerTouchX-x);
}else{
$this.mCustomScrollbar("scrollTo",mCSB_containerTouchY-y);
}
});
$this.data({"bindEvent_content_touch":true});
}
}
},
scroll:function(bypassCallbacks){
var $this=$(this),
mCSB_dragger=$this.find(".mCSB_dragger"),
mCSB_container=$this.find(".mCSB_container"),
mCustomScrollBox=$this.find(".mCustomScrollBox");
if($this.data("horizontalScroll")){
var draggerX=mCSB_dragger.position().left,
targX=-draggerX*$this.data("scrollAmount"),
thisX=mCSB_container.position().left,
posX=Math.round(thisX-targX);
}else{
var draggerY=mCSB_dragger.position().top,
targY=-draggerY*$this.data("scrollAmount"),
thisY=mCSB_container.position().top,
posY=Math.round(thisY-targY);
}
if($.browser.webkit){ /*fix webkit zoom and jquery animate*/
var screenCssPixelRatio=(window.outerWidth-8)/window.innerWidth,
isZoomed=(screenCssPixelRatio<.98 || screenCssPixelRatio>1.02);
}
if($this.data("scrollInertia")===0 || isZoomed){
if(!bypassCallbacks){
$this.mCustomScrollbar("callbacks","onScrollStart"); /*user custom callback functions*/
}
if($this.data("horizontalScroll")){
mCSB_container.css("left",targX);
}else{
mCSB_container.css("top",targY);
}
if(!bypassCallbacks){
/*user custom callback functions*/
if($this.data("whileScrolling")){
$this.data("whileScrolling_Callback").call();
}
$this.mCustomScrollbar("callbacks","onScroll");
}
$this.data({"mCS_Init":false});
}else{
if(!bypassCallbacks){
$this.mCustomScrollbar("callbacks","onScrollStart"); /*user custom callback functions*/
}
if($this.data("horizontalScroll")){
mCSB_container.stop().animate({left:"-="+posX},$this.data("scrollInertia"),$this.data("scrollEasing"),function(){
if(!bypassCallbacks){
$this.mCustomScrollbar("callbacks","onScroll"); /*user custom callback functions*/
}
$this.data({"mCS_Init":false});
});
}else{
mCSB_container.stop().animate({top:"-="+posY},$this.data("scrollInertia"),$this.data("scrollEasing"),function(){
if(!bypassCallbacks){
$this.mCustomScrollbar("callbacks","onScroll"); /*user custom callback functions*/
}
$this.data({"mCS_Init":false});
});
}
}
},
scrollTo:function(scrollTo,options){
var defaults={
moveDragger:false,
callback:true
},
options=$.extend(defaults,options),
$this=$(this),
scrollToPos,
mCustomScrollBox=$this.find(".mCustomScrollBox"),
mCSB_container=mCustomScrollBox.children(".mCSB_container"),
mCSB_draggerContainer=$this.find(".mCSB_draggerContainer"),
mCSB_dragger=mCSB_draggerContainer.children(".mCSB_dragger"),
targetPos;
if(scrollTo || scrollTo===0){
if(typeof(scrollTo)==="number"){ /*if integer, scroll by number of pixels*/
if(options.moveDragger){ /*scroll dragger*/
scrollToPos=scrollTo;
}else{ /*scroll content by default*/
targetPos=scrollTo;
scrollToPos=Math.round(targetPos/$this.data("scrollAmount"));
}
}else if(typeof(scrollTo)==="string"){ /*if string, scroll by element position*/
var target;
if(scrollTo==="top"){ /*scroll to top*/
target=0;
}else if(scrollTo==="bottom" && !$this.data("horizontalScroll")){ /*scroll to bottom*/
target=mCSB_container.outerHeight()-mCustomScrollBox.height();
}else if(scrollTo==="left"){ /*scroll to left*/
target=0;
}else if(scrollTo==="right" && $this.data("horizontalScroll")){ /*scroll to right*/
target=mCSB_container.outerWidth()-mCustomScrollBox.width();
}else if(scrollTo==="first"){ /*scroll to first element position*/
target=$this.find(".mCSB_container").find(":first");
}else if(scrollTo==="last"){ /*scroll to last element position*/
target=$this.find(".mCSB_container").find(":last");
}else{ /*scroll to element position*/
target=$this.find(scrollTo);
}
if(target.length===1){ /*if such unique element exists, scroll to it*/
if($this.data("horizontalScroll")){
targetPos=target.position().left;
}else{
targetPos=target.position().top;
}
scrollToPos=Math.ceil(targetPos/$this.data("scrollAmount"));
}else{
scrollToPos=target;
}
}
/*scroll to*/
if(scrollToPos<0){
scrollToPos=0;
}
if($this.data("horizontalScroll")){
if(scrollToPos>=mCSB_draggerContainer.width()-mCSB_dragger.width()){ /*max dragger position is bottom*/
scrollToPos=mCSB_draggerContainer.width()-mCSB_dragger.width();
}
mCSB_dragger.css("left",scrollToPos);
}else{
if(scrollToPos>=mCSB_draggerContainer.height()-mCSB_dragger.height()){ /*max dragger position is bottom*/
scrollToPos=mCSB_draggerContainer.height()-mCSB_dragger.height();
}
mCSB_dragger.css("top",scrollToPos);
}
if(options.callback){
$this.mCustomScrollbar("scroll",false);
}else{
$this.mCustomScrollbar("scroll",true);
}
}
},
callbacks:function(callback){
var $this=$(this),
mCustomScrollBox=$this.find(".mCustomScrollBox"),
mCSB_container=$this.find(".mCSB_container");
switch(callback){
/*start scrolling callback*/
case "onScrollStart":
if(!mCSB_container.is(":animated")){
$this.data("onScrollStart_Callback").call();
}
break;
/*end scrolling callback*/
case "onScroll":
if($this.data("horizontalScroll")){
var mCSB_containerX=Math.round(mCSB_container.position().left);
if(mCSB_containerX<0 && mCSB_containerX<=mCustomScrollBox.width()-mCSB_container.outerWidth()+$this.data("onTotalScroll_Offset")){
$this.data("onTotalScroll_Callback").call();
}else if(mCSB_containerX>=-$this.data("onTotalScroll_Offset")){
$this.data("onTotalScrollBack_Callback").call();
}else{
$this.data("onScroll_Callback").call();
}
}else{
var mCSB_containerY=Math.round(mCSB_container.position().top);
if(mCSB_containerY<0 && mCSB_containerY<=mCustomScrollBox.height()-mCSB_container.outerHeight()+$this.data("onTotalScroll_Offset")){
$this.data("onTotalScroll_Callback").call();
}else if(mCSB_containerY>=-$this.data("onTotalScroll_Offset")){
$this.data("onTotalScrollBack_Callback").call();
}else{
$this.data("onScroll_Callback").call();
}
}
break;
/*while scrolling callback*/
case "whileScrolling":
if($this.data("whileScrolling_Callback") && !$this.data("whileScrolling")){
$this.data({"whileScrolling":setInterval(function(){
if(mCSB_container.is(":animated") && !$this.data("mCS_Init")){
$this.data("whileScrolling_Callback").call();
}
},$this.data("whileScrolling_Interval"))});
}
break;
}
},
disable:function(resetScroll){
var $this=$(this),
mCustomScrollBox=$this.children(".mCustomScrollBox"),
mCSB_container=mCustomScrollBox.children(".mCSB_container"),
mCSB_scrollTools=mCustomScrollBox.children(".mCSB_scrollTools"),
mCSB_dragger=mCSB_scrollTools.find(".mCSB_dragger");
mCustomScrollBox.unbind("mousewheel focusin");
if(resetScroll){
if($this.data("horizontalScroll")){
mCSB_dragger.add(mCSB_container).css("left",0);
}else{
mCSB_dragger.add(mCSB_container).css("top",0);
}
}
mCSB_scrollTools.css("display","none");
mCSB_container.addClass("mCS_no_scrollbar");
$this.data({"bindEvent_mousewheel":false,"bindEvent_focusin":false}).addClass("mCS_disabled");
},
destroy:function(){
var $this=$(this),
content=$this.find(".mCSB_container").html();
$this.find(".mCustomScrollBox").remove();
$this.html(content).removeClass("mCustomScrollbar _mCS_"+$(document).data("mCustomScrollbar-index")).addClass("mCS_destroyed");
}
}
$.fn.mCustomScrollbar=function(method){
if(methods[method]){
return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
}else if(typeof method==="object" || !method){
return methods.init.apply(this,arguments);
}else{
$.error("Method "+method+" does not exist");
}
};
})(jQuery);
/*iOS 6 bug fix
iOS 6 suffers from a bug that kills timers that are created while a page is scrolling.
The following fixes that problem by recreating timers after scrolling finishes (with interval correction).*/
var iOSVersion=iOSVersion();
if(iOSVersion>=6){
(function(h){var a={};var d={};var e=h.setTimeout;var f=h.setInterval;var i=h.clearTimeout;var c=h.clearInterval;if(!h.addEventListener){return false}function j(q,n,l){var p,k=l[0],m=(q===f);function o(){if(k){k.apply(h,arguments);if(!m){delete n[p];k=null}}}l[0]=o;p=q.apply(h,l);n[p]={args:l,created:Date.now(),cb:k,id:p};return p}function b(q,o,k,r,t){var l=k[r];if(!l){return}var m=(q===f);o(l.id);if(!m){var n=l.args[1];var p=Date.now()-l.created;if(p<0){p=0}n-=p;if(n<0){n=0}l.args[1]=n}function s(){if(l.cb){l.cb.apply(h,arguments);if(!m){delete k[r];l.cb=null}}}l.args[0]=s;l.created=Date.now();l.id=q.apply(h,l.args)}h.setTimeout=function(){return j(e,a,arguments)};h.setInterval=function(){return j(f,d,arguments)};h.clearTimeout=function(l){var k=a[l];if(k){delete a[l];i(k.id)}};h.clearInterval=function(l){var k=d[l];if(k){delete d[l];c(k.id)}};var g=h;while(g.location!=g.parent.location){g=g.parent}g.addEventListener("scroll",function(){var k;for(k in a){b(e,i,a,k)}for(k in d){b(f,c,d,k)}})}(window));
}
function iOSVersion(){
var agent=window.navigator.userAgent,
start=agent.indexOf('OS ');
if((agent.indexOf('iPhone')>-1 || agent.indexOf('iPad')>-1) && start>-1){
return window.Number(agent.substr(start+3,3).replace('_','.'));
}
return 0;
}

12
lib/dashboard/js/jquery.mousewheel.min.js

@ -0,0 +1,12 @@
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function(a){function d(b){var c=b||window.event,d=[].slice.call(arguments,1),e=0,f=!0,g=0,h=0;return b=a.event.fix(c),b.type="mousewheel",c.wheelDelta&&(e=c.wheelDelta/120),c.detail&&(e=-c.detail/3),h=e,c.axis!==undefined&&c.axis===c.HORIZONTAL_AXIS&&(h=0,g=-1*e),c.wheelDeltaY!==undefined&&(h=c.wheelDeltaY/120),c.wheelDeltaX!==undefined&&(g=-1*c.wheelDeltaX/120),d.unshift(b,e,g,h),(a.event.dispatch||a.event.handle).apply(this,d)}var b=["DOMMouseScroll","mousewheel"];if(a.event.fixHooks)for(var c=b.length;c;)a.event.fixHooks[b[--c]]=a.event.mouseHooks;a.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=b.length;a;)this.addEventListener(b[--a],d,!1);else this.onmousewheel=d},teardown:function(){if(this.removeEventListener)for(var a=b.length;a;)this.removeEventListener(b[--a],d,!1);else this.onmousewheel=null}},a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery)

BIN
lib/dashboard/webfonts/22AE77_0_0.eot

3
lib/dashboard/webfonts/22AE77_0_0.ttf

@ -0,0 +1,3 @@
<!-- saved from url=(0048)http://www-cdn.jtvnw.net/webfonts/22AE77_0_0.ttf -->
<html><body><div class="webkit-line-gutter-backdrop"></div><table><tbody><tr><td class="webkit-line-number"></td><td class="webkit-line-content"> <span class="webkit-html-attribute-name">Ö°Í°</span>/<span class="webkit-html-attribute-name">°.Ͳ.</span></td></tr><tr><td class="webkit-line-number"></td><td class="webkit-line-content"><span class="webkit-html-attribute-name">+³@</span> <span class="webkit-html-attribute-name">+° 2±2+±°

3
lib/dashboard/webfonts/22AE77_0_0.woff

@ -0,0 +1,3 @@
<!-- saved from url=(0049)http://www-cdn.jtvnw.net/webfonts/22AE77_0_0.woff -->
<html><body><div class="webkit-line-gutter-backdrop"></div><table><tbody><tr><td class="webkit-line-number"></td><td class="webkit-line-content">wOFF

BIN
lib/dashboard/webfonts/scoolar_tfb.eot

BIN
lib/dashboard/webfonts/scoolar_tfb.ttf

59
lib/initialize.js

@ -0,0 +1,59 @@
var file = require('fs');
//create logs directory
file.exists('./../logs', function (exists) {
if (!exists) {
file.mkdir('./../logs');
}
});
process.on('uncaughtException', function(err) {
file.appendFile('./../logs/error-log.txt', err.message + '\r\n' + err.stack + '\r\n', function() {});
});
exports.initialize = function(options) {
var config = options || {}, db, irc, commands, dashboard, currency;
//-------- Setup -------
irc = require('./irc.js')({
name : config.twitch.bot.name,
pass : config.twitch.bot.password,
channel : '#' + config.twitch.channel
});
db = require('./mysql.js')({
host : config.currency.host,
user : config.currency.user,
password : config.currency.password,
database : config.currency.database
});
commands = require('./commands.js')(irc, db, {
bot_name : config.twitch.bot.name,
currency : config.currency.name
});
currency = require('./currency.js')(irc, db, {
currency : config.currency.name,
payrate : config.currency.payrate,
subscribers : config.twitch.subscribers,
website : config.currency.website
});
//-------- Start -------
irc.start();
db.start();
currency.start();
if (config.commands === true) commands.start();
irc.on('data', function (data) {
console.log(data);
irc.realtime(data);
});
irc.on('command', function (data) {
currency.commands(data);
if (config.commands === true) commands.commands(data);
});
irc.on('message', function (msg) {
irc.queue(msg);
});
};

368
lib/irc.js

@ -0,0 +1,368 @@
/**
* api:
* IRC([required options])
* required options - {name, pass, channel}
*
* IRC.connect()
* connects to the twitch irc server
*
* IRC.on('command', callback)
* allows custom commands
*
* IRC.on('data', callback)
* event when data is recieved / sent
*
* IRC.msg(message, [options])
* options - {caller, auth[0/1]}
*
* IRC.caller(data[0])
* parse out user name from socket data,
* mainly for plugin use when working with commands
*
* example:
* require:
* var irc = require('./lib/core/irc.js')({
* name : 'TwitchBot',
* pass : 'twitch!twitch!twitch!',
* channel : '#awesomebroadcaster'
* });
*
* connect:
* irc.connect();
*
* custom commands:
* irc.on('command' function (data) {
* if (data[3] == ':!command') {
* // do something
* }
* });
*
* irc data:
* irc.on('data', function (data) {
* //do something with data
* });
*
* irc logging:
* irc.on('data', function (data) {
* irc.realtime(data);
* }
*
* send a message to chat:
* irc.msg('Hi chat!');
* irc.msg('Hi chat!', {caller: 'SupremoRTD', auth: 1});
*
* get user name:
* irc.caller(data[0]);
*/
var net = require('net'),
events = require('events'),
file = require('fs'),
https = require('https'),
utils = require('./utils.js');
//-------- Construct ---------
function IRC(options) {
var __self = this;
__self.options = options || {pass: 'irc_bot', name: 'irc_bot', channel: 'irc_bot'};
__self.config = {
// twitch bot info
pass : __self.options.pass,
name : __self.options.name,
nick : 'irc_bot',
broadcaster : __self.options.channel.slice(1).charAt(0).toUpperCase() + __self.options.channel.slice(2).toLowerCase(),
// twitch server
addr : '199.9.250.229', //__self.options.name.toLowerCase() + '.jtvirc.com',
port : 6667,
channel : __self.options.channel.toLowerCase(),
encoding : 'ascii'
};
__self.mods = [];
__self.buffer = [];
// message queue
__self.queue_timer = 2000;
__self.queue_messages = [];
__self.previous_message = '';
// irc logging
__self.check_streaming = 4;//minutes
__self.streaming = false;
__self.new_file = false;
__self.log = '';
}
IRC.prototype = new events.EventEmitter();
//-------- Methods --------
IRC.prototype.start = function () {
var __self = this;
// check stream status
function stream_status() {
var time = utils.make_interval(__self.check_streaming);
if (time === 0) {
https.get('https://api.twitch.tv/kraken/streams/' + __self.config.channel.slice(1), function (response) {
var body = '';
// put together response
response.on('data', function (chunk) {
body += chunk;
});
// log file creation
response.on('end', function () {
var json = JSON.parse(body);
__self.streaming = json.stream !== null;
if (__self.streaming && !__self.new_file) {
// prevent another file from being created while streaming
__self.new_file = true;
// set stream time for file
var date = new Date(),
hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(),
streaming_time = '';
// create start time string
streaming_time += (date.getMonth().toString() + 1) + date.getDate().toString() + date.getFullYear().toString();
streaming_time += hours.toString() + min.toString() + sec.toString();
// create new log file
__self.log = './../logs/' + __self.config.channel.slice(1) + '_' + streaming_time.toString() + '.txt';
file.open(__self.log, 'w');
} else if (!__self.streaming) {
__self.new_file = false;
}
setTimeout(stream_status, 1000);
});
});
} else {
setTimeout(stream_status, time);
}
}
stream_status();
__self.connect();
__self.monitor_queue();
};
IRC.prototype.realtime = function (data){
var __self = this;
// only log irc data if streaming
if (__self.streaming) {
// check if file exists, if it does append
file.exists(__self.log, function (exists) {
if (exists) {
file.appendFile(__self.log, data + '\r\n', 'utf-8', function (err) {
if (err) {
throw err;
}
});
}
});
}
};
IRC.prototype.connect = function () {
var __self = this;
// create new socket
__self.socket = new net.Socket();
__self.socket.setEncoding(__self.config.encoding);
__self.socket.setNoDelay();
__self.socket.connect(__self.config.port, __self.config.addr);
// connect to twitch irc via socket
__self.socket.on('connect', function () {
__self.emit('data', 'RECV - Established connection to Twitch IRC, registering user...');
__self.raw('PASS ' + __self.config.pass, true);
__self.raw('NICK ' + __self.config.name);
__self.raw('USER ' + __self.config.nick + ' ' + __self.config.nick + '.com ' + __self.config.nick + ' :' + __self.config.name);
});
// handle incoming socket data
__self.socket.on('data', function (data) {
var prepack, lines, line, word;
prepack = data.replace('\r\n', '\n');
__self.buffer += prepack;
lines = __self.buffer.split('\n');
__self.buffer = '';
if (lines[lines.length - 1] !== '') {
__self.buffer = lines[lines.length - 1];
}
lines = lines.splice(0, lines.length - 1);
for (var i = 0; i < lines.length; i++) {
line = lines[i].replace('\r','');
word = line.replace('\r', '').split(' ');
__self.emit('data', 'RECV - ' + line);
__self.join(word);
__self.pingpong(word);
__self.moderators(word);
if (word[3] !== undefined) {
__self.emit('command', word);
}
}
});
__self.socket.on('error', function(){
__self.reconnect();
});
};
// reconnect to socket
IRC.prototype.reconnect = function () {
var __self = this;
// send quit to server, destroy socket connection,
// clear socket variable and then reconnect
__self.socket.end('QUIT\r\n');
__self.socket.destroy();
__self.socket = null;
__self.connect();
};
// join channel
IRC.prototype.join = function (data) {
var __self = this;
if (data[3] === ':End') {
__self.raw('JOIN ' + __self.config.channel);
}
};
// ping / pong
IRC.prototype.pingpong = function (data) {
var __self = this;
if (data[0] === 'PING') {
__self.raw('PONG ' + data[1]);
}
};
// store / remove mods
IRC.prototype.moderators = function (data) {
var __self = this;
if (data[1] === 'MODE') {
if (data[4] !== undefined) {
var user = data[4].charAt(0).toUpperCase() + data[4].slice(1);
switch (data[3]) {
case '+o':
if (__self.mods.indexOf(user) < 0) {
__self.mods.push(user);
}
break;
case '-o':
if (__self.mods.indexOf(user) >= 0) {
__self.mods.splice(__self.mods.indexOf(user), 1);
}
break;
}
}
}
};
// output to socket / console
IRC.prototype.raw = function (data, hide) {
var __self = this;
__self.socket.write(data + '\r\n', __self.config.encoding, function (){
if (!hide) {
// monitor commands sent by the bot
// and push them to command action
var parse = data.split(' ');
if (parse[0] === 'PRIVMSG') {
parse = __self.options.name + ' ' + data;
__self.emit('command', parse.split(' '));
__self.emit('data', 'SENT - ' + __self.options.name + ' ' + data);
} else {
// output response
__self.emit('data', 'SENT - ' + data);
}
}
});
};
// who sent message
IRC.prototype.caller = function (data) {
var caller = data.split('!');
return caller[0].charAt(1).toUpperCase() + caller[0].slice(2);
};
// send message to twitch chat
IRC.prototype.msg = function (msg, options) {
var __self = this, opts = options || {caller:null, auth:0};
switch (opts.auth) {
case 0:
__self.raw('PRIVMSG ' + __self.config.channel + ' :' + msg);
break;
case 1:
if (__self.mods.indexOf(opts.caller) >= 0) {
__self.raw('PRIVMSG ' + __self.config.channel + ' :' + msg);
}
break;
}
};
// message queue
IRC.prototype.queue = function(msg) {
var __self = this;
__self.queue_messages.push(msg);
};
IRC.prototype.monitor_queue = function() {
var __self = this, prepend_text = ['>', '+'];
// handle messages in queue
function handle_queue() {
if (__self.queue_messages.length > 0) {
var message = __self.queue_messages[0].message,
options = __self.queue_messages[0].options,
timer = __self.queue_messages[0].timer || __self.queue_timer;
// change message if it's the same as the previous message
if (message === __self.previous_message) {
for (var i = 0; i < prepend_text.length; i++) {
if (prepend_text[i] !== message.charAt(0)) {
message = prepend_text[i] + message.slice(1);
__self.previous_message = message;
break;
}
}
} else {
__self.previous_message = __self.queue_messages[0].message;
}
// remove message from queue
__self.queue_messages.splice(0, 1);
// output message to chat
setTimeout(function() {
if (options === null) {
__self.msg(message);
} else {
__self.msg(message, options);
}
// recheck the queue
setTimeout(handle_queue, 500);
}, timer);
} else {
setTimeout(handle_queue, 500);
}
}
handle_queue();
};
module.exports = function (options) {
return new IRC(options);
};

81
lib/mysql.js

@ -0,0 +1,81 @@
/**
* api:
* DB([required options])
* required options - {host, user, password, database}
*
* example:
* var db = require('./lib/plugins/db.js')({
* host : 'localhost',
* user : 'user',
* password : 'password',
* database : 'database',
* });
*/
var mysql = require('mysql'),
file = require('fs');
//-------- Construct ---------
function DB(options) {
var __self = this;
// config
__self.host = options.host || '';
__self.user = options.user || '';
__self.password = options.password || '';
__self.database = options.database || '';
}
//-------- Methods ---------
DB.prototype.start = function() {
var __self = this, commands ='', viewers = '';
// table structure for table commands
commands += 'CREATE TABLE IF NOT EXISTS `commands` (';
commands += '`id` int(11) NOT NULL AUTO_INCREMENT,';
commands += '`command` text COLLATE utf8_unicode_ci NOT NULL,';
commands += '`text` longtext COLLATE utf8_unicode_ci NOT NULL,';
commands += '`auth` int(11) NOT NULL DEFAULT \'1\',';
commands += 'PRIMARY KEY (`id`)';
commands += ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1';
// table structure for table viewers
viewers += 'CREATE TABLE IF NOT EXISTS `viewers` (';
viewers += '`user` varchar(64) COLLATE utf8_unicode_ci NOT NULL,';
viewers += '`points` int(11) NOT NULL,';
viewers += 'PRIMARY KEY (`user`)';
viewers += ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
// execute sql, create tables if they don't exist
__self.execute(commands + '; ' + viewers, function(){});
};
DB.prototype.execute = function(sql, callback) {
var __self = this,
connection = mysql.createConnection({
host : __self.host,
user : __self.user,
password : __self.password,
database : __self.database,
multipleStatements : true
});
// execute query
connection.query(sql, function (err, rows, fields) {
// error handling
if (err) {
file.appendFile('./../logs/error-log.txt', err.message + '\r\n' + err.stack + '\r\n', function() {});
return;
}
// close connection
connection.end();
// return results
callback(rows, fields);
});
};
module.exports = function (options) {
return new DB(options);
};

15
lib/utils.js

@ -0,0 +1,15 @@
exports.selectRandomArrayItem = function(array){
return array[Math.floor(Math.random() * array.length)];
};
exports.max = function (value) {
return Math.max.apply(Math, value.map(function (o) {return o.bid;}));
};
// adjusts setTimeout time so it's in sync with actual time intervals
// e.g. 5 minutes intervals will happen at 10:05/10:10/10:15 regardless of start time
// TODO: add the ability to set the interval in seconds / minutes / hours
exports.make_interval = function (interval) {
var d = new Date(), min = d.getMinutes(), sec = d.getSeconds();
return min % interval === 0 && sec === 0 ? 0 : ((60 * (interval - (min % interval))) - sec) * 1000;
};

5
node_modules/mustache/.jshintrc

@ -0,0 +1,5 @@
{
"eqnull": true,
"evil": true
}

10
node_modules/mustache/.npmignore

@ -0,0 +1,10 @@
.DS_Store
.rvmrc
node_modules
runner.js
jquery.mustache.js
qooxdoo.mustache.js
dojox
yui3
requirejs.mustache.js

4
node_modules/mustache/.travis.yml

@ -0,0 +1,4 @@
language: node_js
node_js:
- 0.6

34
node_modules/mustache/CHANGES

@ -0,0 +1,34 @@
= 0.7.2 / 27 Dec 2012
* Fixed a rendering bug (#274) when using nested higher-order sections.
* Converted tests to use mocha instead of vows.
= 0.7.1 / 6 Dec 2012
* Handle empty templates gracefully. Fixes #265, #267, and #270.
* Cache partials by template, not by name. Fixes #257.
* Added Mustache.compileTokens to compile the output of Mustache.parse. Fixes
#258.
= 0.7.0 / 10 Sep 2012
* Rename Renderer => Writer.
* Allow partials to be loaded dynamically using a callback (thanks
@TiddoLangerak for the suggestion).
* Fixed a bug with higher-order sections that prevented them from being
passed the raw text of the section from the original template.
* More concise token format. Tokens also include start/end indices in the
original template.
* High-level API is consistent with the Writer API.
* Allow partials to be passed to the pre-compiled function (thanks
@fallenice).
* Don't use eval (thanks @cweider).
= 0.6.0 / 31 Aug 2012
* Use JavaScript's definition of falsy when determining whether to render an
inverted section or not. Issue #186.
* Use Mustache.escape to escape values inside {{}}. This function may be
reassigned to alter the default escaping behavior. Issue #244.
* Fixed a bug that clashed with QUnit (thanks @kannix).
* Added volo support (thanks @guybedford).

10
node_modules/mustache/LICENSE

@ -0,0 +1,10 @@
The MIT License
Copyright (c) 2009 Chris Wanstrath (Ruby)
Copyright (c) 2010 Jan Lehnardt (JavaScript)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

400
node_modules/mustache/README.md

@ -0,0 +1,400 @@
# mustache.js - Logic-less {{mustache}} templates with JavaScript
> What could be more logical awesome than no logic at all?
[mustache.js](http://github.com/janl/mustache.js) is an implementation of the [mustache](http://mustache.github.com/) template system in JavaScript.
[Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object.
We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.
For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html).
## Where to use mustache.js?
You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [node](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views.
mustache.js ships with support for both the [CommonJS](http://www.commonjs.org/) module API and the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API, or AMD.
## Who uses mustache.js?
An updated list of mustache.js users is kept [on the Github wiki](http://wiki.github.com/janl/mustache.js/beard-competition). Add yourself or your company if you use mustache.js!
## Usage
Below is quick example how to use mustache.js:
var view = {
title: "Joe",
calc: function () {
return 2 + 4;
}
};
var output = Mustache.render("{{title}} spends {{calc}}", view);
In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template.
## Templates
A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key.
There are several types of tags available in mustache.js.
### Variables
The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered.
All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable.
View:
{
"name": "Chris",
"company": "<b>GitHub</b>"
}
Template:
* {{name}}
* {{age}}
* {{company}}
* {{{company}}}
* {{&company}}
Output:
* Chris
*
* &lt;b&gt;GitHub&lt;/b&gt;
* <b>GitHub</b>
* <b>GitHub</b>
JavaScript's dot notation may be used to access keys that are properties of objects in a view.
View:
{
"name": {
"first": "Michael",
"last": "Jackson"
},
"age": "RIP"
}
Template:
* {{name.first}} {{name.last}}
* {{age}}
Output:
* Michael Jackson
* RIP
### Sections
Sections render blocks of text one or more times, depending on the value of the key in the current context.
A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block".
The behavior of the section is determined by the value of the key.
#### False Values or Empty Lists
If the `person` key does not exist, or exists and has a value of `null`, `undefined`, or `false`, or is an empty list, the block will not be rendered.
View:
{
"person": false
}
Template:
Shown.
{{#person}}
Never shown!
{{/person}}
Output:
Shown.
#### Non-Empty Lists
If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times.
When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections.
View:
{
"stooges": [
{ "name": "Moe" },
{ "name": "Larry" },
{ "name": "Curly" }
]
}
Template:
{{#stooges}}
<b>{{name}}</b>
{{/stooges}}
Output:
<b>Moe</b>
<b>Larry</b>
<b>Curly</b>
When looping over an array of strings, a `.` can be used to refer to the current item in the list.
View:
{
"musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}
Template:
{{#musketeers}}
* {{.}}
{{/musketeers}}
Output:
* Athos
* Aramis
* Porthos
* D'Artagnan
If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration.
View:
{
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
return this.firstName + " " + this.lastName;
}
}
Template:
{{#beatles}}
* {{name}}
{{/beatles}}
Output:
* John Lennon
* Paul McCartney
* George Harrison
* Ringo Starr
#### Functions
If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object.
View:
{
"name": "Tater",
"bold": function () {
return function (text, render) {
return "<b>" + render(text) + "</b>";
}
}
}
Template:
{{#bold}}Hi {{name}}.{{/bold}}
Output:
<b>Hi Tater.</b>
### Inverted Sections
An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, or an empty list.
View:
{
"repos": []
}
Template:
{{#repos}}<b>{{name}}</b>{{/repos}}
{{^repos}}No repos :({{/repos}}
Output:
No repos :(
### Comments
Comments begin with a bang and are ignored. The following template:
<h1>Today{{! ignore me }}.</h1>
Will render as follows:
<h1>Today.</h1>
Comments may contain newlines.
### Partials
Partials begin with a greater than sign, like {{> box}}.
Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops.
They also inherit the calling context. Whereas in ERB you may have this:
<%= partial :next_more, :start => start, :size => size %>
Mustache requires only this:
{{> next_more}}
Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, or template expansion, even though it's not literally true.
For example, this template and partial:
base.mustache:
<h2>Names</h2>
{{#names}}
{{> user}}
{{/names}}
user.mustache:
<strong>{{name}}</strong>
Can be thought of as a single, expanded template:
<h2>Names</h2>
{{#names}}
<strong>{{name}}</strong>
{{/names}}
In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text.
### Set Delimiter
Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings.
Consider the following contrived example:
* {{ default_tags }}
{{=<% %>=}}
* <% erb_style_tags %>
<%={{ }}=%>
* {{ default_tags_again }}
Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration.
According to [ctemplates](http://google-ctemplate.googlecode.com/svn/trunk/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup."
Custom delimiters may not contain whitespace or the equals sign.
### Compiled Templates
Mustache templates can be compiled into JavaScript functions using `Mustache.compile` for improved rendering performance.
If you have template views that are rendered multiple times, compiling your template into a JavaScript function will minimise the amount of work required for each re-render.
Pre-compiled templates can also be generated server-side, for delivery to the browser as ready to use JavaScript functions, further reducing the amount of client side processing required for initialising templates.
**Mustache.compile**
Use `Mustache.compile` to compile standard Mustache string templates into reusable Mustache template functions.
var compiledTemplate = Mustache.compile(stringTemplate);
The function returned from `Mustache.compile` can then be called directly, passing in the template data as an argument (with an object of partials as an optional second parameter), to generate the final output.
var templateOutput = compiledTemplate(templateData);
**Mustache.compilePartial**
Template partials can also be compiled using the `Mustache.compilePartial` function. The first parameter of this function, is the name of the partial as it appears within parent templates.
Mustache.compilePartial('partial-name', stringTemplate);
Compiled partials are then available to both `Mustache.render` and `Mustache.compile`.
## Plugins for JavaScript Libraries
mustache.js may be built specifically for several different client libraries, including the following:
- [jQuery](http://jquery.com/)
- [MooTools](http://mootools.net/)
- [Dojo](http://www.dojotoolkit.org/)
- [YUI](http://developer.yahoo.com/yui/)
- [qooxdoo](http://qooxdoo.org/)
These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands:
$ rake jquery
$ rake mootools
$ rake dojo
$ rake yui
$ rake qooxdoo
## Testing
The mustache.js test suite uses the [vows](http://vowsjs.org/) testing framework. In order to run the tests you'll need to install [node](http://nodejs.org/). Once that's done you can install vows using [npm](http://npmjs.org/).
$ npm install -g vows
Then run the tests.
$ vows --spec
The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following:
1. Create a template file named `mytest.mustache` in the `test/_files`
directory. Replace `mytest` with the name of your test.
2. Create a corresponding view file named `mytest.js` in the same directory.
This file should contain a JavaScript object literal enclosed in
parentheses. See any of the other view files for an example.
3. Create a file with the expected output in `mytest.txt` in the same
directory.
Then, you can run the test with:
$ TEST=mytest vows test/render_test.js
## Thanks
mustache.js wouldn't kick ass if it weren't for these fine souls:
* Chris Wanstrath / defunkt
* Alexander Lang / langalex
* Sebastian Cohnen / tisba
* J Chris Anderson / jchris
* Tom Robinson / tlrobinson
* Aaron Quint / quirkey
* Douglas Crockford
* Nikita Vasilyev / NV
* Elise Wood / glytch
* Damien Mathieu / dmathieu
* Jakub Kuźma / qoobaa
* Will Leinweber / will
* dpree
* Jason Smith / jhs
* Aaron Gibralter / agibralter
* Ross Boucher / boucher
* Matt Sanford / mzsanford
* Ben Cherry / bcherry
* Michael Jackson / mjijackson

68
node_modules/mustache/Rakefile

@ -0,0 +1,68 @@
require 'rake'
require 'rake/clean'
task :default => :test
ROOT = File.expand_path('..', __FILE__)
MUSTACHE_JS = File.read(File.join(ROOT, 'mustache.js'))
def mustache_version
match = MUSTACHE_JS.match(/exports\.version = "([^"]+)";/)
match[1]
end
def minified_file
ENV['FILE'] || 'mustache.min.js'
end
desc "Run all tests, requires vows (see http://vowsjs.org)"
task :test do
sh "vows --spec"
end
desc "Minify to #{minified_file}, requires UglifyJS (see http://marijnhaverbeke.nl/uglifyjs)"
task :minify do
sh "uglifyjs mustache.js > #{minified_file}"
end
desc "Run JSHint, requires jshint (see http://www.jshint.com)"
task :lint do
sh "jshint mustache.js"
end
# Creates a task that uses the various template wrappers to make a wrapped
# output file. There is some extra complexity because Dojo and YUI use
# different final locations.
def templated_build(name, opts={})
short = name.downcase
source = File.join("wrappers", short)
dependencies = ["mustache.js"] + Dir.glob("#{source}/*.tpl.*")
target_js = opts[:location] ? "mustache.js" : "#{short}.mustache.js"
CLEAN.include(opts[:location] ? opts[:location] : target_js)
desc "Package for #{name}"
task short.to_sym => dependencies do
puts "Packaging for #{name}"
mkdir_p opts[:location] if opts[:location]
files = [
"#{source}/mustache.js.pre",
'mustache.js',
"#{source}/mustache.js.post"
]
open("#{opts[:location] || '.'}/#{target_js}", 'w') do |f|
files.each {|file| f << File.read(file) }
end
puts "Done, see #{opts[:location] || '.'}/#{target_js}"
end
end
templated_build "jQuery"
templated_build "MooTools"
templated_build "Dojo", :location => "dojox/string"
templated_build "YUI3", :location => "yui3/mustache"
templated_build "qooxdoo"

610
node_modules/mustache/mustache.js

@ -0,0 +1,610 @@
/*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*/
/*global define: false*/
(function (root, factory) {
if (typeof exports === "object" && exports) {
module.exports = factory; // CommonJS
} else if (typeof define === "function" && define.amd) {
define(factory); // AMD
} else {
root.Mustache = factory; // <script>
}
}(this, (function () {
var exports = {};
exports.name = "mustache.js";
exports.version = "0.7.2";
exports.tags = ["{{", "}}"];
exports.Scanner = Scanner;
exports.Context = Context;
exports.Writer = Writer;
var whiteRe = /\s*/;
var spaceRe = /\s+/;
var nonSpaceRe = /\S/;
var eqRe = /\s*=/;
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
// See https://github.com/janl/mustache.js/issues/189
function testRe(re, string) {
return RegExp.prototype.test.call(re, string);
}
function isWhitespace(string) {
return !testRe(nonSpaceRe, string);
}
var isArray = Array.isArray || function (obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
function escapeRe(string) {
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
var entityMap = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': '&quot;',
"'": '&#39;',
"/": '&#x2F;'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
// Export the escaping function so that the user may override it.
// See https://github.com/janl/mustache.js/issues/244
exports.escape = escapeHtml;
function Scanner(string) {
this.string = string;
this.tail = string;
this.pos = 0;
}
/**
* Returns `true` if the tail is empty (end of string).
*/
Scanner.prototype.eos = function () {
return this.tail === "";
};
/**
* Tries to match the given regular expression at the current position.
* Returns the matched text if it can match, the empty string otherwise.
*/
Scanner.prototype.scan = function (re) {
var match = this.tail.match(re);
if (match && match.index === 0) {
this.tail = this.tail.substring(match[0].length);
this.pos += match[0].length;
return match[0];
}
return "";
};
/**
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
*/
Scanner.prototype.scanUntil = function (re) {
var match, pos = this.tail.search(re);
switch (pos) {
case -1:
match = this.tail;
this.pos += this.tail.length;
this.tail = "";
break;
case 0:
match = "";
break;
default:
match = this.tail.substring(0, pos);
this.tail = this.tail.substring(pos);
this.pos += pos;
}
return match;
};
function Context(view, parent) {
this.view = view;
this.parent = parent;
this.clearCache();
}
Context.make = function (view) {
return (view instanceof Context) ? view : new Context(view);
};
Context.prototype.clearCache = function () {
this._cache = {};
};
Context.prototype.push = function (view) {
return new Context(view, this);
};
Context.prototype.lookup = function (name) {
var value = this._cache[name];
if (!value) {
if (name === ".") {
value = this.view;
} else {
var context = this;
while (context) {
if (name.indexOf(".") > 0) {
var names = name.split("."), i = 0;
value = context.view;
while (value && i < names.length) {
value = value[names[i++]];
}
} else {
value = context.view[name];
}
if (value != null) {
break;
}
context = context.parent;
}
}
this._cache[name] = value;
}
if (typeof value === "function") {
value = value.call(this.view);
}
return value;
};
function Writer() {
this.clearCache();
}
Writer.prototype.clearCache = function () {
this._cache = {};
this._partialCache = {};
};
Writer.prototype.compile = function (template, tags) {
var fn = this._cache[template];
if (!fn) {
var tokens = exports.parse(template, tags);
fn = this._cache[template] = this.compileTokens(tokens, template);
}
return fn;
};
Writer.prototype.compilePartial = function (name, template, tags) {
var fn = this.compile(template, tags);
this._partialCache[name] = fn;
return fn;
};
Writer.prototype.compileTokens = function (tokens, template) {
var fn = compileTokens(tokens);
var self = this;
return function (view, partials) {
if (partials) {
if (typeof partials === "function") {
self._loadPartial = partials;
} else {
for (var name in partials) {
self.compilePartial(name, partials[name]);
}
}
}
return fn(self, Context.make(view), template);
};
};
Writer.prototype.render = function (template, view, partials) {
return this.compile(template)(view, partials);
};
Writer.prototype._section = function (name, context, text, callback) {
var value = context.lookup(name);
switch (typeof value) {
case "object":
if (isArray(value)) {
var buffer = "";
for (var i = 0, len = value.length; i < len; ++i) {
buffer += callback(this, context.push(value[i]));
}
return buffer;
}
return value ? callback(this, context.push(value)) : "";
case "function":
var self = this;
var scopedRender = function (template) {
return self.render(template, context);
};
var result = value.call(context.view, text, scopedRender);
return result != null ? result : "";
default:
if (value) {
return callback(this, context);
}
}
return "";
};
Writer.prototype._inverted = function (name, context, callback) {
var value = context.lookup(name);
// Use JavaScript's definition of falsy. Include empty arrays.
// See https://github.com/janl/mustache.js/issues/186
if (!value || (isArray(value) && value.length === 0)) {
return callback(this, context);
}
return "";
};
Writer.prototype._partial = function (name, context) {
if (!(name in this._partialCache) && this._loadPartial) {
this.compilePartial(name, this._loadPartial(name));
}
var fn = this._partialCache[name];
return fn ? fn(context) : "";
};
Writer.prototype._name = function (name, context) {
var value = context.lookup(name);
if (typeof value === "function") {
value = value.call(context.view);
}
return (value == null) ? "" : String(value);
};
Writer.prototype._escaped = function (name, context) {
return exports.escape(this._name(name, context));
};
/**
* Low-level function that compiles the given `tokens` into a function
* that accepts three arguments: a Writer, a Context, and the template.
*/
function compileTokens(tokens) {
var subRenders = {};
function subRender(i, tokens, template) {
if (!subRenders[i]) {
var fn = compileTokens(tokens);
subRenders[i] = function (writer, context) {
return fn(writer, context, template);
};
}
return subRenders[i];
}
return function (writer, context, template) {
var buffer = "";
var token, sectionText;
for (var i = 0, len = tokens.length; i < len; ++i) {
token = tokens[i];
switch (token[0]) {
case "#":
sectionText = template.slice(token[3], token[5]);
buffer += writer._section(token[1], context, sectionText, subRender(i, token[4], template));
break;
case "^":
buffer += writer._inverted(token[1], context, subRender(i, token[4], template));
break;
case ">":
buffer += writer._partial(token[1], context);
break;
case "&":
buffer += writer._name(token[1], context);
break;
case "name":
buffer += writer._escaped(token[1], context);
break;
case "text":
buffer += token[1];
break;
}
}
return buffer;
};
}
/**
* Forms the given array of `tokens` into a nested tree structure where
* tokens that represent a section have two additional items: 1) an array of
* all tokens that appear in that section and 2) the index in the original
* template that represents the end of that section.
*/
function nestTokens(tokens) {
var tree = [];
var collector = tree;
var sections = [];
var token;
for (var i = 0, len = tokens.length; i < len; ++i) {
token = tokens[i];
switch (token[0]) {
case '#':
case '^':
sections.push(token);
collector.push(token);
collector = token[4] = [];
break;
case '/':
var section = sections.pop();
section[5] = token[2];
collector = sections.length > 0 ? sections[sections.length - 1][4] : tree;
break;
default:
collector.push(token);
}
}
return tree;
}
/**
* Combines the values of consecutive text tokens in the given `tokens` array
* to a single token.
*/
function squashTokens(tokens) {
var squashedTokens = [];
var token, lastToken;
for (var i = 0, len = tokens.length; i < len; ++i) {
token = tokens[i];
if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
lastToken[1] += token[1];
lastToken[3] = token[3];
} else {
lastToken = token;
squashedTokens.push(token);
}
}
return squashedTokens;
}
function escapeTags(tags) {
return [
new RegExp(escapeRe(tags[0]) + "\\s*"),
new RegExp("\\s*" + escapeRe(tags[1]))
];
}
/**
* Breaks up the given `template` string into a tree of token objects. If
* `tags` is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. ["<%", "%>"]). Of
* course, the default is to use mustaches (i.e. Mustache.tags).
*/
exports.parse = function (template, tags) {
template = template || '';
tags = tags || exports.tags;
if (typeof tags === 'string') tags = tags.split(spaceRe);
if (tags.length !== 2) {
throw new Error('Invalid tags: ' + tags.join(', '));
}
var tagRes = escapeTags(tags);
var scanner = new Scanner(template);
var sections = []; // Stack to hold section tokens
var tokens = []; // Buffer to hold the tokens
var spaces = []; // Indices of whitespace tokens on the current line
var hasTag = false; // Is there a {{tag}} on the current line?
var nonSpace = false; // Is there a non-space char on the current line?
// Strips all whitespace tokens array for the current line
// if there was a {{#tag}} on it and otherwise only space.
function stripSpace() {
if (hasTag && !nonSpace) {
while (spaces.length) {
tokens.splice(spaces.pop(), 1);
}
} else {
spaces = [];
}
hasTag = false;
nonSpace = false;
}
var start, type, value, chr;
while (!scanner.eos()) {
start = scanner.pos;
value = scanner.scanUntil(tagRes[0]);
if (value) {
for (var i = 0, len = value.length; i < len; ++i) {
chr = value.charAt(i);
if (isWhitespace(chr)) {
spaces.push(tokens.length);
} else {
nonSpace = true;
}
tokens.push(["text", chr, start, start + 1]);
start += 1;
if (chr === "\n") {
stripSpace(); // Check for whitespace on the current line.
}
}
}
start = scanner.pos;
// Match the opening tag.
if (!scanner.scan(tagRes[0])) {
break;
}
hasTag = true;
type = scanner.scan(tagRe) || "name";
// Skip any whitespace between tag and value.
scanner.scan(whiteRe);
// Extract the tag value.
if (type === "=") {
value = scanner.scanUntil(eqRe);
scanner.scan(eqRe);
scanner.scanUntil(tagRes[1]);
} else if (type === "{") {
var closeRe = new RegExp("\\s*" + escapeRe("}" + tags[1]));
value = scanner.scanUntil(closeRe);
scanner.scan(curlyRe);
scanner.scanUntil(tagRes[1]);
type = "&";
} else {
value = scanner.scanUntil(tagRes[1]);
}
// Match the closing tag.
if (!scanner.scan(tagRes[1])) {
throw new Error('Unclosed tag at ' + scanner.pos);
}
// Check section nesting.
if (type === '/') {
if (sections.length === 0) {
throw new Error('Unopened section "' + value + '" at ' + start);
}
var section = sections.pop();
if (section[1] !== value) {
throw new Error('Unclosed section "' + section[1] + '" at ' + start);
}
}
var token = [type, value, start, scanner.pos];
tokens.push(token);
if (type === '#' || type === '^') {
sections.push(token);
} else if (type === "name" || type === "{" || type === "&") {
nonSpace = true;
} else if (type === "=") {
// Set the tags for the next time around.
tags = value.split(spaceRe);
if (tags.length !== 2) {
throw new Error('Invalid tags at ' + start + ': ' + tags.join(', '));
}
tagRes = escapeTags(tags);
}
}
// Make sure there are no open sections when we're done.
var section = sections.pop();
if (section) {
throw new Error('Unclosed section "' + section[1] + '" at ' + scanner.pos);
}
return nestTokens(squashTokens(tokens));
};
// The high-level clearCache, compile, compilePartial, and render functions
// use this default writer.
var _writer = new Writer();
/**
* Clears all cached templates and partials in the default writer.
*/
exports.clearCache = function () {
return _writer.clearCache();
};
/**
* Compiles the given `template` to a reusable function using the default
* writer.
*/
exports.compile = function (template, tags) {
return _writer.compile(template, tags);
};
/**
* Compiles the partial with the given `name` and `template` to a reusable
* function using the default writer.
*/
exports.compilePartial = function (name, template, tags) {
return _writer.compilePartial(name, template, tags);
};
/**
* Compiles the given array of tokens (the output of a parse) to a reusable
* function using the default writer.
*/
exports.compileTokens = function (tokens, template) {
return _writer.compileTokens(tokens, template);
};
/**
* Renders the `template` with the given `view` and `partials` using the
* default writer.
*/
exports.render = function (template, view, partials) {
return _writer.render(template, view, partials);
};
// This is here for backwards compatibility with 0.4.x.
exports.to_html = function (template, view, partials, send) {
var result = exports.render(template, view, partials);
if (typeof send === "function") {
send(result);
} else {
return result;
}
};
return exports;
}())));

14
node_modules/mustache/mustache.js.nuspec

@ -0,0 +1,14 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>mustache.js</id>
<version>0.7.2</version>
<authors>mustache.js Authors</authors>
<licenseUrl>https://github.com/janl/mustache.js/blob/master/LICENSE</licenseUrl>
<projectUrl>http://mustache.github.com/</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Logic-less templates in JavaScript.</description>
<releaseNotes></releaseNotes>
<tags>mustache template templates javascript</tags>
</metadata>
</package>

32
node_modules/mustache/package.json
File diff suppressed because it is too large
View File

3
node_modules/mustache/test/_files/ampersand_escape.js

@ -0,0 +1,3 @@
({
message: "Some <code>"
})

1
node_modules/mustache/test/_files/ampersand_escape.mustache

@ -0,0 +1 @@
{{&message}}

1
node_modules/mustache/test/_files/ampersand_escape.txt

@ -0,0 +1 @@
Some <code>

4
node_modules/mustache/test/_files/apostrophe.js

@ -0,0 +1,4 @@
({
'apos': "'",
'control': 'X'
})

1
node_modules/mustache/test/_files/apostrophe.mustache

@ -0,0 +1 @@
{{apos}}{{control}}

1
node_modules/mustache/test/_files/apostrophe.txt

@ -0,0 +1 @@
&#39;X

3
node_modules/mustache/test/_files/array_of_strings.js

@ -0,0 +1,3 @@
({
array_of_strings: ['hello', 'world']
})

1
node_modules/mustache/test/_files/array_of_strings.mustache

@ -0,0 +1 @@
{{#array_of_strings}}{{.}} {{/array_of_strings}}

1
node_modules/mustache/test/_files/array_of_strings.txt

@ -0,0 +1 @@
hello world

3
node_modules/mustache/test/_files/backslashes.js

@ -0,0 +1,3 @@
({
value: "\\abc"
})

7
node_modules/mustache/test/_files/backslashes.mustache

@ -0,0 +1,7 @@
* {{value}}
* {{{value}}}
* {{&value}}
<script>
foo = { bar: 'abc\"xyz\"' };
foo = { bar: 'x\'y' };
</script>

7
node_modules/mustache/test/_files/backslashes.txt

@ -0,0 +1,7 @@
* \abc
* \abc
* \abc
<script>
foo = { bar: 'abc\"xyz\"' };
foo = { bar: 'x\'y' };
</script>

3
node_modules/mustache/test/_files/bug_11_eating_whitespace.js

@ -0,0 +1,3 @@
({
tag: "yo"
})

1
node_modules/mustache/test/_files/bug_11_eating_whitespace.mustache

@ -0,0 +1 @@
{{tag}} foo

1
node_modules/mustache/test/_files/bug_11_eating_whitespace.txt

@ -0,0 +1 @@
yo foo

4
node_modules/mustache/test/_files/changing_delimiters.js

@ -0,0 +1,4 @@
({
"foo": "foooooooooooooo",
"bar": "<b>bar!</b>"
})

1
node_modules/mustache/test/_files/changing_delimiters.mustache

@ -0,0 +1 @@
{{=<% %>=}}<% foo %> {{foo}} <%{bar}%> {{{bar}}}

1
node_modules/mustache/test/_files/changing_delimiters.txt

@ -0,0 +1 @@
foooooooooooooo {{foo}} <b>bar!</b> {{{bar}}}

7
node_modules/mustache/test/_files/check_falsy.js

@ -0,0 +1,7 @@
({
number: function(text, render) {
return function(text, render) {
return +render(text);
}
}
})

1
node_modules/mustache/test/_files/check_falsy.mustache

@ -0,0 +1 @@
<p>{{#number}}0{{/number}}</p>

1
node_modules/mustache/test/_files/check_falsy.txt

@ -0,0 +1 @@
<p>0</p>

5
node_modules/mustache/test/_files/comments.js

@ -0,0 +1,5 @@
({
title: function () {
return "A Comedy of Errors";
}
})

1
node_modules/mustache/test/_files/comments.mustache

@ -0,0 +1 @@
<h1>{{title}}{{! just something interesting... or not... }}</h1>

1
node_modules/mustache/test/_files/comments.txt

@ -0,0 +1 @@
<h1>A Comedy of Errors</h1>

19
node_modules/mustache/test/_files/complex.js

@ -0,0 +1,19 @@
({
header: function () {
return "Colors";
},
item: [
{name: "red", current: true, url: "#Red"},
{name: "green", current: false, url: "#Green"},
{name: "blue", current: false, url: "#Blue"}
],
link: function () {
return this["current"] !== true;
},
list: function () {
return this.item.length !== 0;
},
empty: function () {
return this.item.length === 0;
}
})

16
node_modules/mustache/test/_files/complex.mustache

@ -0,0 +1,16 @@
<h1>{{header}}</h1>
{{#list}}
<ul>
{{#item}}
{{#current}}
<li><strong>{{name}}</strong></li>
{{/current}}
{{#link}}
<li><a href="{{url}}">{{name}}</a></li>
{{/link}}
{{/item}}
</ul>
{{/list}}
{{#empty}}
<p>The list is empty.</p>
{{/empty}}

6
node_modules/mustache/test/_files/complex.txt

@ -0,0 +1,6 @@
<h1>Colors</h1>
<ul>
<li><strong>red</strong></li>
<li><a href="#Green">green</a></li>
<li><a href="#Blue">blue</a></li>
</ul>

8
node_modules/mustache/test/_files/context_lookup.js

@ -0,0 +1,8 @@
({
"outer": {
"id": 1,
"second": {
"nothing": 2
}
}
})

1
node_modules/mustache/test/_files/context_lookup.mustache

@ -0,0 +1 @@
{{#outer}}{{#second}}{{id}}{{/second}}{{/outer}}

1
node_modules/mustache/test/_files/context_lookup.txt

@ -0,0 +1 @@
1

6
node_modules/mustache/test/_files/delimiters.js

@ -0,0 +1,6 @@
({
first: "It worked the first time.",
second: "And it worked the second time.",
third: "Then, surprisingly, it worked the third time.",
fourth: "Fourth time also fine!."
})

7
node_modules/mustache/test/_files/delimiters.mustache

@ -0,0 +1,7 @@
{{=<% %>=}}*
<% first %>
* <% second %>
<%=| |=%>
* | third |
|={{ }}=|
* {{ fourth }}

5
node_modules/mustache/test/_files/delimiters.txt

@ -0,0 +1,5 @@
*
It worked the first time.
* And it worked the second time.
* Then, surprisingly, it worked the third time.
* Fourth time also fine!.

4
node_modules/mustache/test/_files/disappearing_whitespace.js

@ -0,0 +1,4 @@
({
bedrooms: true,
total: 1
})

1
node_modules/mustache/test/_files/disappearing_whitespace.mustache

@ -0,0 +1 @@
{{#bedrooms}}{{total}}{{/bedrooms}} BED

1
node_modules/mustache/test/_files/disappearing_whitespace.txt

@ -0,0 +1 @@
1 BED

23
node_modules/mustache/test/_files/dot_notation.js

@ -0,0 +1,23 @@
({
name: "A Book",
authors: ["John Power", "Jamie Walsh"],
price: {
value: 200,
vat: function () {
return this.value * 0.2;
},
currency: {
symbol: '$',
name: 'USD'
}
},
availability: {
status: true,
text: "In Stock"
},
// And now, some truthy false values
truthy: {
zero: 0,
notTrue: false
}
})

9
node_modules/mustache/test/_files/dot_notation.mustache

@ -0,0 +1,9 @@
<!-- exciting part -->
<h1>{{name}}</h1>
<p>Authors: <ul>{{#authors}}<li>{{.}}</li>{{/authors}}</ul></p>
<p>Price: {{{price.currency.symbol}}}{{price.value}} {{#price.currency}}{{name}} <b>{{availability.text}}</b>{{/price.currency}}</p>
<p>VAT: {{{price.currency.symbol}}}{{#price}}{{vat}}{{/price}}</p>
<!-- boring part -->
<h2>Test truthy false values:</h2>
<p>Zero: {{truthy.zero}}</p>
<p>False: {{truthy.notTrue}}</p>

9
node_modules/mustache/test/_files/dot_notation.txt

@ -0,0 +1,9 @@
<!-- exciting part -->
<h1>A Book</h1>
<p>Authors: <ul><li>John Power</li><li>Jamie Walsh</li></ul></p>
<p>Price: $200 USD <b>In Stock</b></p>
<p>VAT: $40</p>
<!-- boring part -->
<h2>Test truthy false values:</h2>
<p>Zero: 0</p>
<p>False: false</p>

5
node_modules/mustache/test/_files/double_render.js

@ -0,0 +1,5 @@
({
foo: true,
bar: "{{win}}",
win: "FAIL"
})

1
node_modules/mustache/test/_files/double_render.mustache

@ -0,0 +1 @@
{{#foo}}{{bar}}{{/foo}}

1
node_modules/mustache/test/_files/double_render.txt

@ -0,0 +1 @@
{{win}}

3
node_modules/mustache/test/_files/empty_list.js

@ -0,0 +1,3 @@
({
jobs: []
})

4
node_modules/mustache/test/_files/empty_list.mustache

@ -0,0 +1,4 @@
These are the jobs:
{{#jobs}}
{{.}}
{{/jobs}}

1
node_modules/mustache/test/_files/empty_list.txt

@ -0,0 +1 @@
These are the jobs:

1
node_modules/mustache/test/_files/empty_sections.js

@ -0,0 +1 @@
({})

1
node_modules/mustache/test/_files/empty_sections.mustache

@ -0,0 +1 @@
{{#foo}}{{/foo}}foo{{#bar}}{{/bar}}

1
node_modules/mustache/test/_files/empty_sections.txt

@ -0,0 +1 @@
foo

6
node_modules/mustache/test/_files/empty_string.js

@ -0,0 +1,6 @@
({
description: "That is all!",
child: {
description: ""
}
})

1
node_modules/mustache/test/_files/empty_string.mustache

@ -0,0 +1 @@
{{description}}{{#child}}{{description}}{{/child}}

1
node_modules/mustache/test/_files/empty_string.txt

@ -0,0 +1 @@
That is all!

1
node_modules/mustache/test/_files/empty_template.js

@ -0,0 +1 @@
({})

1
node_modules/mustache/test/_files/empty_template.mustache

@ -0,0 +1 @@
<html><head></head><body><h1>Test</h1></body></html>

1
node_modules/mustache/test/_files/empty_template.txt

@ -0,0 +1 @@
<html><head></head><body><h1>Test</h1></body></html>

3
node_modules/mustache/test/_files/error_not_found.js

@ -0,0 +1,3 @@
({
bar: 2
})

1
node_modules/mustache/test/_files/error_not_found.mustache

@ -0,0 +1 @@
{{foo}}

0
node_modules/mustache/test/_files/error_not_found.txt

6
node_modules/mustache/test/_files/escaped.js

@ -0,0 +1,6 @@
({
title: function () {
return "Bear > Shark";
},
entities: "&quot; \"'<>/"
})

2
node_modules/mustache/test/_files/escaped.mustache

@ -0,0 +1,2 @@
<h1>{{title}}</h1>
And even {{entities}}, but not {{{entities}}}.

2
node_modules/mustache/test/_files/escaped.txt

@ -0,0 +1,2 @@
<h1>Bear &gt; Shark</h1>
And even &amp;quot; &quot;&#39;&lt;&gt;&#x2F;, but not &quot; "'<>/.

8
node_modules/mustache/test/_files/falsy.js

@ -0,0 +1,8 @@
({
"emptyString": "",
"emptyArray": [],
"zero": 0,
"null": null,
"undefined": undefined,
"NaN": 0/0
})

12
node_modules/mustache/test/_files/falsy.mustache

@ -0,0 +1,12 @@
{{#emptyString}}empty string{{/emptyString}}
{{^emptyString}}inverted empty string{{/emptyString}}
{{#emptyArray}}empty array{{/emptyArray}}
{{^emptyArray}}inverted empty array{{/emptyArray}}
{{#zero}}zero{{/zero}}
{{^zero}}inverted zero{{/zero}}
{{#null}}null{{/null}}
{{^null}}inverted null{{/null}}
{{#undefined}}undefined{{/undefined}}
{{^undefined}}inverted undefined{{/undefined}}
{{#NaN}}NaN{{/NaN}}
{{^NaN}}inverted NaN{{/NaN}}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save