diff --git a/.gitignore b/.gitignore
index 5b5cbc3..a860310 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1 @@
-Notes.txt
-dancer.js
-underscore-min.js
-chromecast/node_modules
-node_modules
\ No newline at end of file
+node_modules/**
diff --git a/.storybook/addons.js b/.storybook/addons.js
new file mode 100644
index 0000000..fd95092
--- /dev/null
+++ b/.storybook/addons.js
@@ -0,0 +1,5 @@
+import addons from '@storybook/addons'
+
+import '@storybook/addon-knobs/register'
+// import register from 'storybook-colors-addon/dist/register'
+// register(addons)
diff --git a/.storybook/config.js b/.storybook/config.js
new file mode 100644
index 0000000..d53fed7
--- /dev/null
+++ b/.storybook/config.js
@@ -0,0 +1,29 @@
+import { configure, addDecorator, addParameters } from '@storybook/react'
+
+import { withKnobs } from '@storybook/addon-knobs'
+
+addDecorator(
+ withKnobs
+)
+
+function loadStories() {
+ require('../src/components/Visualizer/Visualizer.story');
+ // require('../src/components/Audio/Audio.story');
+ // require('../src/components/Player/Duration.story');
+ // require('../src/components/Player/Player.story');
+ // require('../src/components/Player/Metadata.story');
+ // require('../src/components/Player/Controls.story');
+}
+
+addParameters({
+ options: {
+ isFullscreen: true,
+ showNav: false,
+ showPanel: false,
+ enableShortcuts: false,
+ }
+})
+
+configure(loadStories, module)
+
+import './general.css'
diff --git a/.storybook/constants.js b/.storybook/constants.js
new file mode 100644
index 0000000..7c35c33
--- /dev/null
+++ b/.storybook/constants.js
@@ -0,0 +1 @@
+export const IS_STORYBOOK = process.env.NODE_ENV === 'storybook'
diff --git a/.storybook/decorators.js b/.storybook/decorators.js
new file mode 100644
index 0000000..c14e5d3
--- /dev/null
+++ b/.storybook/decorators.js
@@ -0,0 +1,13 @@
+import React from 'react';
+import store from "../src/store"
+import getProvider from '../src/components/Provider'
+
+const Provider = getProvider(store)
+
+export const dispatch = store.dispatch
+
+export const withProvider = (stories) => {
+ return
+ {stories()}
+
+}
diff --git a/.storybook/general.css b/.storybook/general.css
new file mode 100644
index 0000000..b9f4e8f
--- /dev/null
+++ b/.storybook/general.css
@@ -0,0 +1,5 @@
+* {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
diff --git a/.storybook/webpack.config.js b/.storybook/webpack.config.js
new file mode 100644
index 0000000..f9bbaf8
--- /dev/null
+++ b/.storybook/webpack.config.js
@@ -0,0 +1,26 @@
+const webpack = require('webpack')
+const path = require('path')
+
+module.exports = async ({ config }) => {
+ config.plugins.push(
+ new webpack.DefinePlugin({
+ __DEV__: true,
+ })
+ )
+
+ config.devServer = {
+ ...config.devServer,
+ inline: true,
+ hot: true,
+ }
+
+ config.module.rules.push({
+ test: /\.ttf$/,
+ loader: "file-loader", // or directly file-loader
+ include: path.resolve(__dirname, "node_modules/react-web-vector-icons"),
+ })
+
+
+
+ return config
+}
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f49a4e1
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/README.md b/README.md
index d459f4e..eb91e93 100644
--- a/README.md
+++ b/README.md
@@ -1,34 +1,28 @@
-# CSS Music Visualizer
+# CSS (Animated) Music Visualizer
-### Disclaimer
-All the code for this project was developed on my own and in my free-time. It's licensed under the [WTFPL](http://www.wtfpl.net/) but a mention would be nice, [@Likethemammal](https://github.com/likethemammal).
+A set of visualizers animated entirely using DOM elements and CSS3 Animations and Transforms. **No SVG, Canvas, WebGL, or plug-in**.
-## About
-
-This is a set of visualizers that are made entirely using DOM elements and CSS3 Animations and Transforms. **There is no SVG, Canvas, WebGL, or visual plug-in used.** It takes quite a bit of tweaking to reduce compositing and optimize rendering layers but this is the kind of stuff CSS can do now a days.
-
-[**Live Demo**](http://likethemammal.github.io/css-visualizer)
+Everything is a `
`.
+[**Live Demo**](https://likethemammal.github.io/css-visualizer/iframe.html?id=visualizer--default)
-*(Everything you see is made from div tags!)*
+
-
+
-It uses [Dancer.js](https://github.com/jsantell/dancer.js) a small Web Audio library to get `spectrum` and `waveform` data using the HTML5 audio tag.
-
-There are currently two types of visualizer:
-
- * The Hexagonal one, which utilizes spectrum data and uses `before` and `after` psudeo-elements to create the six-sided shape.
- * And Bars, which projects the waveform data and uses the CSS3 transform `skew` to create the 3D column shape.
+## About
-
+Uses the Web Audio API to decode audio data.
-##Goals
+* [Soundcloud API](https://developers.soundcloud.com/)
+* [visualizer-micro](https://github.com/likethemammal/visualizer-micro)
-It has a relatively simple UI but the plan is to connect it to the [SoundCloud](http://SoundCloud.com) and [Grooveshark](http://grooveshark.com) APIs to visualizer any song from those services.
+## Todo:
-
+* Chromecast support (doesnt support mp3s)
+* Other visualizations
-There are a few other visualizer ideas I'm toying with as well. As one of the restriction I've decided to only use traditional DOM elements like `div`, `li`, etc.
+## License
+Licensed under Apache License 2.0.
-
+[@Likethemammal](https://twitter.com/likethemammal)
diff --git a/css/styles.css b/css/styles.css
deleted file mode 100644
index 2cde1d8..0000000
--- a/css/styles.css
+++ /dev/null
@@ -1,562 +0,0 @@
-body {
- margin: 0;
- background: #000000;
- overflow: hidden;
- font-family: "Helvetica Neue", sans-serif;
-}
-
-/* clearfix rules */
-.cf:before,
-.cf:after {
- content: " "; /* 1 */
- display: table; /* 2 */
-}
-
-.cf:after {
- clear: both;
-}
-
-
-
-#visualizer {
- position: fixed;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
- z-index: 1;
-}
-
-#ui-container {
- position: absolute;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
- z-index: 2;
-}
-
-#ui {
- position: relative;
- width: 100%;
- height: 100%;
-
- -webkit-transition: opacity 200ms;
- -moz-transition: opacity 200ms;
- -o-transition: opacity 200ms;
- transition: opacity 200ms;
-
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
-}
-
-.ui-outer {
- position: absolute;
- max-width: 360px;
- width: 100%;
- padding: 30px;
-
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
-}
-
-.ui-inner {
- background: #212121;
- color: #fff;
- opacity: 0.6;
-
- -webkit-border-radius: 2px;
- -moz-border-radius: 2px;
- border-radius: 2px;
-
- -webkit-transition: opacity 100ms linear;
- -moz-transition: opacity 100ms linear;
- -o-transition: opacity 100ms linear;
- transition: opacity 100ms linear;
-
- -webkit-box-shadow: 0px 3px 5px #000;
- -moz-box-shadow: 0px 3px 5px #000;
- box-shadow: 0px 3px 5px #000;
-
-}
-
-.ui-inner:hover {
- opacity: 1;
-}
-
-#chooser {
- display: block;
- background: #212121;
- color: #fff;
- height: 45px;
- line-height: 45px;
- float: left;
- border: none;
- font-size: 15px;
- padding: 0 10px 0 15px;
- margin: 0;
- margin-right: -1px;
- cursor: pointer;
-
- -webkit-border-radius: 2px 0 0 2px;
- -moz-border-radius: 2px 0 0 2px;
- border-radius: 2px 0 0 2px;
-}
-
-#chooser:hover {
- background-color: #111;
-}
-
-#chooser option {
- background-color: #212121;
-}
-
-#play-pause {
- background-image: url('../imgs/glyphicons_174_pause.png');
-}
-
-#next {
- background-image: url('../imgs/glyphicons_178_step_forward.png');
-}
-
-#fullscreen {
- background-image: url('../imgs/glyphicons_215_resize_full.png');
-}
-
-#about {
- background-image: url('../imgs/glyphicons_194_circle_question_mark.png');
-}
-
-#fullscreen:hover {
- -webkit-animation: toggleFullscreen 1s linear infinite alternate;
- -moz-animation: toggleFullscreen 1s linear infinite alternate;
- -o-animation: toggleFullscreen 1s linear infinite alternate;
- animation: toggleFullscreen 1s linear infinite alternate;
-}
-
-#search-input {
-}
-
-#search-btn {
- background-image: url('../imgs/glyphicons_027_search.png');
-}
-
-.ui-btn {
- display: block;
- float: left;
- height: 45px;
- width: 45px;
- margin: 0;
- border: none;
- cursor: pointer;
- background: #212121 no-repeat center center;
-}
-
-.ui-btn:hover {
- background-color: #111;
-}
-
-.ui-btn:last-child {
- -webkit-border-radius: 0 2px 2px 0;
- -moz-border-radius: 0 2px 2px 0;
- border-radius: 0 2px 2px 0;
-}
-
-#meta-data {
- bottom: 0;
-}
-
-#meta-data .ui-inner {
- position: relative;
-}
-
-#duration {
- content: ' ';
- position: absolute;
- top: 0;
- right: 100%;
- bottom: 0;
- left: 0;
- background: #fff;
- opacity: 0.25;
-}
-
-#artist {
- text-transform: uppercase;
- font-weight: normal;
- padding: 15px 15px 0 15px;
- margin: 0;
- margin-bottom: 5px;
-}
-
-#title {
- font-weight: normal;
- opacity: 0.8;
- padding: 0 15px 15px 15px;
- margin: 0;
-}
-
-.meta-data-words {
- display: block;
- width: 100%;
- color: #fff;
-
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- text-decoration: none;
-
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
-}
-
-.meta-data-words:hover {
- text-decoration: underline;
-}
-
-
-
-/* Bars */
-#reflection-overlay {
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- z-index: 10;
- opacity: 0.5;
-
- background: transparent; /* Old browsers */
- background: -moz-linear-gradient(top, transparent 50%, #000000 50%, #000000 50%, transparent 100%); /* FF3.6+ */
- background: -webkit-gradient(linear, left top, left bottom, color-stop(50%,transparent), color-stop(50%,#000000), color-stop(50%,#000000), color-stop(100%,transparent)); /* Chrome,Safari4+ */
- background: -webkit-linear-gradient(top, transparent 50%,#000000 50%,#000000 50%,transparent 100%); /* Chrome10+,Safari5.1+ */
- background: -o-linear-gradient(top, transparent 50%,#000000 50%,#000000 50%,transparent 100%); /* Opera 11.10+ */
- background: -ms-linear-gradient(top, transparent 50%,#000000 50%,#000000 50%,transparent 100%); /* IE10+ */
- background: linear-gradient(to bottom, transparent 50%,#000000 50%,#000000 50%,transparent 100%); /* W3C */
- filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='transparent', endColorstr='transparent',GradientType=0 ); /* IE6-9 */
-}
-
-.bar-wrapper {
- height: 100%;
- position: absolute;
-
- -webkit-transform: scaleY(0);
- -moz-transform: scaleY(0);
- transform: scaleY(0);
-
- -webkit-transition: -webkit-transform 50ms linear;
- -moz-transition: -moz-transform 50ms linear;
- -o-transition: -o-transform 50ms linear;
- transition: transform 50ms linear;
-}
-
-.bar {
- width: 12px;
- height: 100%;
-}
-
-.bar::before,
-.bar::after {
- position: absolute;
- content: ' ';
-}
-
-.bar::before {
- top: -3px;
- left: -6px;
- width: 6px;
- height: 100%;
-
- -webkit-transform: skew(0,45deg);
- -moz-transform: skew(0,45deg);
- -o-transform: skew(0,45deg);
- transform: skew(0,45deg);
-}
-
-.bar::after {
- top: -6px;
- left: -4px;
- width: 100%;
- height: 6px;
-
- -webkit-transform: skew(45deg);
- -moz-transform: skew(45deg);
- -o-transform: skew(45deg);
- transform: skew(45deg);
-}
-
-
-
-
-/* Hexagons */
-#overlay-container {
- -webkit-filter: saturate(140%);
- filter: saturate(140%);
-}
-
-.overlay {
- position: absolute;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
-
- -webkit-transition: opacity 500ms;
- -moz-transition: opacity 500ms;
- -o-transition: opacity 500ms;
- transition: opacity 500ms;
-
-}
-
-#hex-container {
- position: absolute;
- top: 50%;
- left: 50%;
- opacity: 0.9;
- margin: 0 auto;
-
- -webkit-animation: ambientMovement 30s ease-in-out infinite alternate;
- -moz-animation: ambientMovement 30s ease-in-out infinite alternate;
- -o-animation: ambientMovement 30s ease-in-out infinite alternate;
- animation: ambientMovement 30s ease-in-out infinite alternate;
-
- -webkit-transform: rotate(-180deg) translate(350px, 200px);
- -moz-transform: rotate(-180deg) translate(350px, 200px);
- -o-transform: rotate(-180deg) translate(350px, 200px);
- transform: rotate(-180deg) translate(350px, 200px);
-}
-
-.hex-wrapper {
- position: absolute;
- margin-left: -100px;
-
- -webkit-transition: -webkit-transform 50ms ease-in-out;
- -moz-transition: -moz-transform 50ms ease-in-out;
- -o-transition: -o-transform 50ms ease-in-out;
- transition: transform 50ms ease-in-out;
-}
-
-.hex {
- width: 208px;
- height: 120px;
- background: #6C6;
-}
-
-.hex:before, .hex:after {
- content:" ";
- border-left: 104px solid transparent;
- border-right: 104px solid transparent;
- position: absolute;
-}
-
-.hex:before {
- top: -60px;
- border-bottom: 60px solid #6C6;
-}
-
-.hex:after {
- bottom: -60px;
- border-top: 60px solid #6C6;
-}
-
-#circle-container {
- position: relative;
- z-index: 1;
- width: 100%;
- height: 100%;
-}
-
-.circle-wrapper {
- position: absolute;
- left: 50%;
- top: 50%;
-}
-
-.circle {
- position: absolute;
- top: 0;
- left: 0;
- bottom: 0;
- right: 0;
- margin: auto;
- background:
- linear-gradient(135deg, #ECEDDC 25%, transparent 25%) -50px 0,
- linear-gradient(225deg, #ECEDDC 25%, transparent 25%) -50px 0,
- linear-gradient(315deg, #ECEDDC 25%, transparent 25%),
- linear-gradient(45deg, #ECEDDC 25%, transparent 25%);
- background-size: 100px 100px;
- background-color: #EC173A;
-
- border: 3px solid black;
- box-shadow: 0 0 5px rgba(0,0,0,0.9);
-
- border-radius: 50%;
- -webkit-transform: translateX(-50%) translateZ(0px);
- -webkit-transform-origin: 0;
-
- -webkit-transition: transform 100ms linear;
-}
-
-/* Keyframes */
-@-webkit-keyframes ambientMovement {
- 0% {
- -webkit-transform: rotate(-180deg);
- top: 50%;
- left: 50%;
- }
-
- 25% {
- top: 10%;
- left: 90%;
- }
-
- 50% {
- -webkit-transform: rotate(-360deg);
- top: 60%;
- left: 70%;
- }
-
- 75% {
- top: 20%;
- left: 30%;
- }
-
- 100% {
- -webkit-transform: rotate(0deg);
- top: 90%;
- left: 10%;
- }
-}
-
-@-moz-keyframes ambientMovement {
- 0% {
- -webkit-transform: rotate(-180deg);
- top: 50%;
- left: 50%;
- }
-
- 25% {
- top: 10%;
- left: 90%;
- }
-
- 50% {
- -webkit-transform: rotate(-360deg);
- top: 60%;
- left: 70%;
- }
-
- 75% {
- top: 20%;
- left: 30%;
- }
-
- 100% {
- -webkit-transform: rotate(0deg);
- top: 90%;
- left: 10%;
- }
-}
-
-@-o-keyframes ambientMovement {
- 0% {
- -webkit-transform: rotate(-180deg);
- top: 50%;
- left: 50%;
- }
-
- 25% {
- top: 10%;
- left: 90%;
- }
-
- 50% {
- -webkit-transform: rotate(-360deg);
- top: 60%;
- left: 70%;
- }
-
- 75% {
- top: 20%;
- left: 30%;
- }
-
- 100% {
- -webkit-transform: rotate(0deg);
- top: 90%;
- left: 10%;
- }
-}
-
-@keyframes ambientMovement {
- 0% {
- -webkit-transform: rotate(-180deg);
- top: 50%;
- left: 50%;
- }
-
- 25% {
- top: 10%;
- left: 90%;
- }
-
- 50% {
- -webkit-transform: rotate(-360deg);
- top: 60%;
- left: 70%;
- }
-
- 75% {
- top: 20%;
- left: 30%;
- }
-
- 100% {
- -webkit-transform: rotate(0deg);
- top: 90%;
- left: 10%;
- }
-}
-
-@-webkit-keyframes toggleFullscreen {
- 0% {
- background-image: url('../imgs/glyphicons_215_resize_full.png');
- }
-
- 100% {
- background-image: url('../imgs/glyphicons_214_resize_small.png');
- }
-}
-
-@-moz-keyframes toggleFullscreen {
- 0% {
- background-image: url('../imgs/glyphicons_215_resize_full.png');
- }
-
- 100% {
- background-image: url('../imgs/glyphicons_214_resize_small.png');
- }
-}
-
-@-o-keyframes toggleFullscreen {
- 0% {
- background-image: url('../imgs/glyphicons_215_resize_full.png');
- }
-
- 100% {
- background-image: url('../imgs/glyphicons_214_resize_small.png');
- }
-}
-
-@keyframes toggleFullscreen {
- 0% {
- background-image: url('../imgs/glyphicons_215_resize_full.png');
- }
-
- 100% {
- background-image: url('../imgs/glyphicons_214_resize_small.png');
- }
-}
\ No newline at end of file
diff --git a/imgs/favicon.ico b/imgs/favicon.ico
deleted file mode 100644
index 69159f3..0000000
Binary files a/imgs/favicon.ico and /dev/null differ
diff --git a/imgs/glyphicons_027_search.png b/imgs/glyphicons_027_search.png
deleted file mode 100644
index 95b2de9..0000000
Binary files a/imgs/glyphicons_027_search.png and /dev/null differ
diff --git a/imgs/glyphicons_173_play.png b/imgs/glyphicons_173_play.png
deleted file mode 100644
index a0f6cfb..0000000
Binary files a/imgs/glyphicons_173_play.png and /dev/null differ
diff --git a/imgs/glyphicons_174_pause.png b/imgs/glyphicons_174_pause.png
deleted file mode 100644
index a24e65b..0000000
Binary files a/imgs/glyphicons_174_pause.png and /dev/null differ
diff --git a/imgs/glyphicons_178_step_forward.png b/imgs/glyphicons_178_step_forward.png
deleted file mode 100644
index 3102374..0000000
Binary files a/imgs/glyphicons_178_step_forward.png and /dev/null differ
diff --git a/imgs/glyphicons_194_circle_question_mark.png b/imgs/glyphicons_194_circle_question_mark.png
deleted file mode 100644
index 22e96ae..0000000
Binary files a/imgs/glyphicons_194_circle_question_mark.png and /dev/null differ
diff --git a/imgs/glyphicons_214_resize_small.png b/imgs/glyphicons_214_resize_small.png
deleted file mode 100644
index cb70f62..0000000
Binary files a/imgs/glyphicons_214_resize_small.png and /dev/null differ
diff --git a/imgs/glyphicons_215_resize_full.png b/imgs/glyphicons_215_resize_full.png
deleted file mode 100644
index f7d4f86..0000000
Binary files a/imgs/glyphicons_215_resize_full.png and /dev/null differ
diff --git a/index.html b/index.html
deleted file mode 100644
index 2f1eacd..0000000
--- a/index.html
+++ /dev/null
@@ -1,141 +0,0 @@
-
-
-
-
-
-
-
CSS Music Visualizers
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/jitsu.md b/jitsu.md
deleted file mode 100644
index 629f7e8..0000000
--- a/jitsu.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# Node Apps
-## socket.io boilerplate
-
-[http://socket.io](http://socket.io)
-
-
-
-# Installation
-
- mkdir myapp
- cd myapp/
- jitsu install socket.io
-
-*If you do not have `jitsu` installed you can install it via `npm install jitsu -g`*
-
-
-# Usage
-
-### Starting boilerplate locally
-
- npm start
-
-*Now you can visit http://localhost:8080 to view your application*
-
-### Deploy boilerplate to nodejitsu
-
- jitsu deploy
-
-*You will now be prompted for a `subdomain` to deploy your application on*
-
-
-# License
-
-(The MIT License)
-
-Copyright (c) 2013 Nodejitsu
-
-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.
diff --git a/js/app/app.js b/js/app/app.js
deleted file mode 100644
index ab2110d..0000000
--- a/js/app/app.js
+++ /dev/null
@@ -1,25 +0,0 @@
-define(['app/visualizers/base', 'underscore', 'bean', 'app/models/DesktopQueue', 'app/view'], function (Base, _, Bean, DesktopQueue, view) {
-
- var App = {
-
- init: function() {
-
- var onLoadFunc = function () {
- Bean.off(document, 'onload');
-
- DesktopQueue.init();
- view.init();
- };
-
- if (document.readyState === "complete") {
- onLoadFunc();
- } else {
- Bean.on(document, 'onload', onLoadFunc);
- }
- }
-
- };
-
- return App;
-
-});
\ No newline at end of file
diff --git a/js/app/chromecast/receiver/main.js b/js/app/chromecast/receiver/main.js
deleted file mode 100644
index d93a512..0000000
--- a/js/app/chromecast/receiver/main.js
+++ /dev/null
@@ -1,54 +0,0 @@
-require.config({
-
- baseUrl: '/js',
-
- paths: {
- bean: 'libs/bean.min',
- underscore: 'libs/underscore-min',
- backbone: 'libs/backbone',
- jquery: 'libs/jquery-2.1.3.min',
-
- q: 'libs/q.min',
- socketio:[
- '//cdnjs.cloudflare.com/ajax/libs/socket.io/1.2.1/socket.io.min',
- 'libs/socket.io.min'
- ]
- },
-
- shim: {
- 'bean': {
- exports: 'bean'
- },
- 'underscore': {
- exports: '_'
- },
- 'jquery': {
- exports: '$'
- },
- backbone: {
- deps: ["underscore", "jquery"],
- exports: "Backbone"
- },
- 'q': {
- exports: 'q'
- },
- 'socketio': {
- exports: 'io'
- }
- }
-
-});
-
-require([
- 'app/chromecast/receiver/receiver',
- 'app/chromecast/receiver/socket',
- 'app/chromecast/receiver/queue',
- 'app/chromecast/receiver/player',
- 'app/chromecast/receiver/view'
-], function (receiver, socket, queue, player, view) {
- view.init();
- player.init();
- queue.init();
- socket.init();
- receiver.init();
-});
\ No newline at end of file
diff --git a/js/app/chromecast/receiver/player.js b/js/app/chromecast/receiver/player.js
deleted file mode 100644
index a41cfa1..0000000
--- a/js/app/chromecast/receiver/player.js
+++ /dev/null
@@ -1,83 +0,0 @@
-define(['app/options', 'bean'], function(Options, Bean) {
-
- var Player = {
-
- isLoaded: false,
- isMetadataLoaded: false,
- isPlaying: false,
- audio: window.mediaElement,
-
- currentTime: 0,
- secondTimer: '',
-
- mediaManager: window.mediaManager,
-
- init: function() {
- Bean.on(this.audio, 'paused', this.onPlayPause.bind(this));
- Bean.on(this.audio, 'play', this.onPlayPause.bind(this));
- Bean.on(this.audio, 'load', this.onLoad.bind(this));
-// Bean.on(this.audio, 'playing', _.throttle(this.onPlayPause.bind(this), 100));
-
-// this.mediaManager.onLoad = this.onLoad.bind(this);
-// this.mediaManager.onLoad = this.onLoad.bind(this);
-
- Bean.on(window, 'player.metadata', this.onMetadataLoad.bind(this));
- Bean.on(window, 'player.connected', this.onSocketConnected.bind(this));
- },
-
- onPlayPause: function() {
- this.isPlaying = this.audio.duration > 0 && !this.audio.paused;
-
- //Set time so we don't have to get it from audio tag.
- this.currentTime = Math.floor(this.audio.currentTime);
-
- //Reset frames
- this.currentFrame = 0;
-
- //Reset timer regardless of play state change.
- clearInterval(this.secondTimer);
-
- if (this.isPlaying) {
-
- //Reset current second timer
- this.secondTimer = setInterval(this.secondClock.bind(this), 1000);
-
- //Start visualizer
- Bean.fire(window, 'view.visStart');
- }
- },
-
- onLoad: function(ev) {
- this.isLoaded = true;
-
- this.startPlayback();
- },
-
- onMetadataLoad: function(ev) {
- this.isMetadataLoaded = true;
-
- Bean.fire(window, 'receiver.message', 'chromecast.metadataReceived');
-
- this.startPlayback();
- },
-
- onSocketConnected: function() {
- this.socketConnected = true;
-
- this.startPlayback();
- },
-
- startPlayback: function() {
- if (this.socketConnected && this.isLoaded && this.isMetadataLoaded) {
- this.audio.play();
- }
- },
-
- secondClock: function() {
- this.currentTime++;
- this.currentFrame = 0;
- }
- };
-
- return Player;
-});
diff --git a/js/app/chromecast/receiver/queue.js b/js/app/chromecast/receiver/queue.js
deleted file mode 100644
index 6530d59..0000000
--- a/js/app/chromecast/receiver/queue.js
+++ /dev/null
@@ -1,40 +0,0 @@
-define(['app/options', 'bean', 'app/models/Queue'], function(Options, Bean, Queue) {
-
- var ChromecastQueue = _.extend({
-
- init: function() {
- Bean.on(window, 'queue.metadata', this.onMetadata.bind(this));
- Bean.on(window, 'queue.audiodata', this.onAudiodata.bind(this));
- Bean.on(window, 'queue.showdata', this.showData.bind(this));
- },
-
- onAudiodata: function(data) {
- //Parse fake audioDataPacket from string into simple obj with seconds data.
- var audioDataPacket = data.audioDataPacket;
-
- var song = this.getCurrentSong();
-
- song.audioDataPacket.mergePackets(audioDataPacket);
-
- this.setCurrentSong(song);
- Bean.fire(window, 'queue.showData');
- },
-
- getCurrentSongFrame: function(currentSecond, currentFrame) {
- var song = this.getCurrentSong();
- return song.audioDataPacket.getFrame(currentSecond, currentFrame);
- },
-
- onMetadata: function(metadata) {
- console.log('metadata received')
- this.addSongFromMetadata(metadata);
- Bean.fire(window, 'player.metadata');
- },
-
- showData: function() {
- console.log(this.audioDataPacket);
- }
- }, Queue);
-
- return ChromecastQueue;
-});
diff --git a/js/app/chromecast/receiver/receiver.js b/js/app/chromecast/receiver/receiver.js
deleted file mode 100644
index 51e367d..0000000
--- a/js/app/chromecast/receiver/receiver.js
+++ /dev/null
@@ -1,42 +0,0 @@
-define(['app/options', 'bean'], function(Options, Bean) {
-
- var Receiver = {
-
- castReceiverManager: window.castReceiverManager,
-
- init: function() {
- this.customMessageBus = castReceiverManager.getCastMessageBus(Options.chromecastNamespace);
- this.customMessageBus.onMessage = this.onMessage;
-
- this.castReceiverManager.onSenderDisconnected = this.onSenderDisconnected.bind(this);
- this.castReceiverManager.onSenderConnected = this.onSenderConnected.bind(this);
- this.castReceiverManager.start();
-
- Bean.on(window, 'receiver.message', _.bind(this.sendMessage, this));
- },
-
- onMessage: function(ev) {
- var data = JSON.parse(ev.data);
- Bean.fire(window, data.event, data.value);
- },
-
- sendMessage: function(message) {
- this.customMessageBus.send(this.sender, message)
- },
-
- onSenderConnected: function(sender) {
- this.sender = sender.senderId;
-
- this.customMessageBus.broadcast('socket.sendRoom');
- },
-
- onSenderDisconnected: function(ev) {
- if(this.castReceiverManager.getSenders().length == 0 &&
- ev.reason == cast.receiver.system.DisconnectReason.REQUESTED_BY_SENDER) {
- window.close();
- }
- }
- };
-
- return Receiver;
-});
diff --git a/js/app/chromecast/receiver/socket.js b/js/app/chromecast/receiver/socket.js
deleted file mode 100644
index f863cd2..0000000
--- a/js/app/chromecast/receiver/socket.js
+++ /dev/null
@@ -1,43 +0,0 @@
-define(['app/options', 'bean', 'socketio', 'app/chromecast/receiver/visualizers/bars'], function(Options, Bean, io, visualizer) {
-
- var Socket = {
-
- room: 0,
-
- init: function() {
-
- Bean.on(window, 'socket.subscribe', this.subscribeSocket.bind(this));
-
- // Connect to socket.io
- this.socket = io.connect();
- this.socket.on('connect', function() {
- this.socket.on('chromecast-audiodata', this.onAudiodata);
- }.bind(this));
-
- this.socket.on('chromecast-connected', this.onSocketConnection);
- },
-
- subscribeSocket: function(data) {
-
- console.log('subscribing to socket')
-
- //Join room with roomID from desktop
- this.socket.emit('chromecast-subscribe', {
- room: data.room,
- visSettings: visualizer.settings
- });
- },
-
- onSocketConnection: function() {
- Bean.fire(window, 'player.connected');
- },
-
- onAudiodata: function(data) {
- Bean.fire(window, 'queue.audiodata', data);
- }
-
- };
-
- return Socket;
-
-});
\ No newline at end of file
diff --git a/js/app/chromecast/receiver/view.js b/js/app/chromecast/receiver/view.js
deleted file mode 100644
index cddce10..0000000
--- a/js/app/chromecast/receiver/view.js
+++ /dev/null
@@ -1,18 +0,0 @@
-define(['app/options', 'bean', 'app/chromecast/receiver/visualizers/bars'], function(Options, Bean, Bars) {
-
- var View = {
-
- init: function() {
- Bean.on(window, 'view.visStart', this.startVisualizer.bind(this));
- },
-
- startVisualizer: function() {
- if (!this.visualizer) {
- this.visualizer = Bars;
- this.visualizer.run();
- }
- }
- };
-
- return View;
-});
diff --git a/js/app/chromecast/receiver/visualizers/bars.js b/js/app/chromecast/receiver/visualizers/bars.js
deleted file mode 100644
index cc9bfb8..0000000
--- a/js/app/chromecast/receiver/visualizers/bars.js
+++ /dev/null
@@ -1,96 +0,0 @@
-define(['underscore', 'app/chromecast/receiver/visualizers/base'], function (_, Base) {
-
- var Bars = _.extend({
-
- visualizer: document.getElementById('visualizer'),
-
- color1: randomColor(),
- color2: randomColor(),
-
- //Anything in this object will be sent to the chromecast visualizer on the desktop (after init() has run)
- settings: {
- fps: 40,
- numOfBars: 0
- },
-
- barWidth: 24,
- bars: [],
-
- init: function() {
- this.setNumOfBars();
-
- var styleSheet = document.createElement('style');
-
- this.setColors(styleSheet);
-
- styleSheet.id = 'visualizer-css';
- document.head.appendChild(styleSheet);
-
- this.setupElements();
- },
-
- setNumOfBars: function() {
- this.settings.numOfBars = Math.floor(window.innerWidth / this.barWidth);
- },
-
- setupElements: function() {
- var reflectionOverlay = document.createElement('div');
-
- reflectionOverlay.id = "reflection-overlay";
-
- this.visualizer.innerHTML = '';
- this.visualizer.appendChild(reflectionOverlay);
-
- for (var i = 0; i < this.settings.numOfBars; i++) {
- var bar = document.createElement('div'),
- barWrapper = document.createElement('div');
-
- bar.className = 'bar';
- barWrapper.className = 'bar-wrapper';
- barWrapper.style.left = i*24 + "px";
-
- barWrapper.appendChild(bar);
- this.visualizer.appendChild(barWrapper);
- }
-
- this.bars = document.getElementsByClassName('bar');
- },
-
- setColors: function(styleSheet) {
- styleSheet = styleSheet || document.getElementById('visualizer-css');
- var stylesStr = '';
- var color = this.color1;
-
- for (var i = 0; i < this.settings.numOfBars; i++) {
-
- var startOfSelectorStr = '.bar-wrapper:nth-of-type(' + (i + 2) + ') .bar', // Its '+ 2' because reflectionOverlay is first-child
- beforeStr = startOfSelectorStr + ':before { background-color: ' + lighterColor(color, 0.1) + '; }',
- afterStr = startOfSelectorStr + ':after { background-color: ' + darkerColor(color, 0.1) + '; }',
- barStr = startOfSelectorStr + ' { background-color: ' + darkerColor(color, 0.2) + '; }';
-
- stylesStr += beforeStr + afterStr + barStr;
-
- color = fadeToColor(color, this.color2, 1/this.settings.numOfBars);
- }
-
- styleSheet.innerHTML = stylesStr;
- },
-
- onWaveform: function(waveform) {
- var bars = this.bars;
- var numBars = this.settings.numOfBars;
-
- for (var j = 0; j < numBars; j++) {
- var magnitude = waveform[j];
- bars[j].parentNode.style[prefix.css + 'transform'] = ["scaleY(", magnitude, ") translate3d(0,0,0)"].join("");
- }
- }
-
- }, Base);
-
- //Need to run this so that window.innerWidth is the width of the chromecast's window, later sent to desktop
- Bars.setNumOfBars();
-
- return Bars;
-
-});
\ No newline at end of file
diff --git a/js/app/chromecast/receiver/visualizers/base.js b/js/app/chromecast/receiver/visualizers/base.js
deleted file mode 100644
index 9bef4d7..0000000
--- a/js/app/chromecast/receiver/visualizers/base.js
+++ /dev/null
@@ -1,58 +0,0 @@
-define(['app/options', 'bean', 'app/chromecast/receiver/player', 'app/chromecast/receiver/queue'], function (Options, Bean, Player, Queue) {
- var Base = {
- visualizer: document.getElementById('visualizer'),
- currentFrame: 0,
-
- run: function() {
- this.clear();
-
- this.init();
-
- var fps = 60;
- if (this.fps) {
- fps = this.fps;
- }
-
- this.AnimationTimer = setInterval(_.bind(this.getData, this), 50 + (60 - this.fps));
- },
-
- clear: function() {
- var styleSheet = document.getElementById('visualizer-css');
- if (styleSheet) {
- document.head.removeChild(styleSheet);
- }
- this.visualizer.innerHTML = '';
- },
-
- getData: function() {
- if (Player.isPlaying) {
- var currentSecond = Player.currentTime;
- var currentFrame = Player.currentFrame;
-
- //Get the data packet for the currentTime of the song
- var data = Queue.getCurrentSongFrame(currentSecond, currentFrame);
-
- //Increment currentFrame on Player so it can be read later.
- Player.currentFrame++;
-
- if (this.onSpectrum) {
- this.onSpectrum(data);
- }
-
- if (this.onWaveform) {
- this.onWaveform(data);
- }
- }
- },
-
- destroy: function() {
- clearInterval(this.AnimationTimer);
-
- if (this.onDestroy) {
- this.onDestroy();
- }
- }
- };
-
- return Base;
-});
\ No newline at end of file
diff --git a/js/app/chromecast/sender/sender.js b/js/app/chromecast/sender/sender.js
deleted file mode 100644
index 5126473..0000000
--- a/js/app/chromecast/sender/sender.js
+++ /dev/null
@@ -1,146 +0,0 @@
-define(['app/options', 'bean', 'app/models/Queue', 'chromecast'], function (Options, Bean, Queue) {
-
- var Sender = {
-
- chromecastBtn: document.getElementById('chromecast'),
- session: '',
- currentMediaUrl: '',
- currentMedia: '',
- chromeLibTimer: '',
-
- init: function() {
- Bean.on(this.chromecastBtn, 'click', this.requestSession.bind(this));
- Bean.on(window, 'sender.loadMedia', this.loadMedia.bind(this));
- Bean.on(window, 'sender.stop', this.stopSession);
- Bean.on(window, 'sender.message', this.sendMessage.bind(this));
-
- if (!window.chromecastLoaded) {
- window['__onGCastApiAvailable'] = function(loaded, errorInfo) {
- if (loaded) {
- this.initializeCastApi();
- } else {
- console.log(errorInfo);
- }
- }.bind(this);
- } else {
- this.initializeCastApi();
- }
-
- },
-
- initializeCastApi: function() {
- if (this.initialized) {
- return false;
- }
-
- this.initialized = true;
- console.log('cast api trying to initialize');
- var sessionRequest = new chrome.cast.SessionRequest(Options.chromecastAppID);
- var apiConfig = new chrome.cast.ApiConfig(sessionRequest, this.sessionListener.bind(this), this.receiverListener);
-
- chrome.cast.initialize(apiConfig, function() {
- console.log('success');
- }, function() {
- console.log('on error');
- });
- },
-
- sessionListener: function(ev) {
- console.log('session listener fired');
-
- this.onSession(ev);
- },
-
- receiverListener: function(ev) {
- if (ev === chrome.cast.ReceiverAvailability.AVAILABLE) {
- console.log('receiver available');
- } else {
- console.log('receiver unavailable', ev);
- }
- },
-
- requestSession: function() {
- if (!this.session) {
- chrome.cast.requestSession(function(e) {
- this.onSession(e);
- console.log('request session success')
- }.bind(this), function(e) {
- console.log('request session error', e)
- });
- } else {
- console.log('Attempting to disconnect chromecast');
- }
- },
-
- onSession: function(session) {
- this.session = session;
-
- this.session.removeMessageListener(Options.chromecastNamespace, this.onMessage.bind(this));
- this.session.addMessageListener(Options.chromecastNamespace, this.onMessage.bind(this));
-
- Bean.fire(window, 'socket.connect');
-
- console.log('on session')
-
-
- //Browser was reloaded and media was grabbed again.
- if (this.session.media.length != 0) {
- this.onMediaLoaded('onRequestSessionSuccess', session.media[0]);
- } else {
- if (this.currentMediaUrl) {
- this.loadMedia(this.currentMediaUrl);
- }
- }
-
- },
-
- onMessage: function(namespace, message) {
- console.log(namespace, message);
- Bean.fire(window, message);
- },
-
- loadMedia: function(mediaUrl) {
- this.currentMediaUrl = mediaUrl;
-
- var mediaInfo = new chrome.cast.media.MediaInfo(mediaUrl, "audio/mpeg");
- var request = new chrome.cast.media.LoadRequest(mediaInfo);
-
- this.session.loadMedia(request, this.onMediaLoaded.bind(this, 'loadMedia'), function(err) {
- console.log('media load error', err);
- });
- },
-
- onMediaLoaded: function(how, media) {
- console.log('media loaded success', media)
- media.addUpdateListener(function() {
- console.log('media updated');
- });
- this.currentMedia = media;
-
- var song = Queue.getCurrentSong();
- this.sendMessage({
- event: 'queue.metadata',
- value: song.getMetadata(true)
- });
- },
-
- stopSession: function() {
- this.session.stop(function() {
- console.log('stop successful');
- }, function(err) {
- console.log('stop error', err);
- });
- },
-
- sendMessage: function(message) {
- this.session.sendMessage(Options.chromecastNamespace, message, function() {
- console.log('message sent success');
- }, function(err) {
- console.log('message sent error');
- })
- }
-
- };
-
- return Sender;
-});
\ No newline at end of file
diff --git a/js/app/chromecast/sender/socket.js b/js/app/chromecast/sender/socket.js
deleted file mode 100644
index 6a251f4..0000000
--- a/js/app/chromecast/sender/socket.js
+++ /dev/null
@@ -1,85 +0,0 @@
-define(['app/options', 'bean', 'socketio'], function (Options, Bean, io) {
-
- var Socket = {
-
- socket: '',
- room: '',
-
- init: function() {
- Bean.on(window, 'socket.connect', this.connect.bind(this));
- Bean.on(window, 'socket.sendRoom', this.sendRoom.bind(this));
- },
-
- connect: function() {
-
- // Connect to socket.io
- this.socket = io.connect();
-
- //Connect to server
- this.socket.on('connect', function(){
-
- //Get the roomID to send to the chromecast
- this.socket.on('joined-room', this.joinedRoom.bind(this));
-
- console.log('socket room created');
- //Create a room for this desktop and a chromecast
- this.socket.emit('create-room');
-
-
- }.bind(this));
- },
-
- joinedRoom: function(roomID) {
- console.log('room joined');
-
- //This socket is already in room
- if (this.room !== '') {
- return;
- }
-
- //When chromecast is connected allow playback
- this.socket.on('chromecast-connected', function(visSettings) {
- console.log('chromecast connected to socket')
-
- //Remove any events for a second possible misfire
- Bean.off(window, 'socket.audiodata');
- Bean.on(window, 'socket.audiodata', this.sendAudioData.bind(this));
-
- //Let other modules know the chromecast has conencted
- Bean.fire(window, 'chromecastConnected', visSettings);
- }.bind(this));
-
- this.room = roomID;
-
- console.log('on room joined',this.room);
-
- this.sendRoom();
- },
-
- sendRoom: function() {
-
- console.log('room is:', this);
-
- //Send roomID to chromecast to connect to server as well
- Bean.fire(window, 'sender.message', {
- event: 'socket.subscribe',
- value: {
- room: this.room
- }
- });
-
- console.log('room id sent to chromecast')
-
- },
-
- sendAudioData: function(data) {
- this.socket.emit('server-audiodata', {
- room: this.room,
- songChanged: data.songChanged,
- audioDataPacket: data.audioDataPacket
- });
- }
- };
-
- return Socket;
-});
\ No newline at end of file
diff --git a/js/app/controllers/Player.js b/js/app/controllers/Player.js
deleted file mode 100644
index d1f3ca3..0000000
--- a/js/app/controllers/Player.js
+++ /dev/null
@@ -1,44 +0,0 @@
-define([
- 'app/options',
- 'bean'
-], function (
- Options,
- Bean
- ) {
-
- var Player = {
-
- ui: document.getElementById('ui'),
- playPause: document.getElementById('play-pause'),
- next: document.getElementById('next'),
- duration: document.getElementById('duration'),
- volumeSlider: document.getElementById('volume-slider'),
-
- init: function() {
- Bean.on(this.playPause, 'click', _.bind(this.onPlayPause, this));
- Bean.on(this.next, 'click', this.onNext);
-
- Bean.on(this.volumeSlider, 'change', _.bind(this.onVolumeChange, this));
- Bean.on(window, 'playerController.announceVolume', _.bind(this.onVolumeChange, this));
-
- },
-
- onVolumeChange: function(ev) {
- var volume = this.volumeSlider.value / 100;
-
- Bean.fire(window, 'playerModel.volumeChange', volume);
- },
-
- onNext: function() {
- Bean.fire(window, 'playerView.next');
- },
-
- onPlayPause: function() {
- var playing = dancer.isPlaying();
-
- Bean.fire(window, 'playerView.playPause', playing);
- }
- };
-
- return Player;
-});
diff --git a/js/app/models/DesktopQueue.js b/js/app/models/DesktopQueue.js
deleted file mode 100644
index bce4c34..0000000
--- a/js/app/models/DesktopQueue.js
+++ /dev/null
@@ -1,217 +0,0 @@
-define(['app/options', 'bean', 'app/models/Queue', 'app/chromecast/sender/sender', 'soundcloud', 'q', 'underscore'], function (Options, Bean, Queue, sender, SC, Q, _) {
-
- var DesktopQueue = _.extend({
-
- dataPacketTimer: '',
-
- init: function() {
- Bean.on(window, 'model.search', _.bind(this.search, this));
- Bean.on(window, 'chromecastConnected', this.onChromecastConnected.bind(this));
- Bean.on(window, 'chromecast.metadataReceived', _.bind(this.onMetadataSent, this));
- Bean.on(window, 'chromecastDisconnected', this.onChromecastDisconnected.bind(this));
- Bean.on(window, 'queue.requestNextSong', _.bind(this.sendNextSong, this));
- Bean.on(window, 'queue.packFrame', _.bind(this.packSongData, this));
-
- this.setupMusic();
- },
-
- setupMusic: function() {
- var tracksLoaded = 0;
-
- for (var i = 0; i < this.songsCache.length; i++) {
- var promise = this.search(this.songsCache[i].streamUrl);
-
- promise.then(_.bind(function() {
- tracksLoaded++;
-
- if (tracksLoaded >= this.songsCache.length) {
- if (Options.autoplayRandom) {
- this.currentSong = this.getRandomSongNum();
- }
-
- sender.init();
-
- Bean.fire(window, 'next');
- }
- }, this));
- }
- },
-
- search: function(searchVal) {
- var hostname = getLocation(searchVal);
- var dotlocation = hostname.indexOf('.');
-
- hostname = hostname.substr(0, dotlocation);
-
- if (hostname === 'soundcloud') {
- var deferred = Q.defer();
- var promise = deferred.promise;
-
- SC.get('/resolve', { url: searchVal }, _.bind(function(urlData) {
- var userID = urlData.id;
- var fetchingURL = '';
-
- switch (urlData.kind) {
- case "user":
- fetchingURL = '/users/' + userID + '/tracks';
- this.getMultipleSongs(fetchingURL, deferred);
-
- break;
-
- case "track":
- this.addSong(urlData);
- deferred.resolve();
- break;
-
- case "playlist":
- fetchingURL = '/playlist/' + userID + '/tracks';
- this.getMultipleSongs(fetchingURL, deferred);
- break;
- }
-
- promise.then(_.bind(function() {
- Bean.fire(window, 'next');
- }, this));
-
- }, this));
-
- return promise;
- } else if (hostname === 'grooveshark') {
- console.log('grooveshark url');
- }
- },
-
- getMultipleSongs: function(fetchingURL, deferred) {
- SC.get(fetchingURL, _.bind(function(tracks) {
- for (var i = 0; i < tracks.length; i++) {
- var track = tracks[i];
- this.addSong(track);
- }
-
- if (deferred) {
- deferred.resolve();
- }
- }, this));
- },
-
- sendNextSong: function() {
- this.setNextSong();
-
- var songInfo = this.getCurrentSong().metadata;
-
- if (this.chromecastConnected) {
- Bean.fire(window, 'sender.loadMedia', songInfo.streamUrl);
- }
-
- Bean.fire(window, 'player.trackInfo', songInfo);
- },
-
- onChromecastConnected: function() {
- this.chromecastConnected = true;
- },
-
- onMetadataSent: function() {
- console.log('metadata sent');
- this.dataPacketTimer = setInterval(this.sendDataPacket.bind(this), 1000);
- },
-
- onChromecastDisconnected: function() {
- this.chromecastConnected = false;
- clearTimeout(this.dataPacketTimer);
- },
-
- sendDataPacket: function() {
- if (dancer.isPlaying()) {
- var song = this.getCurrentSong();
-
- Bean.fire(window, 'socket.audiodata', {
- songChanged: this.songChanged,
- audioDataPacket: song.audioDataPacket.serializeData()
- });
-
- song.audioDataPacket.emptyPackets();
-
- this.setCurrentSong(song);
- }
- },
-
- packSongData: function(data) {
- var song = this.getCurrentSong();
- song.audioDataPacket.packFrame(data.frame, data.second);
- this.setCurrentSong(song);
- },
-
- songsCache: [
-// {
-// artist: 'Alex Metric',
-// title: 'Scandalism',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/alexmetric/scandalism'
-// },
- {
- artist: 'Kygo',
- title: 'Sexual Healing (Remix)',
- format: 'mp3',
- streamUrl: 'https://soundcloud.com/kygo/marvin-gaye-sexual-healing'
- },
- {
- artist: 'Bondax',
- title: 'All Inside',
- format: 'mp3',
- streamUrl: 'https://soundcloud.com/bondax/all-inside'
-// },
-// {
-// artist: 'Estelle Miller',
-// title: 'Jacknjill',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/estelle-miller/jacknjill'
-// },
-// {
-// artist: 'Estelle Miller',
-// title: 'Delicate Words',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/estelle-miller/delicate-words'
-// },
-// {
-// artist: 'Nobuo Uematsu',
-// title: 'To Zanarkand',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/final-fantasy-soundtracks/final-fantasy-x-ost-to'
-// },
-// {
-// artist: 'Koji Kondo',
-// title: 'Song of Storms',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/user6966642/the-legend-of-zelda-song-of-storms'
-// },
-// {
-// artist: 'Carl Douglas',
-// title: 'Kung Fu Fighting 1974 Disco',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/kuploadr3/carl-douglas-kung-fu-fighting'
-// },
-// {
-// artist: 'Ella Fitzgerald',
-// title: 'Someone To Watch Over Me',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/maha-khalid-1/ella-fitzgerald-someone-to'
-// },
-// {
-// artist: 'Neon Indian',
-// title: 'Polish Girl',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/mgmtneonindian/polish-girl'
-// },
-// {
-// artist: 'Toto',
-// title: 'Africa',
-// format: 'mp3',
-// streamUrl: 'https://soundcloud.com/kuploadr/toto-africa'
- }
- ]
-
- }, Queue);
-
- return DesktopQueue;
-
-});
\ No newline at end of file
diff --git a/js/app/models/Queue.js b/js/app/models/Queue.js
deleted file mode 100644
index 45fa3e3..0000000
--- a/js/app/models/Queue.js
+++ /dev/null
@@ -1,82 +0,0 @@
-define(['app/models/Song'], function (Song) {
-
- var Queue = {
- songsListenedTo: [],
- songs: [],
- currentSong: 0,
-
- resetSongs: function() {
- this.songs = [];
- this.currentSong = 0;
- },
-
- addSong: function(track) {
- var song = new Song();
- song.setMetadata({
- streamUrl: track.stream_url + '?client_id=' + clientID,
- title: track.title,
- titleUrl: track.permalink_url,
- artist: track.user.username,
- artistUrl: track.user.permalink_url,
- length: track.duration
- });
- this.songs.push(song);
- },
-
- addSongFromMetadata: function(metadata) {
- var song = new Song();
- song.setMetadata(metadata, true);
- this.songs.push(song);
- },
-
- getRandomSongNum: function() {
- var randomNum;
- var songsListened = this.getListenedSongs();
-
- if (songsListened.length < this.songs.length) {
-
- randomNum = Math.floor(Math.random()*this.songs.length);
-
- if (!this.songs[randomNum].listened) {
- return randomNum;
- } else {
- return this.getRandomSongNum();
- }
-
- } else {
- this.resetSongHistory();
-
- return 0;
- }
- },
-
- getListenedSongs: function() {
- return this.songs.filter(function(song) {
- return song.listened;
- });
- },
-
- resetSongHistory: function() {
- for (var i = 0; i < this.songs.length; i++) {
- this.songs[i].listened = false;
- }
- },
-
- setNextSong: function() {
- this.songs[this.currentSong].listened = true;
- this.currentSong = this.getRandomSongNum();
- },
-
- getCurrentSong: function() {
- return this.songs[this.currentSong];
- },
-
- setCurrentSong: function(song) {
- this.songs[this.currentSong] = song;
- }
-
- };
-
- return Queue;
-
-});
\ No newline at end of file
diff --git a/js/app/models/Song.js b/js/app/models/Song.js
deleted file mode 100644
index 9a7dc44..0000000
--- a/js/app/models/Song.js
+++ /dev/null
@@ -1,23 +0,0 @@
-define(['app/models/audio-data-packet' ,'backbone'], function(AudioDataPacket, Backbone) {
-
- var Song = Backbone.Model.extend({
-
- metadata: {},
- listened: false,
- audioDataPacket: new AudioDataPacket(),
-
- setMetadata: function(songInfo, serialized) {
- this.metadata = (serialized) ? JSON.parse(songInfo) : songInfo;
- },
-
- getMetadata: function(serialize) {
- return (serialize) ? JSON.stringify(this.metadata) : this.metadata;
- },
-
- showData: function() {
- console.log(this.audioDataPacket);
- }
- });
-
- return Song;
-});
diff --git a/js/app/models/audio-data-packet.js b/js/app/models/audio-data-packet.js
deleted file mode 100644
index 2bc3a87..0000000
--- a/js/app/models/audio-data-packet.js
+++ /dev/null
@@ -1,89 +0,0 @@
-define(['underscore', 'backbone'], function (_, Backbone) {
- var AudioDataPacket = Backbone.Model.extend({
-
- seconds: {},
- secondNums: [],
- lastCompleteSecond: 0,
-
- emptyPackets: function() {
- //Get any partial that might not have been sent between intervals
- var partialSecondNum = this.lastCompleteSecond + 1;
- var partialSecond = this.seconds[partialSecondNum];
-
- //Empty data
- this.seconds = {};
- this.secondNums = [];
-
- //Replace partial second.
- this.seconds[partialSecondNum] = partialSecond;
- this.secondNums.push(partialSecondNum);
- },
-
- mergePackets: function(packet) {
- packet = this.deserializeData(packet);
-
- for (var i = 0; i < packet.secondNums.length; i++) {
- var secondNumber = packet.secondNums[i];
- var packetFrames = this.smartParse(packet.seconds[secondNumber]);
- var localFrames = this.seconds[secondNumber] || [];
-
- //Get frame string from frames array, convert to array, and add to local stack.
- for (var j = 0; j < packetFrames.length; j++) {
- var frame = this.smartParse(packetFrames[j]);
- localFrames.push(frame);
- }
-
- //Reset the local stack whether its empty or not.
- this.seconds[i] = localFrames;
- }
- },
-
- getFrame: function(second, frame) {
- var frames = this.seconds[second] || []; //get all the frames at a particular second
-
- return frames[frame] || [];
- },
-
- packFrame: function(frame, second) {
- //Set the frame to the position in the seconds obj that's specified
- var frames = this.smartParse(this.seconds[second]);
-
- //Add record that the second has been added
- if (_.indexOf(this.secondNums, second) < 0) {
- this.secondNums.push(second);
- }
-
- //Stringify value to make it easier to send
- frames.push(JSON.stringify(frame));
-
- //Stringify the whole frames array and reassign back as the correct second.
- this.seconds[second] = JSON.stringify(frames);
-
- //Set the last completed second
- if (second > this.lastCompleteSecond) {
- this.lastCompleteSecond = second - 1;
- }
- },
-
- smartParse: function(array) {
- return array ? JSON.parse(array) : []
- },
-
- serializeData: function() {
- //Complex objects can be sent through the socket so we just send the data.
- return {
- seconds: JSON.stringify(this.seconds),
- secondNums: JSON.stringify(this.secondNums)
- };
- },
-
- deserializeData: function(packet) {
- return {
- seconds: this.smartParse(packet.seconds),
- secondNums: this.smartParse(packet.secondNums)
- };
- }
- });
-
- return AudioDataPacket;
-});
\ No newline at end of file
diff --git a/js/app/models/player.js b/js/app/models/player.js
deleted file mode 100644
index 8e28402..0000000
--- a/js/app/models/player.js
+++ /dev/null
@@ -1,92 +0,0 @@
-define(['app/options', 'bean', 'underscore'], function (Options, Bean, _) {
-
- var PlayerModel = {
-
- audio: new Audio(),
- audioLoaded: false,
-
- playbackRate: 1,
-
- DurationTimer: 0,
-
- init: function() {
- Bean.on(window, 'loadAndPlay', _.bind(this.loadAndPlay, this));
- Bean.on(window, 'next', _.bind(this.nextSong, this));
- Bean.on(window, 'playerModel.playPause', this.togglePlayPause, this);
- Bean.on(window, 'playerModel.volumeChange', _.bind(this.setVolume, this));
- Bean.on(window, 'chromecastConnected', this.onChromecastConnected.bind(this));
- Bean.on(window, 'player.trackInfo', _.bind(this.onNewTrackInfo, this));
- },
-
- loadAndPlay: function() {
- if (!this.audioLoaded) {
- dancer.load(this.audio);
- this.audioLoaded = true;
- }
-
- dancer.play();
- },
-
- togglePlayPause: function() {
- if (dancer.isPlaying()) {
- dancer.pause();
- } else {
- dancer.play();
- }
- },
-
- nextSong: function() {
- // todo: fix error for "Failed to execute 'createMediaElementSource' on 'AudioContext'", might be a Chrome bug;
- dancer.pause();
-
- Bean.fire(window, 'queue.requestNextSong');
-
- },
-
- onNewTrackInfo: function(trackInfo) {
- if (this.chromecastConnected) {
- this.setVolume(Options.chromecastVolume);
- this.playbackRate = Options.chromecastPlaybackRate;
- }
-
- Bean.fire(window, 'view.resetDuration');
-
- clearInterval(this.DurationTimeout);
-
- this.DurationTimeout = setInterval(_.bind(function() {
- if (this.audio.duration) {
- var totalDuration = Math.floor(this.audio.duration);
- var currentDuration = this.audio.currentTime;
- var percentComplete = currentDuration/totalDuration || 0;
- var precision = 100;
- var percentLeft = Math.floor((1 - percentComplete)*100 * precision) / precision;
-
-
- Bean.fire(window, 'view.durationProgress', percentLeft + '%');
- }
- }, this) , (1000 / 60) * this.playbackRate);
-
- Bean.fire(window, 'view.metadata', [[trackInfo.artist, trackInfo.title, trackInfo.artistUrl, trackInfo.titleUrl]]);
-
- this.audio.src = trackInfo.streamUrl;
- this.audio.playbackRate = this.playbackRate;
-
- Bean.off(this.audio, 'ended');
- Bean.on(this.audio, 'ended', _.bind(this.nextSong, this));
-
- Bean.fire(window, 'loadAndPlay');
- },
-
- setVolume: function(volume) {
- this.audio.volume = volume;
- Bean.fire(window, 'visualizer.setVolume', volume);
- },
-
- onChromecastConnected: function() {
- this.chromecastConnected = true;
- }
- };
-
- return PlayerModel;
-
-});
\ No newline at end of file
diff --git a/js/app/options.js b/js/app/options.js
deleted file mode 100644
index cb5540a..0000000
--- a/js/app/options.js
+++ /dev/null
@@ -1,19 +0,0 @@
-define([], function() {
-
- var Options = {
- debug: true,
- debugVolume: 0.01,
-
- defaultVolume: 0.25,
- autoplayRandom: true,
- hideVis: false,
- fadeUI: true,
- loadFromSC: true,
- chromecastAppID: '80CEE4EA',
- chromecastNamespace: 'urn:x-cast:css.visualizer',
- chromecastPlaybackRate: 4,
- chromecastVolume: 0.00001
- };
-
- return Options;
-});
diff --git a/js/app/utils.js b/js/app/utils.js
deleted file mode 100644
index eb82afd..0000000
--- a/js/app/utils.js
+++ /dev/null
@@ -1,238 +0,0 @@
-function randomColor() {
- var color1 = Math.floor(Math.random()*255),
- color2 = Math.floor(Math.random()*255),
- color3 = Math.floor(Math.random()*255),
- colorStr = 'rgb(' + color1 + ',' + color2 + ',' + color3 + ')';
-
- return colorStr;
-}
-
-function pad(num, totalChars) {
- var pad = '0';
- num = num + '';
- while (num.length < totalChars) {
- num = pad + num;
- }
- return num;
-};
-
-function changeColor(color, ratio, darker) { // Ratio is between 0 and 1
- // Trim trailing/leading whitespace
- color = color.replace(/^\s*|\s*$/, '');
-
- // Expand three-digit hex
- color = color.replace(
- /^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i,
- '#$1$1$2$2$3$3'
- );
-
- // Calculate ratio
- var difference = Math.round(ratio * 256) * (darker ? -1 : 1),
- // Determine if input is RGB(A)
- rgb = color.match(new RegExp('^rgba?\\(\\s*' +
- '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
- '\\s*,\\s*' +
- '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
- '\\s*,\\s*' +
- '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
- '(?:\\s*,\\s*' +
- '(0|1|0?\\.\\d+))?' +
- '\\s*\\)$'
- , 'i')),
- alpha = !!rgb && rgb[4] != null ? rgb[4] : null,
-
- // Convert hex to decimal
- decimal = !!rgb? [rgb[1], rgb[2], rgb[3]] : color.replace(
- /^#?([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])/i,
- function() {
- return parseInt(arguments[1], 16) + ',' +
- parseInt(arguments[2], 16) + ',' +
- parseInt(arguments[3], 16);
- }
- ).split(/,/),
- returnValue;
-
- // Return RGB(A)
- return !!rgb ?
- 'rgb' + (alpha !== null ? 'a' : '') + '(' +
- Math[darker ? 'max' : 'min'](
- parseInt(decimal[0], 10) + difference, darker ? 0 : 255
- ) + ', ' +
- Math[darker ? 'max' : 'min'](
- parseInt(decimal[1], 10) + difference, darker ? 0 : 255
- ) + ', ' +
- Math[darker ? 'max' : 'min'](
- parseInt(decimal[2], 10) + difference, darker ? 0 : 255
- ) +
- (alpha !== null ? ', ' + alpha : '') +
- ')' :
- // Return hex
- [
- '#',
- pad(Math[darker ? 'max' : 'min'](
- parseInt(decimal[0], 10) + difference, darker ? 0 : 255
- ).toString(16), 2),
- pad(Math[darker ? 'max' : 'min'](
- parseInt(decimal[1], 10) + difference, darker ? 0 : 255
- ).toString(16), 2),
- pad(Math[darker ? 'max' : 'min'](
- parseInt(decimal[2], 10) + difference, darker ? 0 : 255
- ).toString(16), 2)
- ].join('');
-};
-
-function lighterColor(color, ratio) {
- return changeColor(color, ratio, false);
-};
-
-function darkerColor(color, ratio) {
- return changeColor(color, ratio, true);
-};
-
-function fadeToColor(rgbColor1, rgbColor2, ratio) {
- var colors1 = getNumsFromRGB(rgbColor1),
- colors2 = getNumsFromRGB(rgbColor2),
- newColors = [];
-
- for (var i = 0; i < colors1.length; i++) {
- var color1 = parseInt(colors1[i], 10);
- var color2 = parseInt(colors2[i], 10);
- newColors.push(Math.round(Math.abs(color1 + ((color2 - color1)*ratio))));
- }
-
- function getNumsFromRGB(rgbColor) {
- var colors = rgbColor.split(',');
-
- var colorA = colors[0].substring(4, colors[0].length),
- colorB = colors[1],
- colorC = colors[2].substring(0, colors[2].length - 1);
-
- return [colorA, colorB, colorC];
- }
-
- return 'rgb(' + newColors + ')';
-
-}
-
-function sampleArray(arrayToSample, numOfSamples, modifier, decimalDigits) {
- var arrayMiddle = arrayToSample.length/ 2,
- sampleLength = Math.floor((arrayMiddle) / numOfSamples),
- sampleAvgs = [],
- precision,
- sample;
-
- modifier = modifier || 1;
- decimalDigits = decimalDigits || 10;
-
- precision = Math.pow(10, decimalDigits);
-
- for (var j = 0; j < numOfSamples; j++) {
- sample = 0;
-
- for (var i = 0; i < sampleLength; i++) {
- sample += Math.abs(arrayToSample[(j * sampleLength) + i]);
- sample += Math.abs(arrayToSample[(j * sampleLength) + i + (arrayMiddle)]);
- }
-
- sample /= sampleLength*2;
-
- sampleAvgs.push(Math.round(sample * modifier * precision) / precision);
- }
-
- return sampleAvgs;
-}
-
-function float32ToArray(array) {
- return Array.prototype.slice.call(array);
-}
-
-function toggleFullscreen(el) {
- var isFullscreen;
-
- if (
- document.fullscreenElement ||
- document.webkitFullscreenElement ||
- document.mozFullScreenElement ||
- document.msFullscreenElement
- ) {
- if (document.exitFullscreen) {
- document.exitFullscreen();
- } else if (document.webkitExitFullscreen) {
- document.webkitExitFullscreen();
- } else if (document.mozCancelFullScreen) {
- document.mozCancelFullScreen();
- } else if (document.msExitFullscreen) {
- document.msExitFullscreen();
- }
- isFullscreen = false;
- } else {
- if (el.requestFullscreen) {
- el.requestFullscreen();
- } else if (el.webkitRequestFullscreen) {
- el.webkitRequestFullscreen();
- } else if (el.mozRequestFullScreen) {
- el.mozRequestFullScreen();
- } else if (el.msRequestFullscreen) {
- el.msRequestFullscreen();
- }
- isFullscreen = true;
- }
-
- return isFullscreen;
-}
-
-function getIsFullscreen() {
- return document.fullscreenElement ||
- document.webkitFullscreenElement ||
- document.mozFullScreenElement ||
- document.msFullscreenElement;
-
-}
-
-//Modified from: http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript
-function getLocation(href) {
- var l = document.createElement("a");
- l.href = href;
- return l.hostname;
-}
-
-//Modified from http://stackoverflow.com/questions/13070054/convert-rgb-strings-to-hex-in-javascript 12/30/14
-function rgbToHex(rgb) {
- var rgbRegex = /^rgb\(\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*\)$/;
- var result, r, g, b, hex = "";
- if ( (result = rgbRegex.exec(rgb)) ) {
- r = componentFromStr(result[1], result[2]);
- g = componentFromStr(result[3], result[4]);
- b = componentFromStr(result[5], result[6]);
-
- hex = "#" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);
- }
- return hex;
-
- function componentFromStr(numStr, percent) {
- var num = Math.max(0, parseInt(numStr, 10));
- return percent ?
- Math.floor(255 * Math.min(100, num) / 100) : Math.min(255, num);
- }
-}
-
-//Modified from http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb 12/30/14
-function hexToRgb(hex) {
- // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
- var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
- hex = hex.replace(shorthandRegex, function(m, r, g, b) {
- return r + r + g + g + b + b;
- });
-
- var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
-
- result = [
- parseInt(result[1], 16),
- parseInt(result[2], 16),
- parseInt(result[3], 16)
- ];
-
- var rgbStr = 'rgb(' + result + ')';
-
- return rgbStr;
-}
\ No newline at end of file
diff --git a/js/app/view.js b/js/app/view.js
deleted file mode 100644
index 9043967..0000000
--- a/js/app/view.js
+++ /dev/null
@@ -1,202 +0,0 @@
-define([
- 'app/options',
- 'bean',
- 'app/views/DesktopPlayer',
- 'app/visualizers/bars',
- 'app/visualizers/circles',
- 'app/visualizers/hexagons',
- 'app/visualizers/chromecast'
-], function (
- Options,
- Bean,
- DesktopPlayer,
- bars,
- circles,
- hexagons,
- chromecastVis
- ) {
-
- var View = {
-
- IdleTimer: 0,
-
- visualizers: {
- current: ''
- },
-
- visualizerContainer: document.getElementById('visualizer-container'),
- chooser: document.getElementById('chooser'),
- uiContainer: document.getElementById('ui-container'),
- ui: document.getElementById('ui'),
- searchBtn: document.getElementById('search-btn'),
- searchInput: document.getElementById('search-input'),
- randomColor: document.getElementById('random-color'),
- fullscreen: document.getElementById('fullscreen'),
- colorPickers: [
- document.getElementById('color-picker1'),
- document.getElementById('color-picker2'),
- document.getElementById('color-picker3')
- ],
-
- init: function() {
- DesktopPlayer.init();
-
- var body = document.body;
- Bean.on(this.chooser, 'change', _.bind(this.switchVisualizers, this));
-
- if (Options.loadFromSC) {
- Bean.on(this.searchBtn, 'click', _.bind(this.onSearch, this));
- Bean.on(this.searchInput, 'keyup', _.bind(function(e) {
- if (e.keyCode === 13) {
- this.onSearch();
- }
- }, this));
- }
-
- var toggleUIFunc = _.bind(this.toggleUI, this);
- Bean.on(body, {
- 'click': toggleUIFunc,
- 'mousemove': toggleUIFunc,
- 'keyup': toggleUIFunc
- });
-
-
- Bean.on(window, 'view.resetColors', _.bind(this.resetColors, this));
- Bean.on(window, 'chromecastConnected', _.bind(function(visualizerSettings) {
- if (!this.chromecastConnected) {
- this.chromecastConnected = true;
- this.visualizerSettings = visualizerSettings;
- this.switchVisualizers();
- }
- }, this));
-
- this.visualizers[bars.name] = bars;
- this.visualizers[circles.name] = circles;
- this.visualizers[hexagons.name] = hexagons;
- this.visualizers[chromecastVis.name] = chromecastVis;
-
- this.switchVisualizers();
- this.setupFullscreen();
- this.setupColorEvents();
- this.setupResizeEvent();
- },
-
- setupColorEvents: function() {
- Bean.on(this.randomColor, 'click', _.bind(function() {
- var current = this.visualizers[this.visualizers.current];
- current.resetColors();
- current.setColors();
- }, this));
-
- var onColorChange = _.bind(function(elNum, color) {
- var currentVisualizer = this.visualizers[this.visualizers.current];
- color = hexToRgb(color);
-
- //Break hex color into rgb values.
- currentVisualizer['color' + elNum] = color;
- currentVisualizer.onColorChange();
- }, this);
-
- // Loop through colorpickers and attach change events
- for (var i = 0; i < this.colorPickers.length; i++) {
- var picker = this.colorPickers[i];
-
- Bean.on(picker, 'change', function(ev, index) {
- var el = ev.currentTarget;
- onColorChange(index + 1, el.value);
- }, i);
- }
-
- },
-
- setupResizeEvent: function() {
- var rtime = new Date(1, 1, 2000, 12,00,00);
- var timeout = false;
- var delta = 200;
-
- Bean.on(window, 'resize', _.throttle(function() {
- rtime = new Date();
- if (timeout === false) {
- timeout = true;
- setTimeout(resizeend, delta);
- }
-
- function resizeend() {
- if (new Date() - rtime < delta) {
- setTimeout(resizeend, delta);
- } else {
- timeout = false;
- doneResizing();
- }
- }
-
- function doneResizing () {
- Bean.fire(window, 'visualizer.onResize');
- }
- }, 100));
-
-
- },
-
- setupFullscreen: function() {
- if (
- document.fullscreenEnabled ||
- document.webkitFullscreenEnabled ||
- document.mozFullScreenEnabled ||
- document.msFullscreenEnabled
- ) {
- Bean.on(this.fullscreen, 'click', _.bind(function() {
- toggleFullscreen(document.body);
- var isFullscreen = getIsFullscreen();
- }, this));
- } else {
- this.fullscreen.style.display = 'none';
- }
- },
-
- switchVisualizers: function() {
- var visName = (this.chromecastConnected) ? 'Chromecast' : this.chooser.value;
- var current = this.visualizers.current;
-
- if (current) {
- this.visualizers[current].destroy();
- }
- this.visualizers[visName].chromecastConnected = this.chromecastConnected;
- this.visualizers[visName].visualizerSettings = this.visualizerSettings;
- this.visualizers[visName].run();
- this.visualizers.current = visName;
- },
-
- onSearch: function() {
- Bean.fire(window, 'model.search', this.searchInput.value);
- },
-
- toggleUI: _.throttle(function() {
- this.visualizerContainer.style.cursor = 'auto';
- this.ui.style.opacity = 1;
-
- if (Options.fadeUI) {
- clearInterval(this.IdleTimer);
-
- this.IdleTimer = setInterval(_.bind(function() {
- this.ui.style.opacity = 0;
- this.visualizerContainer.style.cursor = 'none';
- }, this), 2000);
- }
-
- }),
-
- resetColors: function(colors) {
- for (var i = 0; i < colors.length; i++) {
- // Needs to be hexcolor for some reason.
- var color = rgbToHex(colors[i]);
- var picker = this.colorPickers[i];
-
- picker.value = color;
- }
- }
-
- };
-
- return View;
-});
diff --git a/js/app/views/DesktopPlayer.js b/js/app/views/DesktopPlayer.js
deleted file mode 100644
index ad62c53..0000000
--- a/js/app/views/DesktopPlayer.js
+++ /dev/null
@@ -1,40 +0,0 @@
-define([
- 'app/options',
- 'bean',
- 'app/views/Player',
- 'app/controllers/Player'
-], function (
- Options,
- Bean,
- PlayerView,
- PlayerController
- ) {
-
- var DesktopPlayer = _.extend({
-
- volumeSlider: document.getElementById('volume-slider'),
-
- init: function() {
- PlayerController.init();
-
- this.setupBaseEvents();
-
- this.setupVolume();
- },
-
- setupVolume: function() {
- var modifer = 100;
-
- if (Options.debug) {
- this.volumeSlider.value = Options.debugVolume * modifer;
- } else {
- this.volumeSlider.value = Options.defaultVolume * modifer;
- }
-
- Bean.fire(this.volumeSlider, 'change');
- }
-
- }, PlayerView);
-
- return DesktopPlayer;
-});
diff --git a/js/app/views/Player.js b/js/app/views/Player.js
deleted file mode 100644
index 2b9e690..0000000
--- a/js/app/views/Player.js
+++ /dev/null
@@ -1,60 +0,0 @@
-define([
- 'bean'
-], function (
- Bean
- ) {
-
- var Player = {
-
- ui: document.getElementById('ui'),
- duration: document.getElementById('duration'),
- playPause: document.getElementById('play-pause'),
-
- setupBaseEvents: function() {
- Bean.on(window, 'playerView.next', this.onNext);
- Bean.on(window, 'playerView.playPause', _.bind(this.onPlayPause, this));
-
- Bean.on(window, 'view.metadata', _.bind(this.attachMetaData, this));
- Bean.on(window, 'view.resetDuration', _.bind(this.setDuration, this));
- Bean.on(window, 'view.durationProgress', _.bind(this.setDuration, this));
- },
-
- setDuration: function(val) {
- val = val || '100%';
- this.duration.style.right = val;
- },
-
- onNext: function() {
- Bean.fire(window, 'next');
- },
-
- onPlayPause: function(playing) {
- if (playing) {
- this.playPause.style['background-image'] = "url('imgs/glyphicons_173_play.png')";
- } else {
- this.playPause.style['background-image'] = "url('imgs/glyphicons_174_pause.png')";
- }
-
- Bean.fire(window, 'playerModel.playPause');
- },
-
- attachMetaData: function(trackInfo) {
- var artistStr = trackInfo[0] || '';
- var titleStr = trackInfo[1] || '';
- var artistUrl = trackInfo[2] || '';
- var titleUrl = trackInfo[3] || '';
- var artist = document.getElementById('artist');
- var title = document.getElementById('title');
-
- artist.innerText = artistStr;
- title.innerText = titleStr;
- artist.href = artistUrl;
- title.href = titleUrl;
-
- this.ui.style.opacity = 1;
- }
-
- };
-
- return Player;
-});
diff --git a/js/app/visualizers/bars.js b/js/app/visualizers/bars.js
deleted file mode 100644
index 5422bd9..0000000
--- a/js/app/visualizers/bars.js
+++ /dev/null
@@ -1,92 +0,0 @@
-define(['app/visualizers/base', 'underscore', 'bean'], function (Base, _, Bean) {
-
- var Bars = _.extend({
- name: 'Bars',
- numOfBars: 0,
- currentAmp: 0,
- fps: 40,
- barWidth: 24,
- init: function() {
- var styleSheet = document.createElement('style');
-
- this.numOfBars = Math.ceil(window.innerWidth/this.barWidth);
-
- this.setColors(styleSheet);
-
- styleSheet.id = 'visualizer-css';
- document.head.appendChild(styleSheet);
-
- this.setupElements();
-
- Bean.on(window, 'visualizer.onResize', _.bind(this.onResize, this));
- },
-
- setupElements: function() {
- var reflectionOverlay = document.createElement('div');
-
- reflectionOverlay.id = "reflection-overlay";
-
- this.visualizer.innerHTML = '';
- this.visualizer.appendChild(reflectionOverlay);
-
- for (var i = 0; i < this.numOfBars; i++) {
- var bar = document.createElement('div'),
- barWrapper = document.createElement('div');
-
- bar.className = 'bar';
- barWrapper.className = 'bar-wrapper';
- barWrapper.style.left = i*24 + "px";
-
- barWrapper.appendChild(bar);
- this.visualizer.appendChild(barWrapper);
- }
-
- this.bars = document.getElementsByClassName('bar');
- },
-
- setColors: function(styleSheet) {
- styleSheet = styleSheet || document.getElementById('visualizer-css');
- var stylesStr = '';
- var color = this.color1;
-
- for (var i = 0; i < this.numOfBars; i++) {
-
- var startOfSelectorStr = '.bar-wrapper:nth-of-type(' + (i + 2) + ') .bar', // Its '+ 2' because reflectionOverlay is first-child
- beforeStr = startOfSelectorStr + ':before { background-color: ' + lighterColor(color, 0.1) + '; }',
- afterStr = startOfSelectorStr + ':after { background-color: ' + darkerColor(color, 0.1) + '; }',
- barStr = startOfSelectorStr + ' { background-color: ' + darkerColor(color, 0.2) + '; }';
-
- stylesStr += beforeStr + afterStr + barStr;
-
- color = fadeToColor(color, this.color2, 1/this.numOfBars);
- }
-
- styleSheet.innerHTML = stylesStr;
- },
-
- onWaveform: function(waveform) {
- var sampleAvgs = sampleArray(waveform, this.numOfBars, this.volumeModifier);
- var bars = this.bars;
-
- for (var j = 0; j < this.numOfBars; j++) {
- var magnitude = (Math.floor(sampleAvgs[j]*1000)/1000);
- bars[j].parentNode.style[prefix.css + 'transform'] = ["scaleY(", magnitude, ") translate3d(0,0,0)"].join("");
- }
- },
-
- onResize: function() {
- var styleSheet = document.getElementById('visualizer-css');
-
- this.numOfBars = Math.ceil(window.innerWidth/24);
- this.setupElements();
- this.setColors(styleSheet);
- },
-
- onDestroy: function() {
- Bean.off(window, 'visualizer.onResize');
- }
- }, Base);
-
- return Bars;
-
-});
\ No newline at end of file
diff --git a/js/app/visualizers/base.js b/js/app/visualizers/base.js
deleted file mode 100644
index c7aab35..0000000
--- a/js/app/visualizers/base.js
+++ /dev/null
@@ -1,93 +0,0 @@
-define(['app/options', 'bean'], function (Options, Bean) {
- var Base = {
- visualizer: document.getElementById('visualizer'),
- AnimationTimer: '',
-
- color1: '',
- color2: '',
- color3: '',
-
- // Needed to compensate for low volumes
- volumeModifier: 1,
-
- run: function() {
- this.clear();
-
- Bean.on(window, 'visualizer.setVolume', _.bind(this.setVolumeModifier, this));
- Bean.fire(window, 'playerController.announceVolume'); //Needed to set volumeModifer each time visualizer switches
-
- this.resetColors();
- this.resetInputColors();
-
- this.init();
-
- var fps = 60;
- if (this.fps) {
- fps = this.fps;
- }
-
- this.AnimationTimer = setInterval(_.bind(this.getData, this), 50 + (60 - this.fps));
- },
-
- clear: function() {
- var styleSheet = document.getElementById('visualizer-css');
- if (styleSheet) {
- document.head.removeChild(styleSheet);
- }
- this.visualizer.innerHTML = '';
- },
-
- getData: function() {
- if (dancer.isPlaying() && !Options.hideVis) {
- var spectrum, waveform;
-
- this.isPlaying = true;
-
- if (this.onSpectrum) {
- spectrum = float32ToArray(dancer.getSpectrum());
- this.onSpectrum(spectrum);
- }
-
- if (this.onWaveform) {
- waveform = float32ToArray(dancer.getWaveform());
- this.onWaveform(waveform);
- }
- } else {
- this.isPlaying = false;
- }
- },
-
- onColorChange: function() {
- if (this.setColors) {
- this.manualColorSwitch = true;
- this.setColors();
- }
- },
-
- resetColors: function() {
- this.color1 = randomColor();
- this.color2 = randomColor();
- this.color3 = randomColor();
- this.resetInputColors();
- },
-
- resetInputColors: function() {
- Bean.fire(window, 'view.resetColors', [[this.color1, this.color2, this.color3]]);
- },
-
- setVolumeModifier: function(volume) {
- this.volumeModifier = (1 / volume);
- },
-
- destroy: function() {
- clearInterval(this.AnimationTimer);
- Bean.off(window, 'visualizer.setVolume');
-
- if (this.onDestroy) {
- this.onDestroy();
- }
- }
- };
-
- return Base;
-});
\ No newline at end of file
diff --git a/js/app/visualizers/chromecast.js b/js/app/visualizers/chromecast.js
deleted file mode 100644
index 6b5d04a..0000000
--- a/js/app/visualizers/chromecast.js
+++ /dev/null
@@ -1,45 +0,0 @@
-define([
- 'app/visualizers/base',
- 'app/models/player',
- 'app/options',
- 'underscore',
- 'bean'
-], function (
- Base,
- PlayerModel,
- Options,
- _,
- Bean) {
-
- var Chromecast = _.extend({
-
- name: 'Chromecast',
-
- init: function() {
- if (this.chromecastConnected) {
- this.onSocketConnection(this.visualizerSettings);
- } else {
- Bean.on(window, 'chromecastConnected', this.onSocketConnection.bind(this));
- }
- },
-
- onSocketConnection: function(visualizerSettings) {
- this.fps = visualizerSettings.fps * Options.chromecastPlaybackRate;
- this.numOfBars = visualizerSettings.numOfBars;
- },
-
- onWaveform: function(waveform) {
- var sampleAvgs = sampleArray(waveform, this.numOfBars, this.volumeModifier, 3);
- var currentSecond = Math.floor(PlayerModel.audio.currentTime);
-
- Bean.fire(window, 'queue.packFrame', {
- frame: sampleAvgs,
- second: currentSecond
- });
- }
-
- }, Base);
-
- return Chromecast;
-
-});
\ No newline at end of file
diff --git a/js/app/visualizers/circles.js b/js/app/visualizers/circles.js
deleted file mode 100644
index 56bfccd..0000000
--- a/js/app/visualizers/circles.js
+++ /dev/null
@@ -1,67 +0,0 @@
-define(['app/visualizers/base', 'underscore'], function (Base, _) {
-
- var Circles = _.extend({
- name: 'Circles',
- numOfCircles: 0,
- circleDiameter: 50,
- init: function() {
- var styleSheet = document.createElement('style');
- var circleContainer = document.createElement('div');
- circleContainer.id = 'circle-container';
-
- this.numOfCircles = Math.ceil(window.innerHeight / this.circleDiameter);
-
- this.setColors(styleSheet);
-
- for (var i = 0; i < this.numOfCircles; i++) {
- var circle = document.createElement('div');
- var circleWrapper = document.createElement('div');
-
- circle.className = 'circle';
- circleWrapper.className = 'circle-wrapper';
- circleWrapper.appendChild(circle);
- circleContainer.appendChild(circleWrapper);
- }
-
- styleSheet.id = 'visualizer-css';
- this.visualizer.appendChild(circleContainer);
- document.head.appendChild(styleSheet);
-
- this.circles = document.getElementsByClassName('circle');
- },
-
- setColors: function(styleSheet) {
- styleSheet = styleSheet || document.getElementById('visualizer-css');
- var stylesStr = '';
- var color = this.color1;
-
- for (var i = 0; i < this.numOfCircles; i++) {
-
- var startOfSelectorStr = '.circle-wrapper:nth-of-type(' + (i + 1) + ') .circle', // Its '+ 2' because reflectionOverlay is first-child
- diameter = (this.circleDiameter * (this.numOfCircles - i)),
- screenCenter = Math.round(window.innerHeight/2),
- barStr = startOfSelectorStr + ' { background-color: ' + color + '; width: ' + diameter + 'px; height: ' + diameter + 'px;}';
-
- stylesStr += barStr;
-
- color = fadeToColor(color, this.color2, 1/this.numOfCircles);
- }
-
- styleSheet.innerHTML = stylesStr;
- },
-
- onWaveform: function(waveform) {
- var sampleAvgs = sampleArray(waveform, this.numOfCircles, this.volumeModifier);
- var circles = this.circles;
- var diluter = 2;
- var precision = 10; //Will affect framerate as it becomes more precise
-
- for (var j = 0; j < this.numOfCircles; j++) {
- var rotateDeg = 360 * (Math.floor(sampleAvgs[j]*precision)/precision) / diluter;
- circles[j].style[prefix.css + 'transform'] = ["rotate(", rotateDeg, "deg) translateX(-50%) translateZ(0)"].join("");
- }
- }
- }, Base);
-
- return Circles;
-});
\ No newline at end of file
diff --git a/js/app/visualizers/hexagons.js b/js/app/visualizers/hexagons.js
deleted file mode 100644
index 611d986..0000000
--- a/js/app/visualizers/hexagons.js
+++ /dev/null
@@ -1,126 +0,0 @@
-define(['app/visualizers/base', 'underscore'], function (Base, _) {
-
- var Hexagons = _.extend({
- name: 'Hexagons',
- hexs: [],
- hexWrappers: [],
- numOfHexs: 15,
- hexDefaultTransformStr: 'rotate(0deg)',
- currentOverlay: '',
- fps: 70,
-
- init: function() {
- this.setupElements();
- this.setShading();
- this.setColors();
- this.ColorTimer = setInterval(_.bind(this.setColors, this), 10000);
- },
-
- setupElements: function() {
- var hexContainer = document.createElement('div'),
- overlayContainer = document.createElement('div'),
- colorOverlay = document.createElement('div'),
- gradientOverlay = document.createElement('div');
-
- hexContainer.id = 'hex-container';
- overlayContainer.id = 'overlay-container';
- colorOverlay.id = 'color-overlay';
- gradientOverlay.id = 'gradient-overlay';
- colorOverlay.className = 'overlay';
- gradientOverlay.className = 'overlay';
-
- overlayContainer.appendChild(gradientOverlay);
- overlayContainer.appendChild(colorOverlay);
-
- this.visualizer.appendChild(overlayContainer);
- this.visualizer.appendChild(hexContainer);
-
- for (var i = 0; i < this.numOfHexs; i++) {
- var hexWrapper = document.createElement('div'),
- hex = document.createElement('div');
-
- hexWrapper.appendChild(hex);
- hex.style[prefix.css + 'transform'] = this.hexDefaultTransformStr;
-
- hexWrapper.className += ' hex-wrapper';
- hex.className += ' hex';
-
- hexContainer.appendChild(hexWrapper);
- }
-
- this.colorOverlay = colorOverlay;
- this.gradientOverlay = gradientOverlay;
-
- this.hexs = document.getElementsByClassName('hex');
- this.hexWrappers = document.getElementsByClassName('hex-wrapper');
- },
-
- setShading: function() {
- var shade = 'rgba(255,255,255,0.08)';
- var styleSheet = document.styleSheets[0];
-
- for (var j = 0; j < this.numOfHexs; j++) {
- var hex = this.hexs[j];
- var beforeStr = '#hex' + j + ':before { border-bottom-color : ' + shade + '}',
- afterStr = '#hex' + j + ':after { border-top-color : ' + shade + '}';
-
- hex.id = 'hex' + j;
- hex.style['background-color'] = shade;
- styleSheet.insertRule(beforeStr, 0);
- styleSheet.insertRule(afterStr, 0);
-
- }
- },
-
- setColors: function() {
- // todo: Add cross-browser support for opacity and gradients
-
- if (this.manualColorSwitch) {
- clearInterval(this.ColorTimer);
- this.currentOverlay = 'color'; //Set to color so that the a gradient is shown
- } else {
- this.color1 = randomColor();
- this.color2 = randomColor();
- this.color3 = randomColor();
- }
-
- var gradientStr = prefix.css + "linear-gradient(-30deg, " + this.color1 + " 0%," + this.color2 + " 50%," + this.color3 + " 100%)";
-
- switch (this.currentOverlay) {
- case 'gradient':
- this.colorOverlay.style['background'] = this.color1;
- this.colorOverlay.style.opacity = 1;
- this.gradientOverlay.style.opacity = 0;
- this.currentOverlay = 'color';
- break;
- case 'color':
- this.gradientOverlay.style['background'] = gradientStr;
- this.colorOverlay.style.opacity = 0;
- this.gradientOverlay.style.opacity = 1;
- this.currentOverlay = 'gradient';
- break;
- default:
- this.colorOverlay.style.opacity = 0;
- this.gradientOverlay.style['background'] = gradientStr;
- this.currentOverlay = 'gradient';
- }
-
- this.resetInputColors();
- },
-
- onSpectrum: function(spectrum) {
- var sampleAvgs = sampleArray(spectrum, this.numOfHexs, this.volumeModifier);
-
- for (var i = 0; i < this.numOfHexs; i++) {
- this.hexWrappers[i].style[prefix.css + 'transform'] = this.hexDefaultTransformStr + ' scale(' + (sampleAvgs[i]*100 + 1) + ')';
- }
- },
-
- onDestroy: function() {
- clearInterval(this.ColorTimer);
- }
-
- }, Base);
-
- return Hexagons;
-});
\ No newline at end of file
diff --git a/js/libs/backbone.js b/js/libs/backbone.js
deleted file mode 100644
index 206b000..0000000
--- a/js/libs/backbone.js
+++ /dev/null
@@ -1,1608 +0,0 @@
-// Backbone.js 1.1.2
-
-// (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
-// Backbone may be freely distributed under the MIT license.
-// For all details and documentation:
-// http://backbonejs.org
-
-(function(root, factory) {
-
- // Set up Backbone appropriately for the environment. Start with AMD.
- if (typeof define === 'function' && define.amd) {
- define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
- // Export global even in AMD case in case this script is loaded with
- // others that may still expect a global Backbone.
- root.Backbone = factory(root, exports, _, $);
- });
-
- // Next for Node.js or CommonJS. jQuery may not be needed as a module.
- } else if (typeof exports !== 'undefined') {
- var _ = require('underscore');
- factory(root, exports, _);
-
- // Finally, as a browser global.
- } else {
- root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
- }
-
-}(this, function(root, Backbone, _, $) {
-
- // Initial Setup
- // -------------
-
- // Save the previous value of the `Backbone` variable, so that it can be
- // restored later on, if `noConflict` is used.
- var previousBackbone = root.Backbone;
-
- // Create local references to array methods we'll want to use later.
- var array = [];
- var push = array.push;
- var slice = array.slice;
- var splice = array.splice;
-
- // Current version of the library. Keep in sync with `package.json`.
- Backbone.VERSION = '1.1.2';
-
- // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
- // the `$` variable.
- Backbone.$ = $;
-
- // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
- // to its previous owner. Returns a reference to this Backbone object.
- Backbone.noConflict = function() {
- root.Backbone = previousBackbone;
- return this;
- };
-
- // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
- // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
- // set a `X-Http-Method-Override` header.
- Backbone.emulateHTTP = false;
-
- // Turn on `emulateJSON` to support legacy servers that can't deal with direct
- // `application/json` requests ... will encode the body as
- // `application/x-www-form-urlencoded` instead and will send the model in a
- // form param named `model`.
- Backbone.emulateJSON = false;
-
- // Backbone.Events
- // ---------------
-
- // A module that can be mixed in to *any object* in order to provide it with
- // custom events. You may bind with `on` or remove with `off` callback
- // functions to an event; `trigger`-ing an event fires all callbacks in
- // succession.
- //
- // var object = {};
- // _.extend(object, Backbone.Events);
- // object.on('expand', function(){ alert('expanded'); });
- // object.trigger('expand');
- //
- var Events = Backbone.Events = {
-
- // Bind an event to a `callback` function. Passing `"all"` will bind
- // the callback to all events fired.
- on: function(name, callback, context) {
- if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
- this._events || (this._events = {});
- var events = this._events[name] || (this._events[name] = []);
- events.push({callback: callback, context: context, ctx: context || this});
- return this;
- },
-
- // Bind an event to only be triggered a single time. After the first time
- // the callback is invoked, it will be removed.
- once: function(name, callback, context) {
- if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
- var self = this;
- var once = _.once(function() {
- self.off(name, once);
- callback.apply(this, arguments);
- });
- once._callback = callback;
- return this.on(name, once, context);
- },
-
- // Remove one or many callbacks. If `context` is null, removes all
- // callbacks with that function. If `callback` is null, removes all
- // callbacks for the event. If `name` is null, removes all bound
- // callbacks for all events.
- off: function(name, callback, context) {
- var retain, ev, events, names, i, l, j, k;
- if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
- if (!name && !callback && !context) {
- this._events = void 0;
- return this;
- }
- names = name ? [name] : _.keys(this._events);
- for (i = 0, l = names.length; i < l; i++) {
- name = names[i];
- if (events = this._events[name]) {
- this._events[name] = retain = [];
- if (callback || context) {
- for (j = 0, k = events.length; j < k; j++) {
- ev = events[j];
- if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
- (context && context !== ev.context)) {
- retain.push(ev);
- }
- }
- }
- if (!retain.length) delete this._events[name];
- }
- }
-
- return this;
- },
-
- // Trigger one or many events, firing all bound callbacks. Callbacks are
- // passed the same arguments as `trigger` is, apart from the event name
- // (unless you're listening on `"all"`, which will cause your callback to
- // receive the true name of the event as the first argument).
- trigger: function(name) {
- if (!this._events) return this;
- var args = slice.call(arguments, 1);
- if (!eventsApi(this, 'trigger', name, args)) return this;
- var events = this._events[name];
- var allEvents = this._events.all;
- if (events) triggerEvents(events, args);
- if (allEvents) triggerEvents(allEvents, arguments);
- return this;
- },
-
- // Tell this object to stop listening to either specific events ... or
- // to every object it's currently listening to.
- stopListening: function(obj, name, callback) {
- var listeningTo = this._listeningTo;
- if (!listeningTo) return this;
- var remove = !name && !callback;
- if (!callback && typeof name === 'object') callback = this;
- if (obj) (listeningTo = {})[obj._listenId] = obj;
- for (var id in listeningTo) {
- obj = listeningTo[id];
- obj.off(name, callback, this);
- if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
- }
- return this;
- }
-
- };
-
- // Regular expression used to split event strings.
- var eventSplitter = /\s+/;
-
- // Implement fancy features of the Events API such as multiple event
- // names `"change blur"` and jQuery-style event maps `{change: action}`
- // in terms of the existing API.
- var eventsApi = function(obj, action, name, rest) {
- if (!name) return true;
-
- // Handle event maps.
- if (typeof name === 'object') {
- for (var key in name) {
- obj[action].apply(obj, [key, name[key]].concat(rest));
- }
- return false;
- }
-
- // Handle space separated event names.
- if (eventSplitter.test(name)) {
- var names = name.split(eventSplitter);
- for (var i = 0, l = names.length; i < l; i++) {
- obj[action].apply(obj, [names[i]].concat(rest));
- }
- return false;
- }
-
- return true;
- };
-
- // A difficult-to-believe, but optimized internal dispatch function for
- // triggering events. Tries to keep the usual cases speedy (most internal
- // Backbone events have 3 arguments).
- var triggerEvents = function(events, args) {
- var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
- switch (args.length) {
- case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
- case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
- case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
- case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
- default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
- }
- };
-
- var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
-
- // Inversion-of-control versions of `on` and `once`. Tell *this* object to
- // listen to an event in another object ... keeping track of what it's
- // listening to.
- _.each(listenMethods, function(implementation, method) {
- Events[method] = function(obj, name, callback) {
- var listeningTo = this._listeningTo || (this._listeningTo = {});
- var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
- listeningTo[id] = obj;
- if (!callback && typeof name === 'object') callback = this;
- obj[implementation](name, callback, this);
- return this;
- };
- });
-
- // Aliases for backwards compatibility.
- Events.bind = Events.on;
- Events.unbind = Events.off;
-
- // Allow the `Backbone` object to serve as a global event bus, for folks who
- // want global "pubsub" in a convenient place.
- _.extend(Backbone, Events);
-
- // Backbone.Model
- // --------------
-
- // Backbone **Models** are the basic data object in the framework --
- // frequently representing a row in a table in a database on your server.
- // A discrete chunk of data and a bunch of useful, related methods for
- // performing computations and transformations on that data.
-
- // Create a new model with the specified attributes. A client id (`cid`)
- // is automatically generated and assigned for you.
- var Model = Backbone.Model = function(attributes, options) {
- var attrs = attributes || {};
- options || (options = {});
- this.cid = _.uniqueId('c');
- this.attributes = {};
- if (options.collection) this.collection = options.collection;
- if (options.parse) attrs = this.parse(attrs, options) || {};
- attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
- this.set(attrs, options);
- this.changed = {};
- this.initialize.apply(this, arguments);
- };
-
- // Attach all inheritable methods to the Model prototype.
- _.extend(Model.prototype, Events, {
-
- // A hash of attributes whose current and previous value differ.
- changed: null,
-
- // The value returned during the last failed validation.
- validationError: null,
-
- // The default name for the JSON `id` attribute is `"id"`. MongoDB and
- // CouchDB users may want to set this to `"_id"`.
- idAttribute: 'id',
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // Return a copy of the model's `attributes` object.
- toJSON: function(options) {
- return _.clone(this.attributes);
- },
-
- // Proxy `Backbone.sync` by default -- but override this if you need
- // custom syncing semantics for *this* particular model.
- sync: function() {
- return Backbone.sync.apply(this, arguments);
- },
-
- // Get the value of an attribute.
- get: function(attr) {
- return this.attributes[attr];
- },
-
- // Get the HTML-escaped value of an attribute.
- escape: function(attr) {
- return _.escape(this.get(attr));
- },
-
- // Returns `true` if the attribute contains a value that is not null
- // or undefined.
- has: function(attr) {
- return this.get(attr) != null;
- },
-
- // Set a hash of model attributes on the object, firing `"change"`. This is
- // the core primitive operation of a model, updating the data and notifying
- // anyone who needs to know about the change in state. The heart of the beast.
- set: function(key, val, options) {
- var attr, attrs, unset, changes, silent, changing, prev, current;
- if (key == null) return this;
-
- // Handle both `"key", value` and `{key: value}` -style arguments.
- if (typeof key === 'object') {
- attrs = key;
- options = val;
- } else {
- (attrs = {})[key] = val;
- }
-
- options || (options = {});
-
- // Run validation.
- if (!this._validate(attrs, options)) return false;
-
- // Extract attributes and options.
- unset = options.unset;
- silent = options.silent;
- changes = [];
- changing = this._changing;
- this._changing = true;
-
- if (!changing) {
- this._previousAttributes = _.clone(this.attributes);
- this.changed = {};
- }
- current = this.attributes, prev = this._previousAttributes;
-
- // Check for changes of `id`.
- if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
-
- // For each `set` attribute, update or delete the current value.
- for (attr in attrs) {
- val = attrs[attr];
- if (!_.isEqual(current[attr], val)) changes.push(attr);
- if (!_.isEqual(prev[attr], val)) {
- this.changed[attr] = val;
- } else {
- delete this.changed[attr];
- }
- unset ? delete current[attr] : current[attr] = val;
- }
-
- // Trigger all relevant attribute changes.
- if (!silent) {
- if (changes.length) this._pending = options;
- for (var i = 0, l = changes.length; i < l; i++) {
- this.trigger('change:' + changes[i], this, current[changes[i]], options);
- }
- }
-
- // You might be wondering why there's a `while` loop here. Changes can
- // be recursively nested within `"change"` events.
- if (changing) return this;
- if (!silent) {
- while (this._pending) {
- options = this._pending;
- this._pending = false;
- this.trigger('change', this, options);
- }
- }
- this._pending = false;
- this._changing = false;
- return this;
- },
-
- // Remove an attribute from the model, firing `"change"`. `unset` is a noop
- // if the attribute doesn't exist.
- unset: function(attr, options) {
- return this.set(attr, void 0, _.extend({}, options, {unset: true}));
- },
-
- // Clear all attributes on the model, firing `"change"`.
- clear: function(options) {
- var attrs = {};
- for (var key in this.attributes) attrs[key] = void 0;
- return this.set(attrs, _.extend({}, options, {unset: true}));
- },
-
- // Determine if the model has changed since the last `"change"` event.
- // If you specify an attribute name, determine if that attribute has changed.
- hasChanged: function(attr) {
- if (attr == null) return !_.isEmpty(this.changed);
- return _.has(this.changed, attr);
- },
-
- // Return an object containing all the attributes that have changed, or
- // false if there are no changed attributes. Useful for determining what
- // parts of a view need to be updated and/or what attributes need to be
- // persisted to the server. Unset attributes will be set to undefined.
- // You can also pass an attributes object to diff against the model,
- // determining if there *would be* a change.
- changedAttributes: function(diff) {
- if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
- var val, changed = false;
- var old = this._changing ? this._previousAttributes : this.attributes;
- for (var attr in diff) {
- if (_.isEqual(old[attr], (val = diff[attr]))) continue;
- (changed || (changed = {}))[attr] = val;
- }
- return changed;
- },
-
- // Get the previous value of an attribute, recorded at the time the last
- // `"change"` event was fired.
- previous: function(attr) {
- if (attr == null || !this._previousAttributes) return null;
- return this._previousAttributes[attr];
- },
-
- // Get all of the attributes of the model at the time of the previous
- // `"change"` event.
- previousAttributes: function() {
- return _.clone(this._previousAttributes);
- },
-
- // Fetch the model from the server. If the server's representation of the
- // model differs from its current attributes, they will be overridden,
- // triggering a `"change"` event.
- fetch: function(options) {
- options = options ? _.clone(options) : {};
- if (options.parse === void 0) options.parse = true;
- var model = this;
- var success = options.success;
- options.success = function(resp) {
- if (!model.set(model.parse(resp, options), options)) return false;
- if (success) success(model, resp, options);
- model.trigger('sync', model, resp, options);
- };
- wrapError(this, options);
- return this.sync('read', this, options);
- },
-
- // Set a hash of model attributes, and sync the model to the server.
- // If the server returns an attributes hash that differs, the model's
- // state will be `set` again.
- save: function(key, val, options) {
- var attrs, method, xhr, attributes = this.attributes;
-
- // Handle both `"key", value` and `{key: value}` -style arguments.
- if (key == null || typeof key === 'object') {
- attrs = key;
- options = val;
- } else {
- (attrs = {})[key] = val;
- }
-
- options = _.extend({validate: true}, options);
-
- // If we're not waiting and attributes exist, save acts as
- // `set(attr).save(null, opts)` with validation. Otherwise, check if
- // the model will be valid when the attributes, if any, are set.
- if (attrs && !options.wait) {
- if (!this.set(attrs, options)) return false;
- } else {
- if (!this._validate(attrs, options)) return false;
- }
-
- // Set temporary attributes if `{wait: true}`.
- if (attrs && options.wait) {
- this.attributes = _.extend({}, attributes, attrs);
- }
-
- // After a successful server-side save, the client is (optionally)
- // updated with the server-side state.
- if (options.parse === void 0) options.parse = true;
- var model = this;
- var success = options.success;
- options.success = function(resp) {
- // Ensure attributes are restored during synchronous saves.
- model.attributes = attributes;
- var serverAttrs = model.parse(resp, options);
- if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
- if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
- return false;
- }
- if (success) success(model, resp, options);
- model.trigger('sync', model, resp, options);
- };
- wrapError(this, options);
-
- method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
- if (method === 'patch') options.attrs = attrs;
- xhr = this.sync(method, this, options);
-
- // Restore attributes.
- if (attrs && options.wait) this.attributes = attributes;
-
- return xhr;
- },
-
- // Destroy this model on the server if it was already persisted.
- // Optimistically removes the model from its collection, if it has one.
- // If `wait: true` is passed, waits for the server to respond before removal.
- destroy: function(options) {
- options = options ? _.clone(options) : {};
- var model = this;
- var success = options.success;
-
- var destroy = function() {
- model.trigger('destroy', model, model.collection, options);
- };
-
- options.success = function(resp) {
- if (options.wait || model.isNew()) destroy();
- if (success) success(model, resp, options);
- if (!model.isNew()) model.trigger('sync', model, resp, options);
- };
-
- if (this.isNew()) {
- options.success();
- return false;
- }
- wrapError(this, options);
-
- var xhr = this.sync('delete', this, options);
- if (!options.wait) destroy();
- return xhr;
- },
-
- // Default URL for the model's representation on the server -- if you're
- // using Backbone's restful methods, override this to change the endpoint
- // that will be called.
- url: function() {
- var base =
- _.result(this, 'urlRoot') ||
- _.result(this.collection, 'url') ||
- urlError();
- if (this.isNew()) return base;
- return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
- },
-
- // **parse** converts a response into the hash of attributes to be `set` on
- // the model. The default implementation is just to pass the response along.
- parse: function(resp, options) {
- return resp;
- },
-
- // Create a new model with identical attributes to this one.
- clone: function() {
- return new this.constructor(this.attributes);
- },
-
- // A model is new if it has never been saved to the server, and lacks an id.
- isNew: function() {
- return !this.has(this.idAttribute);
- },
-
- // Check if the model is currently in a valid state.
- isValid: function(options) {
- return this._validate({}, _.extend(options || {}, { validate: true }));
- },
-
- // Run validation against the next complete set of model attributes,
- // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
- _validate: function(attrs, options) {
- if (!options.validate || !this.validate) return true;
- attrs = _.extend({}, this.attributes, attrs);
- var error = this.validationError = this.validate(attrs, options) || null;
- if (!error) return true;
- this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
- return false;
- }
-
- });
-
- // Underscore methods that we want to implement on the Model.
- var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
-
- // Mix in each Underscore method as a proxy to `Model#attributes`.
- _.each(modelMethods, function(method) {
- Model.prototype[method] = function() {
- var args = slice.call(arguments);
- args.unshift(this.attributes);
- return _[method].apply(_, args);
- };
- });
-
- // Backbone.Collection
- // -------------------
-
- // If models tend to represent a single row of data, a Backbone Collection is
- // more analagous to a table full of data ... or a small slice or page of that
- // table, or a collection of rows that belong together for a particular reason
- // -- all of the messages in this particular folder, all of the documents
- // belonging to this particular author, and so on. Collections maintain
- // indexes of their models, both in order, and for lookup by `id`.
-
- // Create a new **Collection**, perhaps to contain a specific type of `model`.
- // If a `comparator` is specified, the Collection will maintain
- // its models in sort order, as they're added and removed.
- var Collection = Backbone.Collection = function(models, options) {
- options || (options = {});
- if (options.model) this.model = options.model;
- if (options.comparator !== void 0) this.comparator = options.comparator;
- this._reset();
- this.initialize.apply(this, arguments);
- if (models) this.reset(models, _.extend({silent: true}, options));
- };
-
- // Default options for `Collection#set`.
- var setOptions = {add: true, remove: true, merge: true};
- var addOptions = {add: true, remove: false};
-
- // Define the Collection's inheritable methods.
- _.extend(Collection.prototype, Events, {
-
- // The default model for a collection is just a **Backbone.Model**.
- // This should be overridden in most cases.
- model: Model,
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // The JSON representation of a Collection is an array of the
- // models' attributes.
- toJSON: function(options) {
- return this.map(function(model){ return model.toJSON(options); });
- },
-
- // Proxy `Backbone.sync` by default.
- sync: function() {
- return Backbone.sync.apply(this, arguments);
- },
-
- // Add a model, or list of models to the set.
- add: function(models, options) {
- return this.set(models, _.extend({merge: false}, options, addOptions));
- },
-
- // Remove a model, or a list of models from the set.
- remove: function(models, options) {
- var singular = !_.isArray(models);
- models = singular ? [models] : _.clone(models);
- options || (options = {});
- var i, l, index, model;
- for (i = 0, l = models.length; i < l; i++) {
- model = models[i] = this.get(models[i]);
- if (!model) continue;
- delete this._byId[model.id];
- delete this._byId[model.cid];
- index = this.indexOf(model);
- this.models.splice(index, 1);
- this.length--;
- if (!options.silent) {
- options.index = index;
- model.trigger('remove', model, this, options);
- }
- this._removeReference(model, options);
- }
- return singular ? models[0] : models;
- },
-
- // Update a collection by `set`-ing a new list of models, adding new ones,
- // removing models that are no longer present, and merging models that
- // already exist in the collection, as necessary. Similar to **Model#set**,
- // the core operation for updating the data contained by the collection.
- set: function(models, options) {
- options = _.defaults({}, options, setOptions);
- if (options.parse) models = this.parse(models, options);
- var singular = !_.isArray(models);
- models = singular ? (models ? [models] : []) : _.clone(models);
- var i, l, id, model, attrs, existing, sort;
- var at = options.at;
- var targetModel = this.model;
- var sortable = this.comparator && (at == null) && options.sort !== false;
- var sortAttr = _.isString(this.comparator) ? this.comparator : null;
- var toAdd = [], toRemove = [], modelMap = {};
- var add = options.add, merge = options.merge, remove = options.remove;
- var order = !sortable && add && remove ? [] : false;
-
- // Turn bare objects into model references, and prevent invalid models
- // from being added.
- for (i = 0, l = models.length; i < l; i++) {
- attrs = models[i] || {};
- if (attrs instanceof Model) {
- id = model = attrs;
- } else {
- id = attrs[targetModel.prototype.idAttribute || 'id'];
- }
-
- // If a duplicate is found, prevent it from being added and
- // optionally merge it into the existing model.
- if (existing = this.get(id)) {
- if (remove) modelMap[existing.cid] = true;
- if (merge) {
- attrs = attrs === model ? model.attributes : attrs;
- if (options.parse) attrs = existing.parse(attrs, options);
- existing.set(attrs, options);
- if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
- }
- models[i] = existing;
-
- // If this is a new, valid model, push it to the `toAdd` list.
- } else if (add) {
- model = models[i] = this._prepareModel(attrs, options);
- if (!model) continue;
- toAdd.push(model);
- this._addReference(model, options);
- }
-
- // Do not add multiple models with the same `id`.
- model = existing || model;
- if (order && (model.isNew() || !modelMap[model.id])) order.push(model);
- modelMap[model.id] = true;
- }
-
- // Remove nonexistent models if appropriate.
- if (remove) {
- for (i = 0, l = this.length; i < l; ++i) {
- if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
- }
- if (toRemove.length) this.remove(toRemove, options);
- }
-
- // See if sorting is needed, update `length` and splice in new models.
- if (toAdd.length || (order && order.length)) {
- if (sortable) sort = true;
- this.length += toAdd.length;
- if (at != null) {
- for (i = 0, l = toAdd.length; i < l; i++) {
- this.models.splice(at + i, 0, toAdd[i]);
- }
- } else {
- if (order) this.models.length = 0;
- var orderedModels = order || toAdd;
- for (i = 0, l = orderedModels.length; i < l; i++) {
- this.models.push(orderedModels[i]);
- }
- }
- }
-
- // Silently sort the collection if appropriate.
- if (sort) this.sort({silent: true});
-
- // Unless silenced, it's time to fire all appropriate add/sort events.
- if (!options.silent) {
- for (i = 0, l = toAdd.length; i < l; i++) {
- (model = toAdd[i]).trigger('add', model, this, options);
- }
- if (sort || (order && order.length)) this.trigger('sort', this, options);
- }
-
- // Return the added (or merged) model (or models).
- return singular ? models[0] : models;
- },
-
- // When you have more items than you want to add or remove individually,
- // you can reset the entire set with a new list of models, without firing
- // any granular `add` or `remove` events. Fires `reset` when finished.
- // Useful for bulk operations and optimizations.
- reset: function(models, options) {
- options || (options = {});
- for (var i = 0, l = this.models.length; i < l; i++) {
- this._removeReference(this.models[i], options);
- }
- options.previousModels = this.models;
- this._reset();
- models = this.add(models, _.extend({silent: true}, options));
- if (!options.silent) this.trigger('reset', this, options);
- return models;
- },
-
- // Add a model to the end of the collection.
- push: function(model, options) {
- return this.add(model, _.extend({at: this.length}, options));
- },
-
- // Remove a model from the end of the collection.
- pop: function(options) {
- var model = this.at(this.length - 1);
- this.remove(model, options);
- return model;
- },
-
- // Add a model to the beginning of the collection.
- unshift: function(model, options) {
- return this.add(model, _.extend({at: 0}, options));
- },
-
- // Remove a model from the beginning of the collection.
- shift: function(options) {
- var model = this.at(0);
- this.remove(model, options);
- return model;
- },
-
- // Slice out a sub-array of models from the collection.
- slice: function() {
- return slice.apply(this.models, arguments);
- },
-
- // Get a model from the set by id.
- get: function(obj) {
- if (obj == null) return void 0;
- return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid];
- },
-
- // Get the model at the given index.
- at: function(index) {
- return this.models[index];
- },
-
- // Return models with matching attributes. Useful for simple cases of
- // `filter`.
- where: function(attrs, first) {
- if (_.isEmpty(attrs)) return first ? void 0 : [];
- return this[first ? 'find' : 'filter'](function(model) {
- for (var key in attrs) {
- if (attrs[key] !== model.get(key)) return false;
- }
- return true;
- });
- },
-
- // Return the first model with matching attributes. Useful for simple cases
- // of `find`.
- findWhere: function(attrs) {
- return this.where(attrs, true);
- },
-
- // Force the collection to re-sort itself. You don't need to call this under
- // normal circumstances, as the set will maintain sort order as each item
- // is added.
- sort: function(options) {
- if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
- options || (options = {});
-
- // Run sort based on type of `comparator`.
- if (_.isString(this.comparator) || this.comparator.length === 1) {
- this.models = this.sortBy(this.comparator, this);
- } else {
- this.models.sort(_.bind(this.comparator, this));
- }
-
- if (!options.silent) this.trigger('sort', this, options);
- return this;
- },
-
- // Pluck an attribute from each model in the collection.
- pluck: function(attr) {
- return _.invoke(this.models, 'get', attr);
- },
-
- // Fetch the default set of models for this collection, resetting the
- // collection when they arrive. If `reset: true` is passed, the response
- // data will be passed through the `reset` method instead of `set`.
- fetch: function(options) {
- options = options ? _.clone(options) : {};
- if (options.parse === void 0) options.parse = true;
- var success = options.success;
- var collection = this;
- options.success = function(resp) {
- var method = options.reset ? 'reset' : 'set';
- collection[method](resp, options);
- if (success) success(collection, resp, options);
- collection.trigger('sync', collection, resp, options);
- };
- wrapError(this, options);
- return this.sync('read', this, options);
- },
-
- // Create a new instance of a model in this collection. Add the model to the
- // collection immediately, unless `wait: true` is passed, in which case we
- // wait for the server to agree.
- create: function(model, options) {
- options = options ? _.clone(options) : {};
- if (!(model = this._prepareModel(model, options))) return false;
- if (!options.wait) this.add(model, options);
- var collection = this;
- var success = options.success;
- options.success = function(model, resp) {
- if (options.wait) collection.add(model, options);
- if (success) success(model, resp, options);
- };
- model.save(null, options);
- return model;
- },
-
- // **parse** converts a response into a list of models to be added to the
- // collection. The default implementation is just to pass it through.
- parse: function(resp, options) {
- return resp;
- },
-
- // Create a new collection with an identical list of models as this one.
- clone: function() {
- return new this.constructor(this.models);
- },
-
- // Private method to reset all internal state. Called when the collection
- // is first initialized or reset.
- _reset: function() {
- this.length = 0;
- this.models = [];
- this._byId = {};
- },
-
- // Prepare a hash of attributes (or other model) to be added to this
- // collection.
- _prepareModel: function(attrs, options) {
- if (attrs instanceof Model) return attrs;
- options = options ? _.clone(options) : {};
- options.collection = this;
- var model = new this.model(attrs, options);
- if (!model.validationError) return model;
- this.trigger('invalid', this, model.validationError, options);
- return false;
- },
-
- // Internal method to create a model's ties to a collection.
- _addReference: function(model, options) {
- this._byId[model.cid] = model;
- if (model.id != null) this._byId[model.id] = model;
- if (!model.collection) model.collection = this;
- model.on('all', this._onModelEvent, this);
- },
-
- // Internal method to sever a model's ties to a collection.
- _removeReference: function(model, options) {
- if (this === model.collection) delete model.collection;
- model.off('all', this._onModelEvent, this);
- },
-
- // Internal method called every time a model in the set fires an event.
- // Sets need to update their indexes when models change ids. All other
- // events simply proxy through. "add" and "remove" events that originate
- // in other collections are ignored.
- _onModelEvent: function(event, model, collection, options) {
- if ((event === 'add' || event === 'remove') && collection !== this) return;
- if (event === 'destroy') this.remove(model, options);
- if (model && event === 'change:' + model.idAttribute) {
- delete this._byId[model.previous(model.idAttribute)];
- if (model.id != null) this._byId[model.id] = model;
- }
- this.trigger.apply(this, arguments);
- }
-
- });
-
- // Underscore methods that we want to implement on the Collection.
- // 90% of the core usefulness of Backbone Collections is actually implemented
- // right here:
- var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
- 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
- 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
- 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
- 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
- 'lastIndexOf', 'isEmpty', 'chain', 'sample'];
-
- // Mix in each Underscore method as a proxy to `Collection#models`.
- _.each(methods, function(method) {
- Collection.prototype[method] = function() {
- var args = slice.call(arguments);
- args.unshift(this.models);
- return _[method].apply(_, args);
- };
- });
-
- // Underscore methods that take a property name as an argument.
- var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
-
- // Use attributes instead of properties.
- _.each(attributeMethods, function(method) {
- Collection.prototype[method] = function(value, context) {
- var iterator = _.isFunction(value) ? value : function(model) {
- return model.get(value);
- };
- return _[method](this.models, iterator, context);
- };
- });
-
- // Backbone.View
- // -------------
-
- // Backbone Views are almost more convention than they are actual code. A View
- // is simply a JavaScript object that represents a logical chunk of UI in the
- // DOM. This might be a single item, an entire list, a sidebar or panel, or
- // even the surrounding frame which wraps your whole app. Defining a chunk of
- // UI as a **View** allows you to define your DOM events declaratively, without
- // having to worry about render order ... and makes it easy for the view to
- // react to specific changes in the state of your models.
-
- // Creating a Backbone.View creates its initial element outside of the DOM,
- // if an existing element is not provided...
- var View = Backbone.View = function(options) {
- this.cid = _.uniqueId('view');
- options || (options = {});
- _.extend(this, _.pick(options, viewOptions));
- this._ensureElement();
- this.initialize.apply(this, arguments);
- this.delegateEvents();
- };
-
- // Cached regex to split keys for `delegate`.
- var delegateEventSplitter = /^(\S+)\s*(.*)$/;
-
- // List of view options to be merged as properties.
- var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
-
- // Set up all inheritable **Backbone.View** properties and methods.
- _.extend(View.prototype, Events, {
-
- // The default `tagName` of a View's element is `"div"`.
- tagName: 'div',
-
- // jQuery delegate for element lookup, scoped to DOM elements within the
- // current view. This should be preferred to global lookups where possible.
- $: function(selector) {
- return this.$el.find(selector);
- },
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // **render** is the core function that your view should override, in order
- // to populate its element (`this.el`), with the appropriate HTML. The
- // convention is for **render** to always return `this`.
- render: function() {
- return this;
- },
-
- // Remove this view by taking the element out of the DOM, and removing any
- // applicable Backbone.Events listeners.
- remove: function() {
- this.$el.remove();
- this.stopListening();
- return this;
- },
-
- // Change the view's element (`this.el` property), including event
- // re-delegation.
- setElement: function(element, delegate) {
- if (this.$el) this.undelegateEvents();
- this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
- this.el = this.$el[0];
- if (delegate !== false) this.delegateEvents();
- return this;
- },
-
- // Set callbacks, where `this.events` is a hash of
- //
- // *{"event selector": "callback"}*
- //
- // {
- // 'mousedown .title': 'edit',
- // 'click .button': 'save',
- // 'click .open': function(e) { ... }
- // }
- //
- // pairs. Callbacks will be bound to the view, with `this` set properly.
- // Uses event delegation for efficiency.
- // Omitting the selector binds the event to `this.el`.
- // This only works for delegate-able events: not `focus`, `blur`, and
- // not `change`, `submit`, and `reset` in Internet Explorer.
- delegateEvents: function(events) {
- if (!(events || (events = _.result(this, 'events')))) return this;
- this.undelegateEvents();
- for (var key in events) {
- var method = events[key];
- if (!_.isFunction(method)) method = this[events[key]];
- if (!method) continue;
-
- var match = key.match(delegateEventSplitter);
- var eventName = match[1], selector = match[2];
- method = _.bind(method, this);
- eventName += '.delegateEvents' + this.cid;
- if (selector === '') {
- this.$el.on(eventName, method);
- } else {
- this.$el.on(eventName, selector, method);
- }
- }
- return this;
- },
-
- // Clears all callbacks previously bound to the view with `delegateEvents`.
- // You usually don't need to use this, but may wish to if you have multiple
- // Backbone views attached to the same DOM element.
- undelegateEvents: function() {
- this.$el.off('.delegateEvents' + this.cid);
- return this;
- },
-
- // Ensure that the View has a DOM element to render into.
- // If `this.el` is a string, pass it through `$()`, take the first
- // matching element, and re-assign it to `el`. Otherwise, create
- // an element from the `id`, `className` and `tagName` properties.
- _ensureElement: function() {
- if (!this.el) {
- var attrs = _.extend({}, _.result(this, 'attributes'));
- if (this.id) attrs.id = _.result(this, 'id');
- if (this.className) attrs['class'] = _.result(this, 'className');
- var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
- this.setElement($el, false);
- } else {
- this.setElement(_.result(this, 'el'), false);
- }
- }
-
- });
-
- // Backbone.sync
- // -------------
-
- // Override this function to change the manner in which Backbone persists
- // models to the server. You will be passed the type of request, and the
- // model in question. By default, makes a RESTful Ajax request
- // to the model's `url()`. Some possible customizations could be:
- //
- // * Use `setTimeout` to batch rapid-fire updates into a single request.
- // * Send up the models as XML instead of JSON.
- // * Persist models via WebSockets instead of Ajax.
- //
- // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
- // as `POST`, with a `_method` parameter containing the true HTTP method,
- // as well as all requests with the body as `application/x-www-form-urlencoded`
- // instead of `application/json` with the model in a param named `model`.
- // Useful when interfacing with server-side languages like **PHP** that make
- // it difficult to read the body of `PUT` requests.
- Backbone.sync = function(method, model, options) {
- var type = methodMap[method];
-
- // Default options, unless specified.
- _.defaults(options || (options = {}), {
- emulateHTTP: Backbone.emulateHTTP,
- emulateJSON: Backbone.emulateJSON
- });
-
- // Default JSON-request options.
- var params = {type: type, dataType: 'json'};
-
- // Ensure that we have a URL.
- if (!options.url) {
- params.url = _.result(model, 'url') || urlError();
- }
-
- // Ensure that we have the appropriate request data.
- if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
- params.contentType = 'application/json';
- params.data = JSON.stringify(options.attrs || model.toJSON(options));
- }
-
- // For older servers, emulate JSON by encoding the request into an HTML-form.
- if (options.emulateJSON) {
- params.contentType = 'application/x-www-form-urlencoded';
- params.data = params.data ? {model: params.data} : {};
- }
-
- // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
- // And an `X-HTTP-Method-Override` header.
- if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
- params.type = 'POST';
- if (options.emulateJSON) params.data._method = type;
- var beforeSend = options.beforeSend;
- options.beforeSend = function(xhr) {
- xhr.setRequestHeader('X-HTTP-Method-Override', type);
- if (beforeSend) return beforeSend.apply(this, arguments);
- };
- }
-
- // Don't process data on a non-GET request.
- if (params.type !== 'GET' && !options.emulateJSON) {
- params.processData = false;
- }
-
- // If we're sending a `PATCH` request, and we're in an old Internet Explorer
- // that still has ActiveX enabled by default, override jQuery to use that
- // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
- if (params.type === 'PATCH' && noXhrPatch) {
- params.xhr = function() {
- return new ActiveXObject("Microsoft.XMLHTTP");
- };
- }
-
- // Make the request, allowing the user to override any Ajax options.
- var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
- model.trigger('request', model, xhr, options);
- return xhr;
- };
-
- var noXhrPatch =
- typeof window !== 'undefined' && !!window.ActiveXObject &&
- !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
-
- // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
- var methodMap = {
- 'create': 'POST',
- 'update': 'PUT',
- 'patch': 'PATCH',
- 'delete': 'DELETE',
- 'read': 'GET'
- };
-
- // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
- // Override this if you'd like to use a different library.
- Backbone.ajax = function() {
- return Backbone.$.ajax.apply(Backbone.$, arguments);
- };
-
- // Backbone.Router
- // ---------------
-
- // Routers map faux-URLs to actions, and fire events when routes are
- // matched. Creating a new one sets its `routes` hash, if not set statically.
- var Router = Backbone.Router = function(options) {
- options || (options = {});
- if (options.routes) this.routes = options.routes;
- this._bindRoutes();
- this.initialize.apply(this, arguments);
- };
-
- // Cached regular expressions for matching named param parts and splatted
- // parts of route strings.
- var optionalParam = /\((.*?)\)/g;
- var namedParam = /(\(\?)?:\w+/g;
- var splatParam = /\*\w+/g;
- var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
-
- // Set up all inheritable **Backbone.Router** properties and methods.
- _.extend(Router.prototype, Events, {
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // Manually bind a single named route to a callback. For example:
- //
- // this.route('search/:query/p:num', 'search', function(query, num) {
- // ...
- // });
- //
- route: function(route, name, callback) {
- if (!_.isRegExp(route)) route = this._routeToRegExp(route);
- if (_.isFunction(name)) {
- callback = name;
- name = '';
- }
- if (!callback) callback = this[name];
- var router = this;
- Backbone.history.route(route, function(fragment) {
- var args = router._extractParameters(route, fragment);
- router.execute(callback, args);
- router.trigger.apply(router, ['route:' + name].concat(args));
- router.trigger('route', name, args);
- Backbone.history.trigger('route', router, name, args);
- });
- return this;
- },
-
- // Execute a route handler with the provided parameters. This is an
- // excellent place to do pre-route setup or post-route cleanup.
- execute: function(callback, args) {
- if (callback) callback.apply(this, args);
- },
-
- // Simple proxy to `Backbone.history` to save a fragment into the history.
- navigate: function(fragment, options) {
- Backbone.history.navigate(fragment, options);
- return this;
- },
-
- // Bind all defined routes to `Backbone.history`. We have to reverse the
- // order of the routes here to support behavior where the most general
- // routes can be defined at the bottom of the route map.
- _bindRoutes: function() {
- if (!this.routes) return;
- this.routes = _.result(this, 'routes');
- var route, routes = _.keys(this.routes);
- while ((route = routes.pop()) != null) {
- this.route(route, this.routes[route]);
- }
- },
-
- // Convert a route string into a regular expression, suitable for matching
- // against the current location hash.
- _routeToRegExp: function(route) {
- route = route.replace(escapeRegExp, '\\$&')
- .replace(optionalParam, '(?:$1)?')
- .replace(namedParam, function(match, optional) {
- return optional ? match : '([^/?]+)';
- })
- .replace(splatParam, '([^?]*?)');
- return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
- },
-
- // Given a route, and a URL fragment that it matches, return the array of
- // extracted decoded parameters. Empty or unmatched parameters will be
- // treated as `null` to normalize cross-browser behavior.
- _extractParameters: function(route, fragment) {
- var params = route.exec(fragment).slice(1);
- return _.map(params, function(param, i) {
- // Don't decode the search params.
- if (i === params.length - 1) return param || null;
- return param ? decodeURIComponent(param) : null;
- });
- }
-
- });
-
- // Backbone.History
- // ----------------
-
- // Handles cross-browser history management, based on either
- // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
- // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
- // and URL fragments. If the browser supports neither (old IE, natch),
- // falls back to polling.
- var History = Backbone.History = function() {
- this.handlers = [];
- _.bindAll(this, 'checkUrl');
-
- // Ensure that `History` can be used outside of the browser.
- if (typeof window !== 'undefined') {
- this.location = window.location;
- this.history = window.history;
- }
- };
-
- // Cached regex for stripping a leading hash/slash and trailing space.
- var routeStripper = /^[#\/]|\s+$/g;
-
- // Cached regex for stripping leading and trailing slashes.
- var rootStripper = /^\/+|\/+$/g;
-
- // Cached regex for detecting MSIE.
- var isExplorer = /msie [\w.]+/;
-
- // Cached regex for removing a trailing slash.
- var trailingSlash = /\/$/;
-
- // Cached regex for stripping urls of hash.
- var pathStripper = /#.*$/;
-
- // Has the history handling already been started?
- History.started = false;
-
- // Set up all inheritable **Backbone.History** properties and methods.
- _.extend(History.prototype, Events, {
-
- // The default interval to poll for hash changes, if necessary, is
- // twenty times a second.
- interval: 50,
-
- // Are we at the app root?
- atRoot: function() {
- return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root;
- },
-
- // Gets the true hash value. Cannot use location.hash directly due to bug
- // in Firefox where location.hash will always be decoded.
- getHash: function(window) {
- var match = (window || this).location.href.match(/#(.*)$/);
- return match ? match[1] : '';
- },
-
- // Get the cross-browser normalized URL fragment, either from the URL,
- // the hash, or the override.
- getFragment: function(fragment, forcePushState) {
- if (fragment == null) {
- if (this._hasPushState || !this._wantsHashChange || forcePushState) {
- fragment = decodeURI(this.location.pathname + this.location.search);
- var root = this.root.replace(trailingSlash, '');
- if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
- } else {
- fragment = this.getHash();
- }
- }
- return fragment.replace(routeStripper, '');
- },
-
- // Start the hash change handling, returning `true` if the current URL matches
- // an existing route, and `false` otherwise.
- start: function(options) {
- if (History.started) throw new Error("Backbone.history has already been started");
- History.started = true;
-
- // Figure out the initial configuration. Do we need an iframe?
- // Is pushState desired ... is it available?
- this.options = _.extend({root: '/'}, this.options, options);
- this.root = this.options.root;
- this._wantsHashChange = this.options.hashChange !== false;
- this._wantsPushState = !!this.options.pushState;
- this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
- var fragment = this.getFragment();
- var docMode = document.documentMode;
- var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
-
- // Normalize root to always include a leading and trailing slash.
- this.root = ('/' + this.root + '/').replace(rootStripper, '/');
-
- if (oldIE && this._wantsHashChange) {
- var frame = Backbone.$('