diff --git a/.gitignore b/.gitignore index 5fdf453..2f0104d 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .DS_Store .AppleDouble .LSOverride -Icon # Thumbnails ._* @@ -22,4 +21,10 @@ Desktop.ini $RECYCLE.BIN/ # SublimeText project files -*.sublime-workspace \ No newline at end of file +*.sublime-workspace + +# build script dependencies +node_modules/ + +# production folder +production/ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..beae257 --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Georg Fischer + +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/README.md b/README.md index 522499f..661cd6d 100644 --- a/README.md +++ b/README.md @@ -3,19 +3,50 @@ image glitch experiment this is an experiment for the web browser. it corrupts jpg images so that they appear "glitched". -[![triangulation experiment screen shot](http://dl.dropboxusercontent.com/u/1098704/Screenshots/github-glitch.png)](http://snorpey.github.io/jpg-glitch/) +[![glitch experiment screen shot](images/screenshot.png)](http://snorpey.github.io/jpg-glitch/) [online demo](http://snorpey.github.io/jpg-glitch/) this experiment is very much based on the [smack my glitch up js](https://github.com/Hugosslade/smackmyglitchupjs) script. +glitch effect code +--- +if you're a developer and just interested in the code for the glitch effect, there's a separate repository for that: [glitch-canvas](https://github.com/snorpey/glitch-canvas). + third party code used in this experiment --- -* [html5slider](http://frankyan.com/labs/html5slider/) by [fryn](https://github.com/fryn), MIT license -* [js signals](http://millermedeiros.github.io/js-signals/) by [millermedeiros](https://github.com/millermedeiros), MIT license -* [require js](http://requirejs.org/), by [jrburke](jrburke), BSD & MIT license -* [raf js](https://gist.github.com/paulirish/1579671), by [paulirish](https://github.com/paulirish), MIT license +* [localforage](https://github.com/mozilla/localForage) by [mozilla](https://github.com/mozilla), Apache License 2.0 +* [requirejs](http://requirejs.org/), by [jrburke](jrburke), BSD & MIT license +* [almond](https://github.com/jrburke/almond), by [jrburke](jrburke), BSD & MIT license +* [javascript-md5](https://blueimp.github.io/JavaScript-MD5/), by [blueimp](https://github.com/blueimp), MIT license +* [reqwest](https://github.com/ded/reqwest/), by [ded](https://github.com/ded), MIT license +* [glitch-canvas](https://github.com/snorpey/glitch-canvas/), by [snorpey](https://github.com/snorpey), MIT license +* [material design icons](https://github.com/Templarian/MaterialDesign), by [templarian](https://github.com/templarian), Open Font License 1.1 license --- -[MIT License](http://www.opensource.org/licenses/mit-license.php) \ No newline at end of file +[MIT License](LICENSE) + +development +--- +if you're interested in adding features, fixing bugs the code, or running the tool on your own server, here are some pointers to help you get familar with the code base. + +if you have questions about the code, don't hesitate to open an [issue](issues) or send me an email. + +* ``config.js``: all defaults and settings are in here +* ``glitcher.js`` the main app starting point. all events are hooked up in here. +* the app does not use any big dom libraries or app frameworks (like jquery, angular or react) +* where possible, the app uses webworkers for complex tasks +* all strings that are displayed to the user are located in the ``lang/`` folder. for each language, a different file is created. +* the app uses a serviceworker to make it available offline in [browsers](http://caniuse.com/#feat=serviceworkers) that support it +* the app was built without any preprocessors in mind. using the [build script](#build-script) is entirely optional and not required to get the app to work. + +build script +--- +the build script takes care of concatenating and minifying all scripts and styles. it uses [gruntjs](http://gruntjs.com/). + +please make sure that both [nodejs](http://nodejs.org/) and grunt-cli are [set up properly](http://gruntjs.com/getting-started) on your machine. + +run ```npm install``` from within the ```build/``` folder to install the dependencies of the build script. + +to build, run ```grunt production``` from within the ```build/``` folder. the optimized files will get copied to the ```production/``` folder. diff --git a/build/Gruntfile.js b/build/Gruntfile.js new file mode 100644 index 0000000..5b1566a --- /dev/null +++ b/build/Gruntfile.js @@ -0,0 +1,216 @@ +// http://gruntjs.com/configuring-tasks +module.exports = function( grunt ) { + var grunt_configuration = { + pkg: grunt.file.readJSON( 'package.json' ), + + // concatenate all javascript files in scripts folder and compress them; + // replace requirejs with the more lightweight almond js + requirejs: { + production: { + options: { + name: 'lib/almond', + include: 'glitcher', + baseUrl: '../scripts/', + mainConfigFile: '../scripts/glitcher.js', + out: '../production/glitcher.min.js', + wrap: true + } + } + }, + + // minify css files in styles dir + cssmin: { + production: { + files: { + '../production/glitcher.min.css': [ '../styles/glitcher.css' ] + } + } + }, + + // minify svg files + svgmin: { + production: { + options: { + plugins: [ + { removeViewBox: false } + ] + }, + files: [ { + expand: true, + cwd: '../', + src: 'images/icon/*.svg', + dest: '../production/' + }, { + expand: true, + cwd: '../', + src: 'images/logos/*.svg', + dest: '../production/' + } ] + } + }, + + uglify: { + options: { + compress: { + dead_code: true, + properties: true, + booleans: true, + unused: true, + hoist_funs: true, + hoist_vars: true, + if_return: true, + join_vars: true + }, + mangle: { + sort: true, + toplevel: true + } + }, + production: { + files: [ + { src: '../serviceworker.js', dest: '../production/serviceworker.min.js' }, + { src: '../scripts/workers/glitchworker.js', dest: '../production/glitchworker.min.js' }, + { src: [ + '../scripts/lib/localforage.nopromises.js', + '../scripts/lib/md5.js', + '../scripts/workers/storageworker.js' + ], dest: '../production/storageworker.min.js' }, + { src: [ + '../scripts/lib/localforage.nopromises.js', + '../scripts/workers/settingsworker.js' + ], dest: '../production/settingsworker.min.js' } + ] + } + }, + + // copy the index file + copy: { + productionTextBasedFiles: { + options: { processContent: updateContent }, + files: [ + { src: '../index.html', dest: '../production/index.html' }, + { src: '../manifest.json', dest: '../production/manifest.json' }, + { src: '../.gitignore', dest: '../production/.gitignore' }, + { src: '../LICENSE', dest: '../production/LICENSE' }, + { + expand: true, + cwd: '../', + src: [ 'lang/*.json' ], + dest: '../production/' + }, + + // copying these files 'in place' to apply updateContent function + // that updates some of the paths in the minified files + { src: '../production/glitcher.min.js', dest: '../production/glitcher.min.js' }, + { src: '../production/serviceworker.min.js', dest: '../production/serviceworker.min.js' }, + { src: '../production/storageworker.min.js', dest: '../production/storageworker.min.js' }, + { src: '../production/settingsworker.min.js', dest: '../production/settingsworker.min.js' }, + { src: '../production/glitcher.min.css', dest: '../production/glitcher.min.css' } + ] + }, + productionBinaryFiles: { + files: [ { + expand: true, + cwd: '../', + src: [ 'images/*.jpg' ], + dest: '../production/' + }, { + expand: true, + cwd: '../', + src: [ 'images/logos/*.png' ], + dest: '../production/' + }, + { src: '../favicon.ico', dest: '../production/favicon.ico' } ] + } + }, + + // minify index file in production dir + // including css and javascript + htmlmin: { + production: { + options: { + removeComments: true, + collapseWhitespace: true, + minifyCSS: true, + minifyJS: { + compress: { + dead_code: true, + properties: true, + booleans: true, + unused: true, + hoist_funs: true, + hoist_vars: true, + if_return: true, + join_vars: true + }, + mangle: { + sort: true, + toplevel: true + } + }, + removeScriptTypeAttributes: true + }, + files: [ { + src: '../production/index.html', dest: '../production/index.html' + } ] + } + }, + }; + + // replace javscript and css paths when copying files + function updateContent ( content, path ) { + if ( path === '../index.html' ) { + content = content + .replace( 'styles/glitcher.css', 'glitcher.min.css' ) + .replace( 'scripts/lib/require.js', 'glitcher.min.js' ) + .replace( 'serviceworker.js', 'serviceworker.min.js' ) + .replace( "scriptEl.setAttribute( 'data-main', 'scripts/glitcher.js' );", '' ); + } + + if ( path === '../production/glitcher.min.js' ) { + content = content + .replace( 'scripts/workers/glitchworker.js', 'glitchworker.min.js' ) + .replace( 'scripts/workers/storageworker.js', 'storageworker.min.js' ) + .replace( 'scripts/workers/settingsworker.js', 'settingsworker.min.js' ); + } + + if ( path === '../production/serviceworker.min.js' ) { + content = content + .replace( /v\d+(.?\d*)+::/g, 'b' + Date.now() + '::' ) // 'v1.0.1::'' -> 'b{timestamp}' + .replace( 'styles/glitcher.css', 'glitcher.min.css' ) + .replace( 'scripts/glitcher.js', 'glitcher.min.js' ) + .replace( 'scripts/workers/glitchworker.js', 'glitchworker.min.js' ) + .replace( 'scripts/workers/storageworker.js', 'storageworker.min.js' ) + .replace( 'scripts/workers/settingsworker.js', 'settingsworker.min.js' ); + } + + if ( path === '../production/storageworker.min.js' || '../production/settingsworker.min.js' ) { + content = content.replace( /,importScripts\(.*\),/, ',' ); // replaces importScripts + } + + if ( path === '../production/glitcher.min.css' ) { + content = content.replace( /\.\.\/images\//gi, 'images/' ); // replaces importScripts + } + + if ( path === '../manifest.json' ) { + content = content.replace( 'serviceworker.js', 'serviceworker.min.js' ); + } + + return content; + } + + grunt.initConfig( grunt_configuration ); + grunt.loadNpmTasks( 'grunt-contrib-requirejs' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-copy' ); + grunt.loadNpmTasks( 'grunt-contrib-htmlmin' ); + grunt.loadNpmTasks( 'grunt-svgmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + + grunt.registerTask( 'default', [ 'requirejs', 'cssmin', 'svgmin', 'uglify', 'copy', 'htmlmin' ] ); + grunt.registerTask( 'production', [ 'requirejs', 'cssmin', 'copy' ] ); + grunt.registerTask( 'js', [ 'requirejs', 'uglify', 'copy' ] ); + grunt.registerTask( 'css', [ 'cssmin' ] ); + grunt.registerTask( 'cp', [ 'copy' ] ); + grunt.registerTask( 'html', [ 'copy', 'htmlmin' ] ); +}; \ No newline at end of file diff --git a/build/package.json b/build/package.json new file mode 100644 index 0000000..7e775ec --- /dev/null +++ b/build/package.json @@ -0,0 +1,14 @@ +{ + "name": "distort-grid-build", + "version": "0.0.1", + "devDependencies": { + "grunt": "~0.4.1", + "grunt-contrib-copy": "~0.4.1", + "grunt-contrib-cssmin": "~0.6.1", + "grunt-contrib-htmlmin": "~0.6.0", + "grunt-contrib-imagemin": "~0.3.0", + "grunt-contrib-requirejs": "~0.4.1", + "grunt-contrib-uglify": "^0.11.0", + "grunt-svgmin": "^3.1.0" + } +} diff --git a/images/favicon.ico b/images/favicon.ico new file mode 100644 index 0000000..7225f31 Binary files /dev/null and b/images/favicon.ico differ diff --git a/images/icon/alert-circle.svg b/images/icon/alert-circle.svg new file mode 100644 index 0000000..1d54e2d --- /dev/null +++ b/images/icon/alert-circle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/camera.svg b/images/icon/camera.svg new file mode 100644 index 0000000..30bcd74 --- /dev/null +++ b/images/icon/camera.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/chevron-down-black.svg b/images/icon/chevron-down-black.svg new file mode 100644 index 0000000..16e63b9 --- /dev/null +++ b/images/icon/chevron-down-black.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/chevron-down.svg b/images/icon/chevron-down.svg new file mode 100644 index 0000000..1dd1a43 --- /dev/null +++ b/images/icon/chevron-down.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/content-save.svg b/images/icon/content-save.svg new file mode 100644 index 0000000..57c0571 --- /dev/null +++ b/images/icon/content-save.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/delete.svg b/images/icon/delete.svg new file mode 100644 index 0000000..3a5c014 --- /dev/null +++ b/images/icon/delete.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/emoticon.svg b/images/icon/emoticon.svg new file mode 100644 index 0000000..0f2f976 --- /dev/null +++ b/images/icon/emoticon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/fullscreen-exit.svg b/images/icon/fullscreen-exit.svg new file mode 100644 index 0000000..85e2eaa --- /dev/null +++ b/images/icon/fullscreen-exit.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/fullscreen.svg b/images/icon/fullscreen.svg new file mode 100644 index 0000000..08d4f2c --- /dev/null +++ b/images/icon/fullscreen.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/information-outline.svg b/images/icon/information-outline.svg new file mode 100644 index 0000000..1211ca5 --- /dev/null +++ b/images/icon/information-outline.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/nav.svg b/images/icon/nav.svg new file mode 100644 index 0000000..aa4949c --- /dev/null +++ b/images/icon/nav.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/images/icon/open-in-app.svg b/images/icon/open-in-app.svg new file mode 100644 index 0000000..18b6df7 --- /dev/null +++ b/images/icon/open-in-app.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/settings.svg b/images/icon/settings.svg new file mode 100644 index 0000000..a410767 --- /dev/null +++ b/images/icon/settings.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/icon/share-variant.svg b/images/icon/share-variant.svg new file mode 100644 index 0000000..4e2d263 --- /dev/null +++ b/images/icon/share-variant.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/images/lincoln.jpg b/images/lincoln.jpg new file mode 100644 index 0000000..cc37d1e Binary files /dev/null and b/images/lincoln.jpg differ diff --git a/images/logos/glitch-144x144.png b/images/logos/glitch-144x144.png new file mode 100644 index 0000000..df8a651 Binary files /dev/null and b/images/logos/glitch-144x144.png differ diff --git a/images/logos/glitch-144x144.svg b/images/logos/glitch-144x144.svg new file mode 100644 index 0000000..630b5a7 --- /dev/null +++ b/images/logos/glitch-144x144.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + diff --git a/images/logos/glitch-168x168.png b/images/logos/glitch-168x168.png new file mode 100644 index 0000000..606a03d Binary files /dev/null and b/images/logos/glitch-168x168.png differ diff --git a/images/logos/glitch-168x168.svg b/images/logos/glitch-168x168.svg new file mode 100644 index 0000000..3067c77 --- /dev/null +++ b/images/logos/glitch-168x168.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + diff --git a/images/logos/glitch-192x192.png b/images/logos/glitch-192x192.png new file mode 100644 index 0000000..a93ad0c Binary files /dev/null and b/images/logos/glitch-192x192.png differ diff --git a/images/logos/glitch-192x192.svg b/images/logos/glitch-192x192.svg new file mode 100644 index 0000000..7aaeba9 --- /dev/null +++ b/images/logos/glitch-192x192.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + diff --git a/images/logos/glitch-48x48.png b/images/logos/glitch-48x48.png new file mode 100644 index 0000000..292aaa0 Binary files /dev/null and b/images/logos/glitch-48x48.png differ diff --git a/images/logos/glitch-48x48.svg b/images/logos/glitch-48x48.svg new file mode 100644 index 0000000..50d2235 --- /dev/null +++ b/images/logos/glitch-48x48.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + diff --git a/images/logos/glitch-72x72.png b/images/logos/glitch-72x72.png new file mode 100644 index 0000000..d18870b Binary files /dev/null and b/images/logos/glitch-72x72.png differ diff --git a/images/logos/glitch-72x72.svg b/images/logos/glitch-72x72.svg new file mode 100644 index 0000000..be0e029 --- /dev/null +++ b/images/logos/glitch-72x72.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + diff --git a/images/logos/glitch-96x96.png b/images/logos/glitch-96x96.png new file mode 100644 index 0000000..33c8caa Binary files /dev/null and b/images/logos/glitch-96x96.png differ diff --git a/images/logos/glitch-96x96.svg b/images/logos/glitch-96x96.svg new file mode 100644 index 0000000..baeb325 --- /dev/null +++ b/images/logos/glitch-96x96.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + diff --git a/images/screenshot.png b/images/screenshot.png new file mode 100644 index 0000000..d4004a4 Binary files /dev/null and b/images/screenshot.png differ diff --git a/index.html b/index.html index 3bc1a99..12a0b6a 100644 --- a/index.html +++ b/index.html @@ -2,37 +2,88 @@ - image glitch experiment - + + + + + + + + Image Glitch Tool + + -
-

glitch images

-

drag an image into the browser window to modify it. this script corrupts some bytes in a jpg image. because of the way jpg encoding works, the corripted file still shows something. inspired by soulwires experiment in flash. this experiment was created by georg. you can follow him on twitter or explore the source code on github.

+
+

With this app, you can glitch your own images by dragging an image into the browser window. Use the sliders in the control panel to alter the glitched parameters. The image updates in real time.

+

This app corrupts some bytes in an image. Because of the way JPEG encoding works, the corrupted file still shows a corrupted image. It was inspired by soulwire’s experiment in Flash.

+

This tool was created by Georg. He is always happy to learn about the things that people are creating with his tools. You can follow him on Twitter or explore the source code of this app on GitHub.

+

If you like the glitcher, you can check out some of Georg’s other JavaScript experiments.

+

+ Please note: javascript and modern browsers are required for this app to work. +

-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- - download bitmap file (.png) -
- - + + \ No newline at end of file diff --git a/lang/de-de.json b/lang/de-de.json new file mode 100644 index 0000000..7685117 --- /dev/null +++ b/lang/de-de.json @@ -0,0 +1,134 @@ +{ + "lang": "en-us", + "index": { + "title": "Image Glitch Werkzeug", + "description": "Mit diesem Programm kannst du ein Bild so bearbeiten, dass es kaputt aussieht. Ziehe ein Bild in das Browserfenster um loszulegen.\n\nDas Programm verändert einige Bytes in der Bilddatei. Aufgrund der Art und Weise wie der [JPEG Logarithmus](https://de.wikipedia.org/wiki/JPEG) funktioniert, wird trotz eigenlich unlesbarer Rohdaten weiterhin ein Bild erzeugt. Dieses Programm ist angelehnt an ein ähnliches Experiment von [experiment](http://blog.soulwire.co.uk/laboratory/flash/as3-bitmapdata-glitch-generator) von [soulwire](http://github.com/soulwire) in Flash.\n\nDieses Programm wurde von [Georg](http://snorpey.com/) entwickelt. Er freut sich übrigens immer, von den Nutzern seiner Programme zu hören wie sie die Programme einsetzen. Du kannst Georg bei [Twitter](https://twitter.com/snorpey) folgen oder dir den Quellcode dieses Programms bei [GitHub](https://github.com/snorpey/jpg-glitch) ansehen.\n\nFalls dir dieses Programm gefallen hat, gefallen dir vielleicht auch Georgs andere [Experimente](http://snorpey.github.io/experiments/)." + }, + "settings": { + "settings": "Einstellungen", + "settingstitle": "Ändere die Einstellungen des Programms", + "canzoomwithpointer": "Erlaube Zoomen mit Mausrad und Gesten", + "resizeuploadedimages": "Große Bilder verkleinen, um Fehler zu vermeiden", + "language": "Sprache (Language)", + "languageoptions": { + "de-de": "Deutsch DE", + "en-us": "Englisch (English US)" + }, + "error": { + "save": "Konnte die Einstellungen nicht im Browser speichern.", + "load": "Konnte die Einstellungen nicht vom Browser laden." + } + }, + "about": { + "info": "Über", + "infotitle": "Weitere Informationen über dieses Programm" + }, + "controls": { + "controls": "Regler", + "controlstitle": "Regler ein- und ausblenden", + "randomize": "Zufall", + "randomizetitle": "Zufällige Reglerwerte wählen", + "center": "Mittig", + "centertitle": "Zentriere das Bild auf dem Bildschirm", + "original": "100%", + "originaltitle": "Zoome zur Originalgröße des Bildes", + "zoom": "Zoom", + "amount": "Betrag", + "seed": "Startwert", + "iterations": "Wiederholungen", + "quality": "Qualität", + "fullscreen": "Vollbild", + "fullscreentitle": "Vollbild ein- und ausschalten" + }, + "nav": { + "menu": "Menü", + "menutitle": "Hauptmenü ein- und ausschalten" + }, + "file": { + "open": "Öffnen", + "opentitle": "Eine Datei von deinem Gerät öffnen", + "import": "Importieren", + "importtitle": "Öffne ein Bild von deiner Festplatte", + "recent": "Bilder aus vorherigen Sitzungen", + "norecent": "Noch keine Bilder vorhanden", + "untitled": "Ohne Titel", + "del": "Löschen", + "deltitle": "Dieses Bild aus dem Speicher deines Browsers löschen", + "openimage": "Öffnen", + "openimagetitle": "Dieses Bild laden", + "offline": "Offline nehmen", + "offlinetitle": "Dieses Bild von Imgur löschen und vom Netz nehmen", + "openlink": "Link öffnen", + "openlinktitle": "Das Bild in einen neuen Browsertab öffnen", + "save": "Speichern", + "savetitle": "Aktuelles Bild für spätere Sitzungen speichern", + "download": "Herunterladen", + "downloadtitle": "Lade das bearbeitete Bild auf herunter", + "saveinbrowser": "Speichern", + "saveinbrowsertitle": "Speichere das Bild im Speicher deines Browsers", + "error": { + "load": "Konnte vorherige Sitzung nicht laden.", + "save": "Konnte aktuelle Sitzung nicht speichern.", + "openimage": "Kann das Bild nicht öffnen.", + "openfile": "Kann die Datei nicht öffnen." + }, + "message": { + "before": "Das gleiche Bild wurde vorher schonmal gespeichert.", + "save": "Die Datei wurde in deinem Browser gespeichert.", + "del": "Eine Datei wurde aus dem Speicher deines Browsers gelöscht.", + "resize": "Dein Bild wurde etwas verkleinert, um Programmfehler zu vermeiden." + } + }, + "share": { + "share": "Teilen", + "sharetitle": "Teile das Bild im Internet", + "info": "Du kannst das Bild auf [Imgur](https://imgur.com) hochladen, um es mit anderen zu teilen. Bitte beachte dass das Bild dann öffentlich einsehbar ist und die [Terms of Service](https://imgur.com/tos) von Imgur gelten.", + "openon": "Das Bild auf {$1} öffnen", + "openontitle": "Das Bild öffnen, dass auf {$1} geteilt wurde", + "shareon": "Auf {$1} teilen", + "shareontitle": "Das Bild auf {$1} teilen", + "upload": "Bild auf Imgur Hochladen", + "uploadtitle": "Lade das Bild auf Imgur hoch, um es mit anderen zu teilen", + "uploading": "Lade Bild hoch…", + "imagelink": "Online Link zum Bild", + "imagelinktitle": "Du kannst diesen Link nehmen um das Bild auf anderen Seiten zu teilen oder hochzuladen", + "opennewtabtitle": "Öffne das Bild in einem neuen Browsertab", + "imgur": "Imgur", + "reddit": "Reddit", + "twitter": "Twitter", + "facebook": "Facebook", + "pinterest": "Pinterest", + "recentlyshared": "Kürzlich geteilte Bilder", + "untitled": "Ohne Titel", + "openlink": "Öffne Link", + "openlinktitle": "Das Bild in einen neuen Browsertab öffnen", + "offline": "Offline nehmen", + "offlinetitle": "Dieses Bild von Imgur löschen und vom Netz nehmen", + "error": { + "base64": "Es gibt keine Base64-Adresse zum hochladen", + "upload": "Konnte das Bild nicht auf Imgur hochladen." + }, + "message": { + "upload": "Das Bild wurde zu Imgur hochgeladen. [Bild öffnen.]({$1})", + "del": "Das Bild wurde von Imgur gelöscht." + } + }, + "webcam": { + "webcam": "Webcam", + "webcamtitle": "Mache ein Bild mit deiner Webcam", + "webcamlabel": "Foto", + "trigger": "Ein Foto machen", + "triggertitle": "Klicken, um ein Foto mit deiner Webcam zu machen", + "picture": "Webcam Foto von {$1}", + "error": { + "access": "Der Zugriff auf deine Webcam wurde leider verweigert." + } + }, + "welcome": { + "firstvisit": [ + "Hallo! Es scheint als wärst du zum ersten Mal hier.", + "Um loszulegen, ziehe an den Reglern am unteren Fensterrand um das Bild zu bearbeiten.", + "Du kannst auch ein Bild importieren. Klicke dazu einfach im Menü auf ÖFFNEN." + ] + } +} \ No newline at end of file diff --git a/lang/en-us.json b/lang/en-us.json new file mode 100644 index 0000000..4c5a99b --- /dev/null +++ b/lang/en-us.json @@ -0,0 +1,135 @@ +{ + "lang": "en-us", + "index": { + "title": "Image Glitch Tool", + "description": "With this app, you can glitch your own images by dragging an image into the browser window. Use the sliders in the control panel to alter the glitched parameters. The image updates in real time.\n\nThis app corrupts some bytes in an image. Because of the way [JPEG encoding](https://en.wikipedia.org/wiki/JPEG) works, the corrupted file still shows a corrupted image. It was inspired by [soulwire](http://github.com/soulwire)’s [experiment](http://blog.soulwire.co.uk/laboratory/flash/as3-bitmapdata-glitch-generator) in Flash.\n\nThis tool was created by [Georg](http://snorpey.com/). He is always happy to learn about the things that people are creating with his tools. You can follow him on [Twitter](https://twitter.com/snorpey) or explore the source code of this app on [GitHub](https://github.com/snorpey/jpg-glitch).\n\nIf you like this glitch tool, you can check out some of Georg’s other [JavaScript experiments](http://snorpey.github.io/experiments/)." + }, + "settings": { + "settings": "Settings", + "settingstitle": "Change the tool settings", + "canzoomwithpointer": "Enable zooming with mousewheel and touch gestures", + "language": "Language (Sprache)", + "languageoptions": { + "de-de": "German (Deutsch DE)", + "en-us": "English US" + }, + "resizeuploadedimages": "Resize big images to avoid errors", + "error": { + "save": "Could not save settings to your browser.", + "load": "Could not load previous settings data from your browser." + } + }, + "about": { + "info": "Info", + "infotitle": "Learn about the author of this tool." + }, + "controls": { + "controls": "Controls", + "controlstitle": "Show and hide controls", + "randomize": "Randomize", + "randomizetitle": "Randomize control values", + "center": "Center", + "centertitle": "Fit image to screen", + "original": "100%", + "originaltitle": "Zoom image to its original size 100%", + "zoom": "Zoom", + "amount": "Amount", + "seed": "Seed", + "iterations": "Iterations", + "quality": "Quality", + "fullscreen": "Fullscreen", + "fullscreentitle": "Toggle Fullscreen" + }, + "nav": { + "menu": "Menu", + "menutitle": "Toggle the main menu" + }, + "file": { + "open": "Open", + "opentitle": "Open an image from your device", + "import": "Import File", + "importtitle": "Import image from your hard drive", + "recent": "Open recently edited file", + "norecent": "No recently edited files available", + "untitled": "Untitled", + "del": "delete", + "deltitle": "Delete this image from your browser’s storage", + "openimage": "Open", + "openimagetitle": "Open this image from your browser’s storage", + "offline": "Take Offline", + "offlinetitle": "Delete this image from Imgur", + "openlink": "Open Link", + "openlinktitle": "Open image link in new browser tab", + "save": "Save", + "savetitle": "Save current image for later sessions", + "download": "Download Image", + "downloadtitle": "Download the glitched image to your device", + "saveinbrowser": "Save in Browser", + "saveinbrowsertitle": "Save image in your browser’s storage", + "error": { + "load": "Could not get previous session data from your browser.", + "save": "Could not save data to your browser.", + "openimage": "Could not open image.", + "openfile": "Could not open file." + }, + "message": { + "before": "This file has been saved before.", + "save": "A file was saved to your browser’s storage.", + "del": "A file was deleted from your browser’s storage.", + "resize": "Your image was scaled down a bit to work better with this app." + } + }, + "share": { + "share": "Share", + "sharetitle": "Share your glitched image on the internet", + "info": "You can upload the image to [Imgur](https://imgur.com) to share it. Please note that after uploading the image will be publicly visible on the internet and the Imgur's [terms of service](https://imgur.com/tos) apply.", + "openon": "Open image on {$1}", + "openontitle": "Open the image you shared on {$1}", + "shareon": "Share image on {$1}", + "shareontitle": "Share your glitched image on {$1}", + "upload": "Upload Image to Imgur", + "uploadtitle": "Upload your glitched image to Imgur and share it with others online", + "uploading": "Uploading Image…", + "imagelink": "Online link to image", + "imagelinktitle": "You can use this link to share the image or embed it on other sites", + "opennewtabtitle": "Open the image in a new browser tab", + "imgur": "Imgur", + "reddit": "Reddit", + "twitter": "Twitter", + "facebook": "Facebook", + "pinterest": "Pinterest", + "recentlyshared": "Recently shared images", + "untitled": "Untitled", + "openlink": "Open Link", + "openlinktitle": "Open the online link of this image in a new browser tab", + "offline": "Take Offline", + "offlinetitle": "Delete this image from Imgur", + "error": { + "base64": "No base64 URL to upload.", + "upload": "Could not upload file to Imgur.", + "del": "Could not delete file from Imgur." + }, + "message": { + "upload": "The image was successfully uploaded to Imgur. [Click here to open it]({$1})", + "del": "The image was successfully deleted from Imgur." + } + }, + "webcam": { + "webcam": "Webcam", + "webcamtitle": "Take a picture with your webcam", + "webcamlabel": "Take a Picture", + "trigger": "Take Picture", + "triggertitle": "Click to take a picture with your webcam", + "picture": "'Webcam Picture {$1}", + "error": { + "access": "Could not access your webcam." + } + }, + "welcome": { + "firstvisit": [ + "Welcome! Looks like this is your first time here.", + "To get started, you can drag the sliders below and glitch an image.", + "You can also import an image from your device. Just click on the OPEN button in the menu." + ] + } +} \ No newline at end of file diff --git a/lincoln.jpg b/lincoln.jpg deleted file mode 100644 index 20d46a4..0000000 Binary files a/lincoln.jpg and /dev/null differ diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..18827b7 --- /dev/null +++ b/manifest.json @@ -0,0 +1,39 @@ +{ + "name": "Image Glitch Tool", + "short_name": "Glitch Tool", + "start_url": "./?utm_source=web_app_manifest", + "display": "standalone", + "background_color": "white", + "orientation": "any", + "icons": [ { + "src": "images/logos/glitch-48x48.png", + "sizes": "48x48", + "type": "image/png" + }, { + "src": "images/logos/glitch-72x72.png", + "sizes": "72x72", + "type": "image/png" + }, { + "src": "images/logos/glitch-96x96.png", + "sizes": "96x96", + "type": "image/png" + }, { + "src": "images/logos/glitch-144x144.png", + "sizes": "144x144", + "type": "image/png" + }, { + "src": "images/logos/glitch-168x168.png", + "sizes": "168x168", + "type": "image/png" + }, { + "src": "images/logos/glitch-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, { + "src": "images/logos/glitch-192x192.svg", + "sizes": "144x144 168x168 192x192", + "density": 2 + } ], + "theme_color": "black", + "service_worker": { "src": "serviceworker.js" } +} \ No newline at end of file diff --git a/scripts/aux/canvas.js b/scripts/aux/canvas.js deleted file mode 100644 index f7fe2dd..0000000 --- a/scripts/aux/canvas.js +++ /dev/null @@ -1,38 +0,0 @@ -/*global define*/ -define( - function() - { - var update = false; - - function resize( canvas, size ) - { - - if ( canvas.width !== size.width ) - { - canvas.width = size.width; - update = true; - } - - if ( canvas.height !== size.height ) - { - canvas.height = size.height; - update = true; - } - - if ( update ) - { - canvas.width = size.width; - canvas.height = size.height; - } - - update = false; - } - - function clear( canvas, ctx ) - { - ctx.clearRect( ctx, 0, 0, canvas.width, canvas.height ); - } - - return { resize: resize, clear: clear }; - } -); \ No newline at end of file diff --git a/scripts/aux/feature-test.js b/scripts/aux/feature-test.js deleted file mode 100644 index f4beb28..0000000 --- a/scripts/aux/feature-test.js +++ /dev/null @@ -1,48 +0,0 @@ -/*global define*/ -define( - function() - { - var tests = { - 'canvas': { required: true, test: function(){ return !! document.createElement('canvas').getContext; } }, - 'query-selector-all': { required: false, test: function(){ return !! document.querySelectorAll; } }, - 'drag-drop': { required: false, test: function(){ return 'draggable' in document.createElement('span'); } }, - 'file-api': { required: false, test: function(){ return typeof FileReader !== 'undefined'; } } - }; - - function test( success, error ) - { - var required_supported = true; - var results = { }; - var required_features_missing = [ ]; - - for ( var key in tests ) - { - var result = tests[key].test(); - - if ( ! result ) - { - if ( tests[key].required ) - { - required_supported = false; - - required_features_missing.push( key ); - } - } - - results[key] = result; - } - - if ( required_supported ) - { - success( results ); - } - - else - { - error( required_features_missing, results ); - } - } - - return test; - } -); \ No newline at end of file diff --git a/scripts/aux/glitch.js b/scripts/aux/glitch.js deleted file mode 100644 index caa5499..0000000 --- a/scripts/aux/glitch.js +++ /dev/null @@ -1,192 +0,0 @@ -/*global define*/ -define( - [ 'aux/canvas' ], - function( canvas_helper ) - { - var canvas = document.createElement( 'canvas' ); - var ctx = canvas.getContext( '2d' ); - - var tmp_canvas = document.createElement( 'canvas' ); - var tmp_ctx = tmp_canvas.getContext( '2d' ); - - var canvas_size = { width: 10, height: 10 }; - - var base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var base64_map = base64_chars.split( '' ); - var reverse_base64_map = { }; - - var iterations; - var quality; - var seed; - var amount; - var base64; - var byte_array; - var jpg_header_length; - var img; - var new_image_data; - - var i; - var len; - - base64_map.forEach( function( val, key ) { reverse_base64_map[val] = key; } ); - - function getGlitchedImageSrc( image_data, input, callback ) - { - seed = input.seed / 100; - quality = input.quality / 100; - amount = input.amount / 100; - iterations = input.iterations; - - canvas_helper.resize( canvas, image_data ); - canvas_helper.resize( tmp_canvas, image_data ); - - base64 = getBase64FromImageData( image_data, quality ); - byte_array = base64ToByteArray( base64 ); - jpg_header_length = getJpegHeaderSize( byte_array ); - - for ( i = 0; i < iterations; i++ ) - { - glitchJpegBytes( byte_array, jpg_header_length, seed, amount, i, iterations ); - } - - img = new Image(); - img.onload = function() { - ctx.drawImage( img, 0, 0 ); - new_image_data = ctx.getImageData( 0, 0, image_data.width, image_data.height ); - callback( new_image_data ); - }; - - img.src = byteArrayToBase64( byte_array ); - } - - function glitchJpegBytes( byte_array, jpg_header_length, seed, amount, i, len ) - { - var max_index = byte_array.length - jpg_header_length - 4; - var px_min = parseInt( max_index / len * i, 10 ); - var px_max = parseInt( max_index / len * ( i + 1 ), 10 ); - - var delta = px_max - px_min; - var px_i = parseInt( px_min + delta * seed, 10 ); - - if ( px_i > max_index ) - { - px_i = max_index; - } - - var index = Math.floor( jpg_header_length + px_i ); - - byte_array[index] = Math.floor( amount * 256 ); - } - - function getBase64FromImageData( image_data, quality ) - { - var q = typeof quality === 'number' && quality < 1 && quality > 0 ? quality : 0.1; - tmp_ctx.putImageData( image_data, 0, 0 ); - return tmp_canvas.toDataURL( 'image/jpeg', q ); - } - - function getJpegHeaderSize( data ) - { - var result = 417; - - for ( var i = 0, l = data.length; i < l; i++ ) - { - if ( data[i] === 0xFF && data[i + 1] === 0xDA ) - { - result = i + 2; - break; - } - } - - return result; - } - - // https://github.com/mutaphysis/smackmyglitchupjs/blob/master/glitch.html - // base64 is 2^6, byte is 2^8, every 4 base64 values create three bytes - function base64ToByteArray( str ) - { - var result = [ ]; - var digit_num; - var cur; - var prev; - - for ( var i = 23, l = str.length; i < l; i++ ) - { - cur = reverse_base64_map[ str.charAt( i ) ]; - digit_num = ( i - 23 ) % 4; - - switch ( digit_num ) - { - // case 0: first digit - do nothing, not enough info to work with - case 1: // second digit - result.push( prev << 2 | cur >> 4 ); - break; - case 2: // third digit - result.push( ( prev & 0x0f ) << 4 | cur >> 2 ); - break; - case 3: // fourth digit - result.push( ( prev & 3 ) << 6 | cur ); - break; - } - - prev = cur; - } - - return result; - } - - function byteArrayToBase64( arr ) - { - var result = [ 'data:image/jpeg;base64,' ]; - var byte_num; - var cur; - var prev; - var i; - - for ( var i = 0, l = arr.length; i < l; i++ ) - { - cur = arr[i]; - byte_num = i % 3; - - switch ( byte_num ) - { - case 0: // first byte - result.push( base64_map[ cur >> 2 ] ); - break; - case 1: // second byte - result.push( base64_map[( prev & 3 ) << 4 | ( cur >> 4 )] ); - break; - case 2: // third byte - result.push( base64_map[( prev & 0x0f ) << 2 | ( cur >> 6 )] ); - result.push( base64_map[cur & 0x3f] ); - break; - } - - prev = cur; - } - - if ( byte_num === 0 ) - { - result.push( base64_map[( prev & 3 ) << 4] ); - result.push( '==' ); - } - - else if ( byte_num === 1 ) - { - result.push( base64_map[( prev & 0x0f ) << 2] ); - result.push( '=' ); - } - - return result.join( '' ); - } - - function getImageDataCopy( image_data ) - { - var copy = tmp_ctx.createImageData( image_data.width, image_data.height ); - copy.data.set( image_data.data ); - return copy; - } - - return getGlitchedImageSrc; - } -); \ No newline at end of file diff --git a/scripts/config.js b/scripts/config.js new file mode 100644 index 0000000..a6678b5 --- /dev/null +++ b/scripts/config.js @@ -0,0 +1,43 @@ +define( + function () { + return { + keys: { + // this is my api key + // please get your own if you're hosting this app + // on a different server. + // https://api.imgur.com/oauth2/addclient + // thank you. + imgur: 'a4c24380d884932', + storage: 'glitch-items' + }, + defaultControlParams: { + amount: { min: 0, max: 99, value: 24 }, + seed: { min: 0, max: 100, value: 53 }, + iterations: { min: 0, max: 100, value: 21 }, + quality: { min: 1, max: 99, value: 46 } + }, + defaultImage: { + name: 'AbrahamLincoln', + path: 'images/lincoln.jpg' + }, + workers: { + glitch: 'scripts/workers/glitchworker.js', + storage: 'scripts/workers/storageworker.js', + settings: 'scripts/workers/settingsworker.js' + }, + language: { + dir: 'lang', + preset: 'en-us' + }, + settings: { + canZoomWithPointer: { value: true }, + resizeUploadedImages: { value: true }, + language: { value: 'en-us', options: [ 'en-us', 'de-de' ] } + }, + localForage: { + name : 'glitchtool', + storeName : 'keyvaluepairs' + } + }; + } +); \ No newline at end of file diff --git a/scripts/glitcher.js b/scripts/glitcher.js new file mode 100644 index 0000000..05b1442 --- /dev/null +++ b/scripts/glitcher.js @@ -0,0 +1,331 @@ +/*global require, requirejs, define*/ +// gf: http://requirejs.org/docs/api.html#config +requirejs.config( { + baseUrl: 'scripts/', + waitSeconds: 10 +} ); + +require( [ + 'config', + 'util/browser', + 'views/appview', + 'views/navview', + 'views/controlsview', + 'views/openfileview', + 'views/fullscreenview', + 'views/webcamview', + 'views/canvasview', + 'views/canvascontrolsview', + 'views/saveview', + 'views/shareview', + 'views/indicatorview', + 'views/workspacenavview', + 'views/aboutview', + 'views/draganddropview', + 'views/workspaceview', + 'views/welcomeview', + 'views/settingsview', + 'models/controlsmodel', + 'models/imagemodel', + 'models/glitchmodel', + 'models/storagemodel', + 'models/sharemodel', + 'models/networkmodel', + 'models/settingsmodel', + 'models/localisationmodel', + 'lib/localforage.nopromises' +], function ( + config, + browser, + AppView, + NavView, + ControlsView, + OpenFileView, + FullscreenView, + WebCamView, + CanvasView, + CanvasControlsView, + SaveView, + ShareView, + IndicatorView, + WorkspaceNavView, + AboutView, + DragAndDropView, + WorkspaceView, + WelcomeView, + SettingsView, + ControlsModel, + ImageModel, + GlitchModel, + StorageModel, + ShareModel, + NetworkModel, + SettingsModel, + LocalisationModel, + localforage +) { + var imageModel = ImageModel(); + var glitchModel = GlitchModel(); + var shareModel = ShareModel(); + var storageModel = StorageModel(); + var controlsModel = ControlsModel( config.defaultControlParams ); + var networkModel = NetworkModel(); + var settingsModel = SettingsModel(); + var localisationModel = LocalisationModel.sharedInstance; + + var appView = AppView( document.body ); + var navView = NavView( appView.el ); + var workspaceView = WorkspaceView( appView.el ); + var workspaceNavView = WorkspaceNavView( workspaceView.el ); + var canvasControlsView = CanvasControlsView( workspaceNavView.el ); + var controlsView = ControlsView( workspaceNavView.el, canvasControlsView.el, config.defaultControlParams ); + var indicatorView = IndicatorView( workspaceView.el ); + var canvasView = CanvasView( workspaceView.el, navView.el ); + var openFileView = OpenFileView( navView.el ); + var saveView = SaveView( navView.el ); + var webcamView = WebCamView( navView.el ); + var shareView = ShareView( navView.el ); + var aboutView = AboutView( navView.el ); + var settingsView = SettingsView( navView.el ); + var fullscreenView = FullscreenView( workspaceView.el ); + var dragAndDropView = DragAndDropView( canvasView.el ); + var welcomeView = WelcomeView(); + + function init () { + addCSSClasses(); + addSubscribers(); + + networkModel.checkConnectivity(); + + if ( browser.test( 'localforage' ) && localforage ) { + setUpLocalForage( function () { + storageModel.load(); + settingsModel.load(); + } ); + } else { + settingsModel.load(); + controlsView.loadInitialValues(); + loadInitialItem(); + } + + document.documentElement.classList.add( 'is-loaded' ); + + setTimeout( function () { + document.documentElement.classList.remove( 'is-loading' ); + }, 10 ); + } + + // hooks up all messaging between items + // using publisher/subscriber model + function addSubscribers () { + controlsView + .on( 'update', controlsModel.setValue ) + .on( 'random', controlsModel.randomizeValues ); + + controlsModel + .on( 'update', controlsView.setValue ) + .on( 'update', glitchModel.setValue ) + .on( 'update', shareView.hideShareLinks ); + + canvasControlsView + .on( 'center', canvasView.animateToCenter ) + .on( 'scale', canvasView.setScale ); + + canvasView + .on( 'scale', canvasControlsView.setScale ) + .on( 'dblclick', canvasView.animateToCenter ); + + openFileView + .on( 'openfile', imageModel.loadFromFile ) + .on( 'openfromlocalstorage', storageModel.loadItem ) + .on( 'deletefromlocalstorage', storageModel.removeLocalData ) + .on( 'deletefromimgur', shareModel.remove ); + + saveView + .on( 'savetolocalstorage', glitchModel.getImageGenerationFn( saveNewEntry ) ) + .on( 'savetolocalstorage', updateDownloadLink ) + .on( 'show', updateDownloadLink ); + + navView.on( 'toggleend', canvasView.resized ); + + imageModel + .on( 'load', glitchModel.setImageData ) + .on( 'load', openFileView.dialog.hide ) + .on( 'load', canvasView.animateToCenter ) + .on( 'load', canvasView.show ) + .on( 'update', canvasView.hide ) + .on( 'error', indicatorView.showError ) + .on( 'error', indicatorView.hideLoading ) + .on( 'statusmessage', indicatorView.showMessage ); + + glitchModel + .on( 'glitch', canvasView.putImageData ) + .on( 'glitch', canvasView.createImageUrl( shareModel.updateUrl ) ) + .on( 'glitch', updateDownloadLink ); + + shareView + .on( 'share', shareModel.upload ) + .on( 'deletefromimgur', shareModel.remove ); + + shareModel + .on( 'uploadstart', shareView.showUpload ) + .on( 'uploadend', shareView.hideUpload ) + .on( 'uploadcomplete', shareView.uploadComplete ) + .on( 'uploadcomplete', glitchModel.getImageGenerationFn( saveNewEntry ) ) + .on( 'removecomplete', storageModel.removeImgurData ) + .on( 'removecomplete', shareView.hideShareLinks ) + .on( 'error', indicatorView.showError ) + .on( 'error', shareView.handleError ) + .on( 'statusmessage', indicatorView.showMessage ); + + webcamView + .on( 'video', imageModel.loadFromVideo ) + .on( 'error', indicatorView.showError ); + + dragAndDropView + .on( 'drop', imageModel.loadFromFile ) + .on( 'drop', canvasView.hide ); + + welcomeView + .on( 'message', indicatorView.showWelcome ); + + workspaceView + .on( 'click', navView.closeSmallScreenNav ); + + settingsView + .on( 'settingchange', settingsModel.setValue ); + + storageModel + .on( 'update', openFileView.updateList ) + .on( 'update', shareView.updateList ) + .on( 'update', loadInitialItem ) + .on( 'loaditem', loadEntry ) + .on( 'statusmessage', indicatorView.showMessage ) + .on( 'error', indicatorView.showError ) + .on( 'firstvisit', welcomeView.show ); + + networkModel + .on( 'connect', shareView.showOnlineOptions ) + .on( 'disconnect', shareView.hideOnlineOptions ) + .on( 'connect', appView.showOnlineOptions ) + .on( 'disconnect', appView.hideOnlineOptions ); + + settingsModel + .on( 'update', canvasView.panZoom.settingUpdated ) + .on( 'update', imageModel.settingUpdated ) + .on( 'update', settingsView.settingUpdated ) + .on( 'update', localisationModel.settingUpdated ) + .on( 'error', indicatorView.showError ); + + localisationModel + .on( 'error', indicatorView.showError ); + } + + function addCSSClasses () { + if ( browser.test( 'touch' ) ) { + document.documentElement.classList.add( 'has-touch' ); + } + } + + function setUpLocalForage ( callback ) { + if ( localforage ) { + localforage.config( config.localForage ); + + var driver = [ + localforage.WEBSQL, + localforage.INDEXEDDB, + localforage.LOCALSTORAGE + ]; + + if ( browser.test( 'safari' ) ) { + driver = localforage.LOCALSTORAGE; + } + + localforage + .setDriver( driver ) + .then( callback ); + } else { + if ( typeof callback === 'function' ) { + callback(); + } + } + } + + function loadInitialItem ( entries ) { + var lastItemUID = -1; + + // load last saved item if possible, + // otherwise, load default image + if ( entries && Object.keys( entries ).length ) { + var now = Date.now(); + var delta = Infinity; + + for ( var uid in entries ) { + if ( entries[uid].timestamp ) { + if ( now - entries[uid].timestamp < delta ) { + delta = now - entries[uid].timestamp; + lastItemUID = uid; + } + } + } + } + + storageModel.off( 'update', loadInitialItem ); + + if ( lastItemUID !== -1 ) { + storageModel.loadItem( lastItemUID ); + } else { + imageModel.loadFromURL( config.defaultImage.path, config.defaultImage.name ); + controlsView.loadInitialValues(); + } + } + + // saves new item to local storage + function saveNewEntry ( thumbnail, publicURL, imgurID, deleteHash ) { + var item = { + thumbnail: thumbnail, + src: imageModel.getLastImageSRC(), + values: controlsModel.getValues(), + name: imageModel.getLastFileName() + }; + + if ( publicURL ) { + item.publicUrl = publicURL; + } + + if ( imgurID ) { + item.imgurID = imgurID; + } + + if ( deleteHash ) { + item.deleteHash = deleteHash; + } + + storageModel.add( item ); + } + + // loads item from localstorage + function loadEntry ( uid, entry ) { + for ( var key in entry.values ) { + controlsModel.setValue( key, entry.values[key] ); + } + + imageModel.loadFromURL( entry.src, entry.name ); + } + + // updates the download link url every time the controls were updated. + // add a delay of 200 to we don't update the DOM too often + var downloadLinkTimeoutId = NaN; + + function updateDownloadLink () { + if ( saveView.getActive() ) { + clearTimeout( downloadLinkTimeoutId ); + + downloadLinkTimeoutId = setTimeout( function () { + glitchModel.getImageGenerationFn( saveView.updateDownloadLink, 'original' )( imageModel.getLastFileName() ) + }, 200 ); + } + } + + init(); +} ); \ No newline at end of file diff --git a/scripts/lib/almond.js b/scripts/lib/almond.js new file mode 100644 index 0000000..2a06588 --- /dev/null +++ b/scripts/lib/almond.js @@ -0,0 +1,430 @@ +/** + * @license almond 0.3.1 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/jrburke/almond for details + */ +//Going sloppy to avoid 'use strict' string cost, but strict practices should +//be followed. +/*jslint sloppy: true */ +/*global setTimeout: false */ + +var requirejs, require, define; +(function (undef) { + var main, req, makeMap, handlers, + defined = {}, + waiting = {}, + config = {}, + defining = {}, + hasOwn = Object.prototype.hasOwnProperty, + aps = [].slice, + jsSuffixRegExp = /\.js$/; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @returns {String} normalized name + */ + function normalize(name, baseName) { + var nameParts, nameSegment, mapValue, foundMap, lastIndex, + foundI, foundStarMap, starI, i, j, part, + baseParts = baseName && baseName.split("/"), + map = config.map, + starMap = (map && map['*']) || {}; + + //Adjust any relative paths. + if (name && name.charAt(0) === ".") { + //If have a base name, try to normalize against it, + //otherwise, assume it is a top-level require that will + //be relative to baseUrl in the end. + if (baseName) { + name = name.split('/'); + lastIndex = name.length - 1; + + // Node .js allowance: + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + //Lop off the last part of baseParts, so that . matches the + //"directory" and not name of the baseName's module. For instance, + //baseName of "one/two/three", maps to "one/two/three.js", but we + //want the directory, "one/two" for this normalization. + name = baseParts.slice(0, baseParts.length - 1).concat(name); + + //start trimDots + for (i = 0; i < name.length; i += 1) { + part = name[i]; + if (part === ".") { + name.splice(i, 1); + i -= 1; + } else if (part === "..") { + if (i === 1 && (name[2] === '..' || name[0] === '..')) { + //End of the line. Keep at least one non-dot + //path segment at the front so it can be mapped + //correctly to disk. Otherwise, there is likely + //no path mapping for a path starting with '..'. + //This can still fail, but catches the most reasonable + //uses of .. + break; + } else if (i > 0) { + name.splice(i - 1, 2); + i -= 2; + } + } + } + //end trimDots + + name = name.join("/"); + } else if (name.indexOf('./') === 0) { + // No baseName, so this is ID is resolved relative + // to baseUrl, pull off the leading dot. + name = name.substring(2); + } + } + + //Apply map config if available. + if ((baseParts || starMap) && map) { + nameParts = name.split('/'); + + for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join("/"); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = map[baseParts.slice(0, j).join('/')]; + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = mapValue[nameSegment]; + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break; + } + } + } + } + + if (foundMap) { + break; + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && starMap[nameSegment]) { + foundStarMap = starMap[nameSegment]; + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + return name; + } + + function makeRequire(relName, forceSync) { + return function () { + //A version of a require function that passes a moduleName + //value for items that may need to + //look up paths relative to the moduleName + var args = aps.call(arguments, 0); + + //If first arg is not require('string'), and there is only + //one arg, it is the array form without a callback. Insert + //a null so that the following concat is correct. + if (typeof args[0] !== 'string' && args.length === 1) { + args.push(null); + } + return req.apply(undef, args.concat([relName, forceSync])); + }; + } + + function makeNormalize(relName) { + return function (name) { + return normalize(name, relName); + }; + } + + function makeLoad(depName) { + return function (value) { + defined[depName] = value; + }; + } + + function callDep(name) { + if (hasProp(waiting, name)) { + var args = waiting[name]; + delete waiting[name]; + defining[name] = true; + main.apply(undef, args); + } + + if (!hasProp(defined, name) && !hasProp(defining, name)) { + throw new Error('No ' + name); + } + return defined[name]; + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + /** + * Makes a name map, normalizing the name, and using a plugin + * for normalization if necessary. Grabs a ref to plugin + * too, as an optimization. + */ + makeMap = function (name, relName) { + var plugin, + parts = splitPrefix(name), + prefix = parts[0]; + + name = parts[1]; + + if (prefix) { + prefix = normalize(prefix, relName); + plugin = callDep(prefix); + } + + //Normalize according + if (prefix) { + if (plugin && plugin.normalize) { + name = plugin.normalize(name, makeNormalize(relName)); + } else { + name = normalize(name, relName); + } + } else { + name = normalize(name, relName); + parts = splitPrefix(name); + prefix = parts[0]; + name = parts[1]; + if (prefix) { + plugin = callDep(prefix); + } + } + + //Using ridiculous property names for space reasons + return { + f: prefix ? prefix + '!' + name : name, //fullName + n: name, + pr: prefix, + p: plugin + }; + }; + + function makeConfig(name) { + return function () { + return (config && config.config && config.config[name]) || {}; + }; + } + + handlers = { + require: function (name) { + return makeRequire(name); + }, + exports: function (name) { + var e = defined[name]; + if (typeof e !== 'undefined') { + return e; + } else { + return (defined[name] = {}); + } + }, + module: function (name) { + return { + id: name, + uri: '', + exports: defined[name], + config: makeConfig(name) + }; + } + }; + + main = function (name, deps, callback, relName) { + var cjsModule, depName, ret, map, i, + args = [], + callbackType = typeof callback, + usingExports; + + //Use name if no relName + relName = relName || name; + + //Call the callback to define the module, if necessary. + if (callbackType === 'undefined' || callbackType === 'function') { + //Pull out the defined dependencies and pass the ordered + //values to the callback. + //Default to [require, exports, module] if no deps + deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; + for (i = 0; i < deps.length; i += 1) { + map = makeMap(deps[i], relName); + depName = map.f; + + //Fast path CommonJS standard dependencies. + if (depName === "require") { + args[i] = handlers.require(name); + } else if (depName === "exports") { + //CommonJS module spec 1.1 + args[i] = handlers.exports(name); + usingExports = true; + } else if (depName === "module") { + //CommonJS module spec 1.1 + cjsModule = args[i] = handlers.module(name); + } else if (hasProp(defined, depName) || + hasProp(waiting, depName) || + hasProp(defining, depName)) { + args[i] = callDep(depName); + } else if (map.p) { + map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); + args[i] = defined[depName]; + } else { + throw new Error(name + ' missing ' + depName); + } + } + + ret = callback ? callback.apply(defined[name], args) : undefined; + + if (name) { + //If setting exports via "module" is in play, + //favor that over return value and exports. After that, + //favor a non-undefined return value over exports use. + if (cjsModule && cjsModule.exports !== undef && + cjsModule.exports !== defined[name]) { + defined[name] = cjsModule.exports; + } else if (ret !== undef || !usingExports) { + //Use the return value from the function. + defined[name] = ret; + } + } + } else if (name) { + //May just be an object definition for the module. Only + //worry about defining if have a module name. + defined[name] = callback; + } + }; + + requirejs = require = req = function (deps, callback, relName, forceSync, alt) { + if (typeof deps === "string") { + if (handlers[deps]) { + //callback in this case is really relName + return handlers[deps](callback); + } + //Just return the module wanted. In this scenario, the + //deps arg is the module name, and second arg (if passed) + //is just the relName. + //Normalize module name, if it contains . or .. + return callDep(makeMap(deps, callback).f); + } else if (!deps.splice) { + //deps is a config object, not an array. + config = deps; + if (config.deps) { + req(config.deps, config.callback); + } + if (!callback) { + return; + } + + if (callback.splice) { + //callback is an array, which means it is a dependency list. + //Adjust args if there are dependencies + deps = callback; + callback = relName; + relName = null; + } else { + deps = undef; + } + } + + //Support require(['a']) + callback = callback || function () {}; + + //If relName is a function, it is an errback handler, + //so remove it. + if (typeof relName === 'function') { + relName = forceSync; + forceSync = alt; + } + + //Simulate async callback; + if (forceSync) { + main(undef, deps, callback, relName); + } else { + //Using a non-zero value because of concern for what old browsers + //do, and latest browsers "upgrade" to 4 if lower value is used: + //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: + //If want a value immediately, use require('id') instead -- something + //that works in almond on the global level, but not guaranteed and + //unlikely to work in other AMD implementations. + setTimeout(function () { + main(undef, deps, callback, relName); + }, 4); + } + + return req; + }; + + /** + * Just drops the config on the floor, but returns req in case + * the config return value is used. + */ + req.config = function (cfg) { + return req(cfg); + }; + + /** + * Expose module registry for debugging and tooling + */ + requirejs._defined = defined; + + define = function (name, deps, callback) { + if (typeof name !== 'string') { + throw new Error('See almond README: incorrect module build, no module name'); + } + + //This module may not have dependencies + if (!deps.splice) { + //deps is not an array, so probably means + //an object literal or factory function for + //the value. Adjust args. + callback = deps; + deps = []; + } + + if (!hasProp(defined, name) && !hasProp(waiting, name)) { + waiting[name] = [name, deps, callback]; + } + }; + + define.amd = { + jQuery: true + }; +}()); diff --git a/scripts/lib/glitch-canvas-with-worker.js b/scripts/lib/glitch-canvas-with-worker.js new file mode 100644 index 0000000..f75581c --- /dev/null +++ b/scripts/lib/glitch-canvas-with-worker.js @@ -0,0 +1,292 @@ +//! glitch-canvas by snorpey, MIT License +(function(window, factory) { + if (typeof define === "function" && define.amd) { + define(factory); + } else if (typeof exports === "object") { + module.exports = factory(); + } else { + window.glitch = factory(); + } +})(this, function() { + + function Glitcher ( webworkerPath ) { + if ( ! ( this instanceof Glitcher ) ) { + return new Glitcher( webworkerPath ); + } + + var self = this + var canvas1El = document.createElement( 'canvas' ); + var canvas2El = document.createElement( 'canvas' ); + var ctx1 = canvas1El.getContext( '2d' ); + var ctx2 = canvas2El.getContext( '2d' ); + var img = new Image(); + var base64; + var img; + var newImageData; + var i; + var len; + var params; + var worker; + var base64Chars; + var base64Map; + var reversedBase64Map; + var byteArrayImageData; + var jpgHeaderLength; + + function init () { + if ( webworkerPath && 'Worker' in window ) { + worker = new Worker( webworkerPath ); + worker.addEventListener( 'message', workerResponded, false ); + } else { + base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + base64Map = base64Chars.split( '' ); + reversedBase64Map = { }; + + base64Map.forEach( function ( val, key ) { + reversedBase64Map[val] = key; + } ); + } + + return self; + } + + function glitch ( imageData, parameters, callback ) { + if ( + isValidImageData( imageData ) && + isType( parameters, 'parameters', 'object' ) && + isType( callback, 'callback', 'function' ) + ) { + resizeCanvas( canvas1El, imageData ); + resizeCanvas( canvas2El, imageData ); + params = getNormalizedParameters( parameters ); + base64 = getBase64FromImageData( imageData, params.quality ); + + img.onload = function () { + ctx1.drawImage( img, 0, 0 ); + newImageData = ctx1.getImageData( 0, 0, imageData.width, imageData.height ); + callback ( newImageData ); + img.onload = null; + }; + + if ( worker ) { + worker.postMessage( { glitch: { base64: base64, parameters: params } } ); + } else { + byteArrayImageData = base64ToByteArray( base64 ); + jpgHeaderLength = getJpegHeaderSize( byteArrayImageData ); + + for ( i = 0, len = params.iterations; i < len; i++ ) { + glitchJpegBytes( byteArrayImageData, jpgHeaderLength, params.seed, params.amount, i, params.iterations ); + } + + img.src = byteArrayToBase64( byteArrayImageData ); + } + } + + return self; + } + + function workerResponded ( event ) { + if ( event && event.data && event.data.glitched ) { + glitched( event.data.glitched ); + } else { + window.console && console.log( 'glitchworker response', event.data ); + } + } + + function workerFailed ( err ) { + window.console && console.log( err.message || err ); + } + + function glitched ( newBase64ImageData ) { + img.src = newBase64ImageData; + } + + function resizeCanvas ( canvas, size ) { + if ( canvas.width !== size.width ) { + canvas.width = size.width; + } + + if ( canvas.height !== size.height ) { + canvas.height = size.height; + } + } + + function getNormalizedParameters ( parameters ) { + return { + seed: ( parameters.seed || 0 ) / 100, + quality: ( parameters.quality || 0 ) / 100, + amount: ( parameters.amount || 0 ) / 100, + iterations: parameters.iterations || 0 + }; + } + + function getBase64FromImageData ( imageData, quality ) { + var q = typeof quality === 'number' && quality < 1 && quality > 0 ? quality : .1; + + ctx2.putImageData( imageData, 0, 0 ); + + var base64 = canvas2El.toDataURL( 'image/jpeg', q ); + + switch ( base64.length % 4 ) { + case 3: + base64 += '='; + break; + + case 2: + base64 += '=='; + break; + + case 1: + base64 += '==='; + break; + } + + return base64; + } + + function isValidImageData ( imageData ) { + if ( + isType( imageData, 'imageData', 'object' ) && + isType( imageData.width, 'imageData.width', 'number' ) && + isType( imageData.height, 'imageData.height', 'number' ) && + isType( imageData.data, 'imageData.data', 'object' ) && + isType( imageData.data.length, 'imageData.data.length', 'number' ) && + checkNumber( imageData.data.length, 'imageData.data.length', isPositive, '> 0' ) + ) { + return true; + } else { + return false; + } + } + + function isType ( it, name, expectedType ) { + if ( typeof it === expectedType ) { + return true; + } else { + error( it, 'typeof ' + name, '"' + expectedType + '"', '"' + typeof it + '"' ); + return false; + } + } + + function checkNumber ( it, name, condition, conditionName ) { + if ( condition( it ) === true) { + return true; + } else { + error( it, name, conditionName, 'not' ); + } + } + + function isPositive ( nr ) { + return nr > 0; + } + + function error ( it, name, expected, result ) { + throw new Error( 'glitch(): Expected ' + name + ' to be ' + expected + ', but it was ' + result + '.' ); + } + + // all functions beyond this point are only used if no webworker is available + + function glitchJpegBytes ( byteArray, jpgHeaderLength, seed, amount, i, len ) { + var maxIndex = byteArray.length - jpgHeaderLength - 4; + var pxMin = parseInt( maxIndex / len * i, 10 ); + var pxMax = parseInt( maxIndex / len * ( i + 1 ), 10 ); + var delta = pxMax - pxMin; + var pxIndex = parseInt( pxMin + delta * seed, 10 ); + + if ( pxIndex > maxIndex ) { + pxIndex = maxIndex; + } + + var index = Math.floor( jpgHeaderLength + pxIndex ); + + byteArray[index] = Math.floor( amount * 256 ); + } + + function base64ToByteArray ( str ) { + var result = [ ]; + var digitNum; + var cur; + var prev; + + for ( i = 23, len = str.length; i < len; i++ ) { + cur = reversedBase64Map[str.charAt( i )]; + digitNum = ( i - 23 ) % 4; + + switch ( digitNum ) { + case 1: + result.push( prev << 2 | cur >> 4 ); + break; + + case 2: + result.push( ( prev & 15 ) << 4 | cur >> 2 ); + break; + + case 3: + result.push( ( prev & 3 ) << 6 | cur ); + break; + } + + prev = cur; + } + + return result; + } + + function byteArrayToBase64 ( arr ) { + var result = [ 'data:image/jpeg;base64,' ]; + var byteNum; + var cur; + var prev; + + for ( i = 0, len = arr.length; i < len; i++ ) { + cur = arr[i]; + byteNum = i % 3; + + switch (byteNum) { + case 0: + result.push( base64Map[cur >> 2] ); + break; + + case 1: + result.push( base64Map[( prev & 3 ) << 4 | cur >> 4] ); + break; + + case 2: + result.push( base64Map[( prev & 15 ) << 2 | cur >> 6] ); + result.push( base64Map[cur & 63] ); + break; + } + + prev = cur; + } + + if ( byteNum === 0 ) { + result.push( base64Map[( prev & 3 ) << 4] ); + result.push( '==' ); + } else if ( byteNum === 1 ) { + result.push( base64Map[( prev & 15 ) << 2] ); + result.push( '=' ); + } + + return result.join( '' ); + } + + function getJpegHeaderSize ( data ) { + var result = 417; + + for ( i = 0, len = data.length; i < len; i++ ) { + if ( data[i] === 255 && data[i + 1] === 218 ) { + result = i + 2; + break; + } + } + + return result; + } + + self.glitch = glitch; + self.init = init; + } + + return Glitcher; +}); \ No newline at end of file diff --git a/scripts/lib/html5slider.js b/scripts/lib/html5slider.js deleted file mode 100644 index ec96c69..0000000 --- a/scripts/lib/html5slider.js +++ /dev/null @@ -1,285 +0,0 @@ -/* -html5slider - a JS implementation of for Firefox 16 and up -https://github.com/fryn/html5slider - -Copyright (c) 2010-2013 Frank Yan, - -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. -*/ - -(function() { - -// test for native support -var test = document.createElement('input'); -try { - test.type = 'range'; - if (test.type == 'range') - return; -} catch (e) { - return; -} - -// test for required property support -test.style.background = 'linear-gradient(red, red)'; -if (!test.style.backgroundImage || !('MozAppearance' in test.style) || - !document.mozSetImageElement || !this.MutationObserver) - return; - -var scale; -var isMac = navigator.platform == 'MacIntel'; -var thumb = { - radius: isMac ? 9 : 6, - width: isMac ? 22 : 12, - height: isMac ? 16 : 20 -}; -var track = 'linear-gradient(transparent ' + (isMac ? - '6px, #999 6px, #999 7px, #ccc 8px, #bbb 9px, #bbb 10px, transparent 10px' : - '9px, #999 9px, #bbb 10px, #fff 11px, transparent 11px') + - ', transparent)'; -var styles = { - 'min-width': thumb.width + 'px', - 'min-height': thumb.height + 'px', - 'max-height': thumb.height + 'px', - padding: '0 0 ' + (isMac ? '2px' : '1px'), - border: 0, - 'border-radius': 0, - cursor: 'default', - 'text-indent': '-999999px' // -moz-user-select: none; breaks mouse capture -}; -var options = { - attributes: true, - attributeFilter: ['min', 'max', 'step', 'value'] -}; -var forEach = Array.prototype.forEach; -var onInput = document.createEvent('HTMLEvents'); -onInput.initEvent('input', true, false); -var onChange = document.createEvent('HTMLEvents'); -onChange.initEvent('change', true, false); - -if (document.readyState == 'loading') - document.addEventListener('DOMContentLoaded', initialize, true); -else - initialize(); - -function initialize() { - // create initial sliders - forEach.call(document.querySelectorAll('input[type=range]'), transform); - // create sliders on-the-fly - new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - if (mutation.addedNodes) - forEach.call(mutation.addedNodes, function(node) { - check(node); - if (node.childElementCount) - forEach.call(node.querySelectorAll('input'), check); - }); - }); - }).observe(document, { childList: true, subtree: true }); -} - -function check(input) { - if (input.localName == 'input' && input.type != 'range' && - input.getAttribute('type') == 'range') - transform(input); -} - -function transform(slider) { - - var isValueSet, areAttrsSet, isChanged, isClick, prevValue, rawValue, prevX; - var min, max, step, range, value = slider.value; - - // lazily create shared slider affordance - if (!scale) { - scale = document.body.appendChild(document.createElement('hr')); - style(scale, { - '-moz-appearance': isMac ? 'scale-horizontal' : 'scalethumb-horizontal', - display: 'block', - visibility: 'visible', - opacity: 1, - position: 'fixed', - top: '-999999px' - }); - document.mozSetImageElement('__sliderthumb__', scale); - } - - // reimplement value and type properties - var getValue = function() { return '' + value; }; - var setValue = function setValue(val) { - value = '' + val; - isValueSet = true; - draw(); - delete slider.value; - slider.value = value; - Object.defineProperty(slider, 'value', { - get: getValue, - set: setValue - }); - }; - Object.defineProperty(slider, 'value', { - get: getValue, - set: setValue - }); - Object.defineProperty(slider, 'type', { - get: function() { return 'range'; } - }); - - // sync properties with attributes - ['min', 'max', 'step'].forEach(function(prop) { - if (slider.hasAttribute(prop)) - areAttrsSet = true; - Object.defineProperty(slider, prop, { - get: function() { return this.hasAttribute(prop) ? this.getAttribute(prop) : ''; }, - set: function(val) { val === null ? this.removeAttribute(prop) : this.setAttribute(prop, val); } - }); - }); - - // initialize slider - slider.readOnly = true; - style(slider, styles); - update(); - - new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - if (mutation.attributeName != 'value') { - update(); - areAttrsSet = true; - } - // note that value attribute only sets initial value - else if (!isValueSet) { - value = slider.getAttribute('value'); - draw(); - } - }); - }).observe(slider, options); - - slider.addEventListener('mousedown', onDragStart, true); - slider.addEventListener('keydown', onKeyDown, true); - slider.addEventListener('focus', onFocus, true); - slider.addEventListener('blur', onBlur, true); - - function onDragStart(e) { - isClick = true; - setTimeout(function() { isClick = false; }, 0); - if (e.button || !range) - return; - var width = parseFloat(getComputedStyle(this, 0).width); - var multiplier = (width - thumb.width) / range; - if (!multiplier) - return; - // distance between click and center of thumb - var dev = e.clientX - this.getBoundingClientRect().left - thumb.width / 2 - - (value - min) * multiplier; - // if click was not on thumb, move thumb to click location - if (Math.abs(dev) > thumb.radius) { - isChanged = true; - this.value -= -dev / multiplier; - } - rawValue = value; - prevX = e.clientX; - this.addEventListener('mousemove', onDrag, true); - this.addEventListener('mouseup', onDragEnd, true); - } - - function onDrag(e) { - var width = parseFloat(getComputedStyle(this, 0).width); - var multiplier = (width - thumb.width) / range; - if (!multiplier) - return; - rawValue += (e.clientX - prevX) / multiplier; - prevX = e.clientX; - isChanged = true; - this.value = rawValue; - } - - function onDragEnd() { - this.removeEventListener('mousemove', onDrag, true); - this.removeEventListener('mouseup', onDragEnd, true); - slider.dispatchEvent(onChange); - } - - function onKeyDown(e) { - if (e.keyCode > 36 && e.keyCode < 41) { // 37-40: left, up, right, down - onFocus.call(this); - isChanged = true; - this.value = value + (e.keyCode == 38 || e.keyCode == 39 ? step : -step); - } - } - - function onFocus() { - if (!isClick) - this.style.boxShadow = !isMac ? '0 0 0 2px #fb0' : - 'inset 0 0 20px rgba(0,127,255,.1), 0 0 1px rgba(0,127,255,.4)'; - } - - function onBlur() { - this.style.boxShadow = ''; - } - - // determines whether value is valid number in attribute form - function isAttrNum(value) { - return !isNaN(value) && +value == parseFloat(value); - } - - // validates min, max, and step attributes and redraws - function update() { - min = isAttrNum(slider.min) ? +slider.min : 0; - max = isAttrNum(slider.max) ? +slider.max : 100; - if (max < min) - max = min > 100 ? min : 100; - step = isAttrNum(slider.step) && slider.step > 0 ? +slider.step : 1; - range = max - min; - draw(true); - } - - // recalculates value property - function calc() { - if (!isValueSet && !areAttrsSet) - value = slider.getAttribute('value'); - if (!isAttrNum(value)) - value = (min + max) / 2;; - // snap to step intervals (WebKit sometimes does not - bug?) - value = Math.round((value - min) / step) * step + min; - if (value < min) - value = min; - else if (value > max) - value = min + ~~(range / step) * step; - } - - // renders slider using CSS background ;) - function draw(attrsModified) { - calc(); - if (isChanged && value != prevValue) - slider.dispatchEvent(onInput); - isChanged = false; - if (!attrsModified && value == prevValue) - return; - prevValue = value; - var position = range ? (value - min) / range * 100 : 0; - var bg = '-moz-element(#__sliderthumb__) ' + position + '% no-repeat, '; - style(slider, { background: bg + track }); - } - -} - -function style(element, styles) { - for (var prop in styles) - element.style.setProperty(prop, styles[prop], 'important'); -} - -})(); diff --git a/scripts/lib/localforage.nopromises.js b/scripts/lib/localforage.nopromises.js new file mode 100644 index 0000000..1445c28 --- /dev/null +++ b/scripts/lib/localforage.nopromises.js @@ -0,0 +1,2103 @@ +if ( 'Promise' in ( typeof window !== 'undefined' ? window : self ) ) { +/*! + localForage -- Offline Storage, Improved + Version 1.3.1 + https://mozilla.github.io/localForage + (c) 2013-2015 Mozilla, Apache License 2.0 +*/ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["localforage"] = factory(); + else + root["localforage"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + exports.__esModule = true; + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + + (function () { + 'use strict'; + + // Custom drivers are stored here when `defineDriver()` is called. + // They are shared across all instances of localForage. + var CustomDrivers = {}; + + var DriverType = { + INDEXEDDB: 'asyncStorage', + LOCALSTORAGE: 'localStorageWrapper', + WEBSQL: 'webSQLStorage' + }; + + var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; + + var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; + + var DefaultConfig = { + description: '', + driver: DefaultDriverOrder.slice(), + name: 'localforage', + // Default DB size is _JUST UNDER_ 5MB, as it's the highest size + // we can use without a prompt. + size: 4980736, + storeName: 'keyvaluepairs', + version: 1.0 + }; + + // Check to see if IndexedDB is available and if it is the latest + // implementation; it's our preferred backend library. We use "_spec_test" + // as the name of the database because it's not the one we'll operate on, + // but it's useful to make sure its using the right spec. + // See: https://github.com/mozilla/localForage/issues/128 + var driverSupport = (function (self) { + // Initialize IndexedDB; fall back to vendor-prefixed versions + // if needed. + var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; + + var result = {}; + + result[DriverType.WEBSQL] = !!self.openDatabase; + result[DriverType.INDEXEDDB] = !!(function () { + // We mimic PouchDB here; just UA test for Safari (which, as of + // iOS 8/Yosemite, doesn't properly support IndexedDB). + // IndexedDB support is broken and different from Blink's. + // This is faster than the test case (and it's sync), so we just + // do this. *SIGH* + // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ + // + // We test for openDatabase because IE Mobile identifies itself + // as Safari. Oh the lulz... + if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { + return false; + } + try { + return indexedDB && typeof indexedDB.open === 'function' && + // Some Samsung/HTC Android 4.0-4.3 devices + // have older IndexedDB specs; if this isn't available + // their IndexedDB is too old for us to use. + // (Replaces the onupgradeneeded test.) + typeof self.IDBKeyRange !== 'undefined'; + } catch (e) { + return false; + } + })(); + + result[DriverType.LOCALSTORAGE] = !!(function () { + try { + return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; + } catch (e) { + return false; + } + })(); + + return result; + })(this); + + var isArray = Array.isArray || function (arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; + + function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function () { + var _args = arguments; + return localForageInstance.ready().then(function () { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; + } + + function extend() { + for (var i = 1; i < arguments.length; i++) { + var arg = arguments[i]; + + if (arg) { + for (var key in arg) { + if (arg.hasOwnProperty(key)) { + if (isArray(arg[key])) { + arguments[0][key] = arg[key].slice(); + } else { + arguments[0][key] = arg[key]; + } + } + } + } + } + + return arguments[0]; + } + + function isLibraryDriver(driverName) { + for (var driver in DriverType) { + if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { + return true; + } + } + + return false; + } + + var LocalForage = (function () { + function LocalForage(options) { + _classCallCheck(this, LocalForage); + + this.INDEXEDDB = DriverType.INDEXEDDB; + this.LOCALSTORAGE = DriverType.LOCALSTORAGE; + this.WEBSQL = DriverType.WEBSQL; + + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver); + } + + // The actual localForage object that we expose as a module or via a + // global. It's extended by pulling in one of our other libraries. + + // Set any config values for localForage; can be called anytime before + // the first API call (e.g. `getItem`, `setItem`). + // We loop through options so we don't overwrite existing config + // values. + + LocalForage.prototype.config = function config(options) { + // If the options argument is an object, we use it to set values. + // Otherwise, we return either a specified config value or all + // config values. + if (typeof options === 'object') { + // If localforage is ready and fully initialized, we can't set + // any new configuration values. Instead, we return an error. + if (this._ready) { + return new Error("Can't call config() after localforage " + 'has been used.'); + } + + for (var i in options) { + if (i === 'storeName') { + options[i] = options[i].replace(/\W/g, '_'); + } + + this._config[i] = options[i]; + } + + // after all config options are set and + // the driver option is used, try setting it + if ('driver' in options && options.driver) { + this.setDriver(this._config.driver); + } + + return true; + } else if (typeof options === 'string') { + return this._config[options]; + } else { + return this._config; + } + }; + + // Used to define a custom driver, shared across all instances of + // localForage. + + LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise(function (resolve, reject) { + try { + var driverName = driverObject._driver; + var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); + var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); + + // A driver name should be defined and not overlap with the + // library-defined, default drivers. + if (!driverObject._driver) { + reject(complianceError); + return; + } + if (isLibraryDriver(driverObject._driver)) { + reject(namingError); + return; + } + + var customDriverMethods = LibraryMethods.concat('_initStorage'); + for (var i = 0; i < customDriverMethods.length; i++) { + var customDriverMethod = customDriverMethods[i]; + if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { + reject(complianceError); + return; + } + } + + var supportPromise = Promise.resolve(true); + if ('_support' in driverObject) { + if (driverObject._support && typeof driverObject._support === 'function') { + supportPromise = driverObject._support(); + } else { + supportPromise = Promise.resolve(!!driverObject._support); + } + } + + supportPromise.then(function (supportResult) { + driverSupport[driverName] = supportResult; + CustomDrivers[driverName] = driverObject; + resolve(); + }, reject); + } catch (e) { + reject(e); + } + }); + + promise.then(callback, errorCallback); + return promise; + }; + + LocalForage.prototype.driver = function driver() { + return this._driver || null; + }; + + LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var self = this; + var getDriverPromise = (function () { + if (isLibraryDriver(driverName)) { + switch (driverName) { + case self.INDEXEDDB: + return new Promise(function (resolve, reject) { + resolve(__webpack_require__(1)); + }); + case self.LOCALSTORAGE: + return new Promise(function (resolve, reject) { + resolve(__webpack_require__(2)); + }); + case self.WEBSQL: + return new Promise(function (resolve, reject) { + resolve(__webpack_require__(4)); + }); + } + } else if (CustomDrivers[driverName]) { + return Promise.resolve(CustomDrivers[driverName]); + } + + return Promise.reject(new Error('Driver not found.')); + })(); + + getDriverPromise.then(callback, errorCallback); + return getDriverPromise; + }; + + LocalForage.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = new Promise(function (resolve, reject) { + resolve(__webpack_require__(3)); + }); + if (callback && typeof callback === 'function') { + serializerPromise.then(function (result) { + callback(result); + }); + } + return serializerPromise; + }; + + LocalForage.prototype.ready = function ready(callback) { + var self = this; + + var promise = self._driverSet.then(function () { + if (self._ready === null) { + self._ready = self._initDriver(); + } + + return self._ready; + }); + + promise.then(callback, callback); + return promise; + }; + + LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self = this; + + if (!isArray(drivers)) { + drivers = [drivers]; + } + + var supportedDrivers = this._getSupportedDrivers(drivers); + + function setDriverToConfig() { + self._config.driver = self.driver(); + } + + function initDriver(supportedDrivers) { + return function () { + var currentDriverIndex = 0; + + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers.length) { + var driverName = supportedDrivers[currentDriverIndex]; + currentDriverIndex++; + + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._extend(driver); + setDriverToConfig(); + + self._ready = self._initStorage(self._config); + return self._ready; + })['catch'](driverPromiseLoop); + } + + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise.reject(error); + return self._driverSet; + } + + return driverPromiseLoop(); + }; + } + + // There might be a driver initialization in progress + // so wait for it to finish in order to avoid a possible + // race condition to set _dbInfo + var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { + return Promise.resolve(); + }) : Promise.resolve(); + + this._driverSet = oldDriverSetDone.then(function () { + var driverName = supportedDrivers[0]; + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._driver = driver._driver; + setDriverToConfig(); + self._wrapLibraryMethodsWithReady(); + self._initDriver = initDriver(supportedDrivers); + }); + })['catch'](function () { + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise.reject(error); + return self._driverSet; + }); + + this._driverSet.then(callback, errorCallback); + return this._driverSet; + }; + + LocalForage.prototype.supports = function supports(driverName) { + return !!driverSupport[driverName]; + }; + + LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + + LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length; i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + + LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + // Add a stub for each driver API method that delays the call to the + // corresponding driver method until localForage is ready. These stubs + // will be replaced by the driver methods as soon as the driver is + // loaded, so there is no performance impact. + for (var i = 0; i < LibraryMethods.length; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + + LocalForage.prototype.createInstance = function createInstance(options) { + return new LocalForage(options); + }; + + return LocalForage; + })(); + + var localForage = new LocalForage(); + + exports['default'] = localForage; + }).call(typeof window !== 'undefined' ? window : self); + module.exports = exports['default']; + +/***/ }, +/* 1 */ +/***/ function(module, exports) { + + // Some code originally from async_storage.js in + // [Gaia](https://github.com/mozilla-b2g/gaia). + 'use strict'; + + exports.__esModule = true; + (function () { + 'use strict'; + + var globalObject = this; + // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. + var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; + + // If IndexedDB isn't available, we get outta here! + if (!indexedDB) { + return; + } + + var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; + var supportsBlobs; + var dbContexts; + + // Abstracts constructing a Blob object, so it also works in older + // browsers that don't support the native Blob constructor. (i.e. + // old QtWebKit versions, at least). + function _createBlob(parts, properties) { + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== 'TypeError') { + throw e; + } + var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; + var builder = new BlobBuilder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } + } + + // Transform a binary string to an array buffer, because otherwise + // weird stuff happens when you try to work with the binary string directly. + // It is known. + // From http://stackoverflow.com/questions/14967647/ (continues on next line) + // encode-decode-image-with-base64-breaks-image (2013-04-21) + function _binStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; + } + + // Fetch a blob using ajax. This reveals bugs in Chrome < 43. + // For details on all this junk: + // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme + function _blobAjax(url) { + return new Promise(function (resolve, reject) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url); + xhr.withCredentials = true; + xhr.responseType = 'arraybuffer'; + + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) { + return; + } + if (xhr.status === 200) { + return resolve({ + response: xhr.response, + type: xhr.getResponseHeader('Content-Type') + }); + } + reject({ status: xhr.status, response: xhr.response }); + }; + xhr.send(); + }); + } + + // + // Detect blob support. Chrome didn't support it until version 38. + // In version 37 they had a broken version where PNGs (and possibly + // other binary types) aren't stored correctly, because when you fetch + // them, the content type is always null. + // + // Furthermore, they have some outstanding bugs where blobs occasionally + // are read by FileReader as null, or by ajax as 404s. + // + // Sadly we use the 404 bug to detect the FileReader bug, so if they + // get fixed independently and released in different versions of Chrome, + // then the bug could come back. So it's worthwhile to watch these issues: + // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 + // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 + // + function _checkBlobSupportWithoutCaching(idb) { + return new Promise(function (resolve, reject) { + var blob = _createBlob([''], { type: 'image/png' }); + var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); + txn.oncomplete = function () { + // have to do it in a separate transaction, else the correct + // content type is always returned + var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); + var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); + getBlobReq.onerror = reject; + getBlobReq.onsuccess = function (e) { + + var storedBlob = e.target.result; + var url = URL.createObjectURL(storedBlob); + + _blobAjax(url).then(function (res) { + resolve(!!(res && res.type === 'image/png')); + }, function () { + resolve(false); + }).then(function () { + URL.revokeObjectURL(url); + }); + }; + }; + })['catch'](function () { + return false; // error, so assume unsupported + }); + } + + function _checkBlobSupport(idb) { + if (typeof supportsBlobs === 'boolean') { + return Promise.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb).then(function (value) { + supportsBlobs = value; + return supportsBlobs; + }); + } + + // encode a blob for indexeddb engines that don't support blobs + function _encodeBlob(blob) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = function (e) { + var base64 = btoa(e.target.result || ''); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); + } + + // decode an encoded blob + function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return _createBlob([arrayBuff], { type: encodedBlob.type }); + } + + // is this one of our fancy encoded blobs? + function _isEncodedBlob(value) { + return value && value.__local_forage_encoded_blob; + } + + // Open the IndexedDB database (automatically creates one if one didn't + // previously exist), using any options set in the config. + function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + // Initialize a singleton container for all running localForages. + if (!dbContexts) { + dbContexts = {}; + } + + // Get the current context of the database; + var dbContext = dbContexts[dbInfo.name]; + + // ...or create a new context. + if (!dbContext) { + dbContext = { + // Running localForages sharing a database. + forages: [], + // Shared database. + db: null + }; + // Register the new context in the global container. + dbContexts[dbInfo.name] = dbContext; + } + + // Register itself as a running localForage in the current context. + dbContext.forages.push(this); + + // Create an array of readiness of the related localForages. + var readyPromises = []; + + function ignoreErrors() { + // Don't handle errors here, + // just makes sure related localForages aren't pending. + return Promise.resolve(); + } + + for (var j = 0; j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== this) { + // Don't wait for itself... + readyPromises.push(forage.ready()['catch'](ignoreErrors)); + } + } + + // Take a snapshot of the related localForages. + var forages = dbContext.forages.slice(0); + + // Initialize the connection process only when + // all the related localForages aren't pending. + return Promise.all(readyPromises).then(function () { + dbInfo.db = dbContext.db; + // Get the connection or open a new one without upgrade. + return _getOriginalConnection(dbInfo); + }).then(function (db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function (db) { + dbInfo.db = dbContext.db = db; + self._dbInfo = dbInfo; + // Share the final connection amongst related localForages. + for (var k = 0; k < forages.length; k++) { + var forage = forages[k]; + if (forage !== self) { + // Self is already up-to-date. + forage._dbInfo.db = dbInfo.db; + forage._dbInfo.version = dbInfo.version; + } + } + }); + } + + function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); + } + + function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); + } + + function _getConnection(dbInfo, upgradeNeeded) { + return new Promise(function (resolve, reject) { + if (dbInfo.db) { + if (upgradeNeeded) { + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + + var dbArgs = [dbInfo.name]; + + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + + var openreq = indexedDB.open.apply(indexedDB, dbArgs); + + if (upgradeNeeded) { + openreq.onupgradeneeded = function (e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + // Added when support for blob shims was added + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === 'ConstraintError') { + globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + + openreq.onerror = function () { + reject(openreq.error); + }; + + openreq.onsuccess = function () { + resolve(openreq.result); + }; + }); + } + + function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + + if (isDowngrade) { + // If the version is not the default one + // then warn for impossible downgrade. + if (dbInfo.version !== defaultVersion) { + globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); + } + // Align the versions to prevent errors. + dbInfo.version = dbInfo.db.version; + } + + if (isUpgrade || isNewStore) { + // If the store is new then increment the version (if needed). + // This will trigger an "upgradeneeded" event which is required + // for creating a store. + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + + return true; + } + + return false; + } + + function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + var req = store.get(key); + + req.onsuccess = function () { + var value = req.result; + if (value === undefined) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + + req.onerror = function () { + reject(req.error); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Iterate over all items stored in database. + function iterate(iterator, callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var iterationNumber = 1; + + req.onsuccess = function () { + var cursor = req.result; + + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, iterationNumber++); + + if (result !== void 0) { + resolve(result); + } else { + cursor['continue'](); + } + } else { + resolve(); + } + }; + + req.onerror = function () { + reject(req.error); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + + return promise; + } + + function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function (resolve, reject) { + var dbInfo; + self.ready().then(function () { + dbInfo = self._dbInfo; + if (value instanceof Blob) { + return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { + if (blobSupport) { + return value; + } + return _encodeBlob(value); + }); + } + return value; + }).then(function (value) { + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // The reason we don't _save_ null is because IE 10 does + // not support saving the `null` type in IndexedDB. How + // ironic, given the bug below! + // See: https://github.com/mozilla/localForage/issues/161 + if (value === null) { + value = undefined; + } + + var req = store.put(value, key); + transaction.oncomplete = function () { + // Cast to undefined so the value passed to + // callback/promise is the same as what one would get out + // of `getItem()` later. This leads to some weirdness + // (setItem('foo', undefined) will return `null`), but + // it's not my fault localStorage is our baseline and that + // it's weird. + if (value === undefined) { + value = null; + } + + resolve(value); + }; + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // We use a Grunt task to make this safe for IE and some + // versions of Android (including those used by Cordova). + // Normally IE won't like `.delete()` and will insist on + // using `['delete']()`, but we have a build step that + // fixes this for us now. + var req = store['delete'](key); + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onerror = function () { + reject(req.error); + }; + + // The request will be also be aborted if we've exceeded our storage + // space. + transaction.onabort = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function clear(callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + var req = store.clear(); + + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function length(callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + var req = store.count(); + + req.onsuccess = function () { + resolve(req.result); + }; + + req.onerror = function () { + reject(req.error); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function key(n, callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + if (n < 0) { + resolve(null); + + return; + } + + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var advanced = false; + var req = store.openCursor(); + req.onsuccess = function () { + var cursor = req.result; + if (!cursor) { + // this means there weren't enough keys + resolve(null); + + return; + } + + if (n === 0) { + // We have the first key, return it if that's what they + // wanted. + resolve(cursor.key); + } else { + if (!advanced) { + // Otherwise, ask the cursor to skip ahead n + // records. + advanced = true; + cursor.advance(n); + } else { + // When we get here, we've got the nth key. + resolve(cursor.key); + } + } + }; + + req.onerror = function () { + reject(req.error); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function keys(callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var keys = []; + + req.onsuccess = function () { + var cursor = req.result; + + if (!cursor) { + resolve(keys); + return; + } + + keys.push(cursor.key); + cursor['continue'](); + }; + + req.onerror = function () { + reject(req.error); + }; + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function executeCallback(promise, callback) { + if (callback) { + promise.then(function (result) { + callback(null, result); + }, function (error) { + callback(error); + }); + } + } + + var asyncStorage = { + _driver: 'asyncStorage', + _initStorage: _initStorage, + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys + }; + + exports['default'] = asyncStorage; + }).call(typeof window !== 'undefined' ? window : self); + module.exports = exports['default']; + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + // If IndexedDB isn't available, we'll fall back to localStorage. + // Note that this will have considerable performance and storage + // side-effects (all data will be serialized on save and only data that + // can be converted to a string via `JSON.stringify()` will be saved). + 'use strict'; + + exports.__esModule = true; + (function () { + 'use strict'; + + var globalObject = this; + var localStorage = null; + + // If the app is running inside a Google Chrome packaged webapp, or some + // other context where localStorage isn't available, we don't use + // localStorage. This feature detection is preferred over the old + // `if (window.chrome && window.chrome.runtime)` code. + // See: https://github.com/mozilla/localForage/issues/68 + try { + // If localStorage isn't available, we get outta here! + // This should be inside a try catch + if (!this.localStorage || !('setItem' in this.localStorage)) { + return; + } + // Initialize localStorage and create a variable to use throughout + // the code. + localStorage = this.localStorage; + } catch (e) { + return; + } + + // Config the localStorage backend, using options set in the config. + function _initStorage(options) { + var self = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + dbInfo.keyPrefix = dbInfo.name + '/'; + + if (dbInfo.storeName !== self._defaultConfig.storeName) { + dbInfo.keyPrefix += dbInfo.storeName + '/'; + } + + self._dbInfo = dbInfo; + + return new Promise(function (resolve, reject) { + resolve(__webpack_require__(3)); + }).then(function (lib) { + dbInfo.serializer = lib; + return Promise.resolve(); + }); + } + + // Remove all keys from the datastore, effectively destroying all data in + // the app's key/value store! + function clear(callback) { + var self = this; + var promise = self.ready().then(function () { + var keyPrefix = self._dbInfo.keyPrefix; + + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + + executeCallback(promise, callback); + return promise; + } + + // Retrieve an item from the store. Unlike the original async_storage + // library in Gaia, we don't modify return values at all. If a key's value + // is `undefined`, we pass that value to the callback function. + function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the key + // is likely undefined and we'll pass it straight to the + // callback. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; + } + + // Iterate over all items in the store. + function iterate(iterator, callback) { + var self = this; + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length = localStorage.length; + + // We use a dedicated iterator instead of the `i` variable below + // so other keys we fetch in localStorage aren't counted in + // the `iterationNumber` argument passed to the `iterate()` + // callback. + // + // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 + var iterationNumber = 1; + + for (var i = 0; i < length; i++) { + var key = localStorage.key(i); + if (key.indexOf(keyPrefix) !== 0) { + continue; + } + var value = localStorage.getItem(key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the + // key is likely undefined and we'll pass it straight + // to the iterator. + if (value) { + value = dbInfo.serializer.deserialize(value); + } + + value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); + + if (value !== void 0) { + return value; + } + } + }); + + executeCallback(promise, callback); + return promise; + } + + // Same as localStorage's key() method, except takes a callback. + function key(n, callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + + // Remove the prefix from the key, if a key is found. + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; + } + + function keys(callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var length = localStorage.length; + var keys = []; + + for (var i = 0; i < length; i++) { + if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { + keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); + } + } + + return keys; + }); + + executeCallback(promise, callback); + return promise; + } + + // Supply the number of keys in the datastore to the callback function. + function length(callback) { + var self = this; + var promise = self.keys().then(function (keys) { + return keys.length; + }); + + executeCallback(promise, callback); + return promise; + } + + // Remove an item from the store, nice and simple. + function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key); + }); + + executeCallback(promise, callback); + return promise; + } + + // Set a key's value and run an optional callback once the value is set. + // Unlike Gaia's implementation, the callback function is passed the value, + // in case you want to operate on that value only after you're sure it + // saved, or something like that. + function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + // Convert undefined values to null. + // https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + return new Promise(function (resolve, reject) { + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key, value); + resolve(originalValue); + } catch (e) { + // localStorage capacity exceeded. + // TODO: Make this a specific error/event. + if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { + reject(e); + } + reject(e); + } + } + }); + }); + }); + + executeCallback(promise, callback); + return promise; + } + + function executeCallback(promise, callback) { + if (callback) { + promise.then(function (result) { + callback(null, result); + }, function (error) { + callback(error); + }); + } + } + + var localStorageWrapper = { + _driver: 'localStorageWrapper', + _initStorage: _initStorage, + // Default API, from Gaia/localStorage. + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys + }; + + exports['default'] = localStorageWrapper; + }).call(typeof window !== 'undefined' ? window : self); + module.exports = exports['default']; + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + 'use strict'; + + exports.__esModule = true; + (function () { + 'use strict'; + + // Sadly, the best way to save binary data in WebSQL/localStorage is serializing + // it to Base64, so this is how we store it to prevent very strange errors with less + // verbose ways of binary <-> string data storage. + var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + var BLOB_TYPE_PREFIX = '~~local_forage_type~'; + var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + + var SERIALIZED_MARKER = '__lfsc__:'; + var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + + // OMG the serializations! + var TYPE_ARRAYBUFFER = 'arbf'; + var TYPE_BLOB = 'blob'; + var TYPE_INT8ARRAY = 'si08'; + var TYPE_UINT8ARRAY = 'ui08'; + var TYPE_UINT8CLAMPEDARRAY = 'uic8'; + var TYPE_INT16ARRAY = 'si16'; + var TYPE_INT32ARRAY = 'si32'; + var TYPE_UINT16ARRAY = 'ur16'; + var TYPE_UINT32ARRAY = 'ui32'; + var TYPE_FLOAT32ARRAY = 'fl32'; + var TYPE_FLOAT64ARRAY = 'fl64'; + var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + + // Get out of our habit of using `window` inline, at least. + var globalObject = this; + + // Abstracts constructing a Blob object, so it also works in older + // browsers that don't support the native Blob constructor. (i.e. + // old QtWebKit versions, at least). + function _createBlob(parts, properties) { + parts = parts || []; + properties = properties || {}; + + try { + return new Blob(parts, properties); + } catch (err) { + if (err.name !== 'TypeError') { + throw err; + } + + var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; + + var builder = new BlobBuilder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + + return builder.getBlob(properties.type); + } + } + + // Serialize a value, afterwards executing a callback (which usually + // instructs the `setItem()` callback/promise to be executed). This is how + // we store binary data with localStorage. + function serialize(value, callback) { + var valueString = ''; + if (value) { + valueString = value.toString(); + } + + // Cannot use `value instanceof ArrayBuffer` or such here, as these + // checks fail when running the tests using casper.js... + // + // TODO: See why those tests fail and use a better solution. + if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { + // Convert binary arrays to a string and prefix the string with + // a special marker. + var buffer; + var marker = SERIALIZED_MARKER; + + if (value instanceof ArrayBuffer) { + buffer = value; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value.buffer; + + if (valueString === '[object Int8Array]') { + marker += TYPE_INT8ARRAY; + } else if (valueString === '[object Uint8Array]') { + marker += TYPE_UINT8ARRAY; + } else if (valueString === '[object Uint8ClampedArray]') { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueString === '[object Int16Array]') { + marker += TYPE_INT16ARRAY; + } else if (valueString === '[object Uint16Array]') { + marker += TYPE_UINT16ARRAY; + } else if (valueString === '[object Int32Array]') { + marker += TYPE_INT32ARRAY; + } else if (valueString === '[object Uint32Array]') { + marker += TYPE_UINT32ARRAY; + } else if (valueString === '[object Float32Array]') { + marker += TYPE_FLOAT32ARRAY; + } else if (valueString === '[object Float64Array]') { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error('Failed to get type for BinaryArray')); + } + } + + callback(marker + bufferToString(buffer)); + } else if (valueString === '[object Blob]') { + // Conver the blob to a binaryArray and then to a string. + var fileReader = new FileReader(); + + fileReader.onload = function () { + // Backwards-compatible prefix for the blob type. + var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); + + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + + fileReader.readAsArrayBuffer(value); + } else { + try { + callback(JSON.stringify(value)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value); + + callback(null, e); + } + } + } + + // Deserialize data we've inserted into a value column/field. We place + // special markers into our strings to mark them as encoded; this isn't + // as nice as a meta field, but it's the only sane thing we can do whilst + // keeping localStorage support intact. + // + // Oftentimes this will just deserialize JSON content, but if we have a + // special marker (SERIALIZED_MARKER, defined above), we will extract + // some kind of arraybuffer/binary data/typed array out of the string. + function deserialize(value) { + // If we haven't marked this string as being specially serialized (i.e. + // something other than serialized JSON), we can just return it and be + // done with it. + if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value); + } + + // The following code deals with deserializing some kind of Blob or + // TypedArray. First we separate out the type of data we're dealing + // with from the data itself. + var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + + var blobType; + // Backwards-compatible blob type serialization strategy. + // DBs created with older versions of localForage will simply not have the blob type. + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + + // Return the right type based on the code/type set during + // serialization. + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return _createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error('Unkown type: ' + type); + } + } + + function stringToBuffer(serializedString) { + // Fill the string into a ArrayBuffer. + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (serializedString[serializedString.length - 1] === '=') { + bufferLength--; + if (serializedString[serializedString.length - 2] === '=') { + bufferLength--; + } + } + + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + + for (i = 0; i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + + /*jslint bitwise: true */ + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; + } + + // Converts a buffer to a string to store, serialized, in the backend + // storage library. + function bufferToString(buffer) { + // base64-arraybuffer + var bytes = new Uint8Array(buffer); + var base64String = ''; + var i; + + for (i = 0; i < bytes.length; i += 3) { + /*jslint bitwise: true */ + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + '='; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + '=='; + } + + return base64String; + } + + var localforageSerializer = { + serialize: serialize, + deserialize: deserialize, + stringToBuffer: stringToBuffer, + bufferToString: bufferToString + }; + + exports['default'] = localforageSerializer; + }).call(typeof window !== 'undefined' ? window : self); + module.exports = exports['default']; + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + /* + * Includes code from: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ + 'use strict'; + + exports.__esModule = true; + (function () { + 'use strict'; + + var globalObject = this; + var openDatabase = this.openDatabase; + + // If WebSQL methods aren't available, we can stop now. + if (!openDatabase) { + return; + } + + // Open the WebSQL database (automatically creates one if one didn't + // previously exist), using any options set in the config. + function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; + } + } + + var dbInfoPromise = new Promise(function (resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return self.setDriver(self.LOCALSTORAGE).then(function () { + return self._initStorage(options); + }).then(resolve)['catch'](reject); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function (t) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { + self._dbInfo = dbInfo; + resolve(); + }, function (t, error) { + reject(error); + }); + }); + }); + + return new Promise(function (resolve, reject) { + resolve(__webpack_require__(3)); + }).then(function (lib) { + dbInfo.serializer = lib; + return dbInfoPromise; + }); + } + + function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + + // Check to see if this is serialized content we need to + // unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + resolve(result); + }, function (t, error) { + + reject(error); + }); + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function iterate(iterator, callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { + var rows = results.rows; + var length = rows.length; + + for (var i = 0; i < length; i++) { + var item = rows.item(i); + var result = item.value; + + // Check to see if this is serialized content + // we need to unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + result = iterator(result, item.key, i + 1); + + // void(0) prevents problems with redefinition + // of `undefined`. + if (result !== void 0) { + resolve(result); + return; + } + } + + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + // The localStorage API doesn't return undefined values in an + // "expected" way, so undefined is always cast to null in all + // drivers. See: https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + dbInfo.db.transaction(function (t) { + t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { + resolve(originalValue); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + // The transaction failed; check + // to see if it's a quota error. + if (sqlError.code === sqlError.QUOTA_ERR) { + // We reject the callback outright for now, but + // it's worth trying to re-run the transaction. + // Even if the user accepts the prompt to use + // more storage on Safari, this error will + // be called. + // + // TODO: Try to re-run the transaction. + reject(sqlError); + } + }); + } + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + globalObject.console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { + resolve(); + }, function (t, error) { + + reject(error); + }); + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Deletes every item in the table. + // TODO: Find out if this resets the AUTO_INCREMENT number. + function clear(callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Does a simple `COUNT(key)` to get the number of items stored in + // localForage. + function length(callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + // Ahhh, SQL makes this one soooooo easy. + t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { + var result = results.rows.item(0).c; + + resolve(result); + }, function (t, error) { + + reject(error); + }); + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Return the key located at key index X; essentially gets the key from a + // `WHERE id = ?`. This is the most efficient way I can think to implement + // this rarely-used (in my experience) part of the API, but it can seem + // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so + // the ID of each key will change every time it's updated. Perhaps a stored + // procedure for the `setItem()` SQL would solve this problem? + // TODO: Don't change ID on `setItem()`. + function key(n, callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function keys(callback) { + var self = this; + + var promise = new Promise(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { + var keys = []; + + for (var i = 0; i < results.rows.length; i++) { + keys.push(results.rows.item(i).key); + } + + resolve(keys); + }, function (t, error) { + + reject(error); + }); + }); + })['catch'](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function executeCallback(promise, callback) { + if (callback) { + promise.then(function (result) { + callback(null, result); + }, function (error) { + callback(error); + }); + } + } + + var webSQLStorage = { + _driver: 'webSQLStorage', + _initStorage: _initStorage, + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys + }; + + exports['default'] = webSQLStorage; + }).call(typeof window !== 'undefined' ? window : self); + module.exports = exports['default']; + +/***/ } +/******/ ]) +}); +; +} \ No newline at end of file diff --git a/scripts/lib/md5.js b/scripts/lib/md5.js new file mode 100644 index 0000000..f92ba37 --- /dev/null +++ b/scripts/lib/md5.js @@ -0,0 +1,274 @@ +/* + * JavaScript MD5 1.0.1 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +/*jslint bitwise: true */ +/*global unescape, define */ + +(function ($) { + 'use strict'; + + /* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + function safe_add(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF), + msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); + } + + /* + * Bitwise rotate a 32-bit number to the left. + */ + function bit_rol(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); + } + + /* + * These functions implement the four basic operations the algorithm uses. + */ + function md5_cmn(q, a, b, x, s, t) { + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); + } + function md5_ff(a, b, c, d, x, s, t) { + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); + } + function md5_gg(a, b, c, d, x, s, t) { + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); + } + function md5_hh(a, b, c, d, x, s, t) { + return md5_cmn(b ^ c ^ d, a, b, x, s, t); + } + function md5_ii(a, b, c, d, x, s, t) { + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); + } + + /* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + function binl_md5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << (len % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var i, olda, oldb, oldc, oldd, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; + + for (i = 0; i < x.length; i += 16) { + olda = a; + oldb = b; + oldc = c; + oldd = d; + + a = md5_ff(a, b, c, d, x[i], 7, -680876936); + d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i], 20, -373897302); + a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5_hh(d, a, b, c, x[i], 11, -358537222); + c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i], 6, -198630844); + d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return [a, b, c, d]; + } + + /* + * Convert an array of little-endian words to a string + */ + function binl2rstr(input) { + var i, + output = ''; + for (i = 0; i < input.length * 32; i += 8) { + output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); + } + return output; + } + + /* + * Convert a raw string to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + function rstr2binl(input) { + var i, + output = []; + output[(input.length >> 2) - 1] = undefined; + for (i = 0; i < output.length; i += 1) { + output[i] = 0; + } + for (i = 0; i < input.length * 8; i += 8) { + output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); + } + return output; + } + + /* + * Calculate the MD5 of a raw string + */ + function rstr_md5(s) { + return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); + } + + /* + * Calculate the HMAC-MD5, of a key and some data (raw strings) + */ + function rstr_hmac_md5(key, data) { + var i, + bkey = rstr2binl(key), + ipad = [], + opad = [], + hash; + ipad[15] = opad[15] = undefined; + if (bkey.length > 16) { + bkey = binl_md5(bkey, key.length * 8); + } + for (i = 0; i < 16; i += 1) { + ipad[i] = bkey[i] ^ 0x36363636; + opad[i] = bkey[i] ^ 0x5C5C5C5C; + } + hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); + return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); + } + + /* + * Convert a raw string to a hex string + */ + function rstr2hex(input) { + var hex_tab = '0123456789abcdef', + output = '', + x, + i; + for (i = 0; i < input.length; i += 1) { + x = input.charCodeAt(i); + output += hex_tab.charAt((x >>> 4) & 0x0F) + + hex_tab.charAt(x & 0x0F); + } + return output; + } + + /* + * Encode a string as utf-8 + */ + function str2rstr_utf8(input) { + return unescape(encodeURIComponent(input)); + } + + /* + * Take string arguments and return either raw or hex encoded strings + */ + function raw_md5(s) { + return rstr_md5(str2rstr_utf8(s)); + } + function hex_md5(s) { + return rstr2hex(raw_md5(s)); + } + function raw_hmac_md5(k, d) { + return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); + } + function hex_hmac_md5(k, d) { + return rstr2hex(raw_hmac_md5(k, d)); + } + + function md5(string, key, raw) { + if (!key) { + if (!raw) { + return hex_md5(string); + } + return raw_md5(string); + } + if (!raw) { + return hex_hmac_md5(key, string); + } + return raw_hmac_md5(key, string); + } + + if (typeof define === 'function' && define.amd) { + define(function () { + return md5; + }); + } else { + $.md5 = md5; + } +}(this)); diff --git a/scripts/lib/raf.js b/scripts/lib/raf.js deleted file mode 100644 index 370894e..0000000 --- a/scripts/lib/raf.js +++ /dev/null @@ -1,31 +0,0 @@ -// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ -// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating - -// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel - -// MIT license - -(function() { - var lastTime = 0; - var vendors = ['ms', 'moz', 'webkit', 'o']; - for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { - window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; - window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] - || window[vendors[x]+'CancelRequestAnimationFrame']; - } - - if (!window.requestAnimationFrame) - window.requestAnimationFrame = function(callback, element) { - var currTime = new Date().getTime(); - var timeToCall = Math.max(0, 16 - (currTime - lastTime)); - var id = window.setTimeout(function() { callback(currTime + timeToCall); }, - timeToCall); - lastTime = currTime + timeToCall; - return id; - }; - - if (!window.cancelAnimationFrame) - window.cancelAnimationFrame = function(id) { - clearTimeout(id); - }; -}()); \ No newline at end of file diff --git a/scripts/lib/require-2.1.4.js b/scripts/lib/require.js similarity index 84% rename from scripts/lib/require-2.1.4.js rename to scripts/lib/require.js index 5b26875..5237640 100644 --- a/scripts/lib/require-2.1.4.js +++ b/scripts/lib/require.js @@ -1,5 +1,5 @@ /** vim: et:ts=4:sw=4:sts=4 - * @license RequireJS 2.1.4 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. + * @license RequireJS 2.1.20 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ @@ -12,7 +12,7 @@ var requirejs, require, define; (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, - version = '2.1.4', + version = '2.1.20', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, @@ -21,8 +21,7 @@ var requirejs, require, define; ostring = op.toString, hasOwn = op.hasOwnProperty, ap = Array.prototype, - apsp = ap.splice, - isBrowser = !!(typeof window !== 'undefined' && navigator && document), + isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, @@ -108,7 +107,10 @@ var requirejs, require, define; if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { - if (deepStringMixin && typeof value !== 'string') { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + if (!target[prop]) { target[prop] = {}; } @@ -134,7 +136,11 @@ var requirejs, require, define; return document.getElementsByTagName('script'); } - //Allow getting a global that expressed in + function defaultOnError(err) { + throw err; + } + + //Allow getting a global that is expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { @@ -173,7 +179,7 @@ var requirejs, require, define; if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { - //Do not overwrite and existing requirejs instance. + //Do not overwrite an existing requirejs instance. return; } cfg = requirejs; @@ -191,19 +197,27 @@ var requirejs, require, define; var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, + bundles: {}, pkgs: {}, shim: {}, - map: {}, config: {} }, registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, + bundlesMap = {}, requireCounter = 1, unnormalizedCounter = 1; @@ -218,20 +232,19 @@ var requirejs, require, define; */ function trimDots(ary) { var i, part; - for (i = 0; ary[i]; i += 1) { + for (i = 0; i < ary.length; i++) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { - if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { - //End of the line. Keep at least one non-dot - //path segment at the front so it can be mapped - //correctly to disk. Otherwise, there is likely - //no path mapping for a path starting with '..'. - //This can still fail, but catches the most reasonable - //uses of .. - break; + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; @@ -251,54 +264,45 @@ var requirejs, require, define; * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { - var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, - foundMap, foundI, foundStarMap, starI, - baseParts = baseName && baseName.split('/'), - normalizedBaseParts = baseParts, + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), map = config.map, starMap = map && map['*']; //Adjust any relative paths. - if (name && name.charAt(0) === '.') { - //If have a base name, try to normalize against it, - //otherwise, assume it is a top-level require that will - //be relative to baseUrl in the end. - if (baseName) { - if (getOwn(config.pkgs, baseName)) { - //If the baseName is a package name, then just treat it as one - //name to concat the name with. - normalizedBaseParts = baseParts = [baseName]; - } else { - //Convert baseName to array, and lop off the last part, - //so that . matches that 'directory' and not name of the baseName's - //module. For instance, baseName of 'one/two/three', maps to - //'one/two/three.js', but we want the directory, 'one/two' for - //this normalization. - normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); - } + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; - name = normalizedBaseParts.concat(name.split('/')); - trimDots(name); - - //Some use of packages may use a . path to reference the - //'main' module name, so normalize for that. - pkgConfig = getOwn(config.pkgs, (pkgName = name[0])); - name = name.join('/'); - if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { - name = pkgName; - } - } else if (name.indexOf('./') === 0) { - // No baseName, so this is ID is resolved relative - // to baseUrl, pull off the leading dot. - name = name.substring(2); + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); } //Apply map config if available. - if (applyMap && (baseParts || starMap) && map) { + if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); - for (i = nameParts.length; i > 0; i -= 1) { + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { @@ -315,16 +319,12 @@ var requirejs, require, define; //Match, update name to the new value. foundMap = mapValue; foundI = i; - break; + break outerLoop; } } } } - if (foundMap) { - break; - } - //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. @@ -345,7 +345,11 @@ var requirejs, require, define; } } - return name; + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; } function removeScript(name) { @@ -363,12 +367,17 @@ var requirejs, require, define; function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { - removeScript(id); //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); - context.require([id]); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + return true; } } @@ -434,7 +443,16 @@ var requirejs, require, define; return normalize(name, parentName, applyMap); }); } else { - normalizedName = normalize(name, parentName, applyMap); + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; } } else { //A regular module. @@ -494,7 +512,12 @@ var requirejs, require, define; fn(defined[id]); } } else { - getModule(depMap).on(name, fn); + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); + } } } @@ -530,11 +553,13 @@ var requirejs, require, define; function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { - //Array splice in the values since the context code has a - //local var ref to defQueue, so cannot just reassign the one - //on context. - apsp.apply(defQueue, - [defQueue.length - 1, 0].concat(globalDefQueue)); + each(globalDefQueue, function(queueItem) { + var id = queueItem[0]; + if (typeof id === 'string') { + context.defQueueMap[id] = true; + } + defQueue.push(queueItem); + }); globalDefQueue = []; } } @@ -551,7 +576,7 @@ var requirejs, require, define; mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { - return mod.exports; + return (defined[mod.map.id] = mod.exports); } else { return (mod.exports = defined[mod.map.id] = {}); } @@ -565,9 +590,9 @@ var requirejs, require, define; id: mod.map.id, uri: mod.map.url, config: function () { - return (config.config && getOwn(config.config, mod.map.id)) || {}; + return getOwn(config.config, mod.map.id) || {}; }, - exports: defined[mod.map.id] + exports: mod.exports || (mod.exports = {}) }); } } @@ -576,6 +601,7 @@ var requirejs, require, define; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; + delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { @@ -607,7 +633,7 @@ var requirejs, require, define; } function checkLoaded() { - var map, modId, err, usingPathFallback, + var err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), @@ -624,9 +650,9 @@ var requirejs, require, define; inCheckLoaded = true; //Figure out the state of all the modules. - eachProp(registry, function (mod) { - map = mod.map; - modId = map.id; + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { @@ -805,7 +831,7 @@ var requirejs, require, define; }, /** - * Checks is the module is ready to define itself, and if so, + * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { @@ -820,7 +846,10 @@ var requirejs, require, define; factory = this.factory; if (!this.inited) { - this.fetch(); + // Only fetch if not already in the defQueue. + if (!hasProp(context.defQueueMap, id)) { + this.fetch(); + } } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { @@ -833,8 +862,13 @@ var requirejs, require, define; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing - //to that instead of throwing an error. - if (this.events.error) { + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //errbacks should not be called for failures in + //their callbacks (#699). However if a global + //onError is set, use that. + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { @@ -844,17 +878,14 @@ var requirejs, require, define; exports = context.execCb(id, factory, depExports, exports); } - if (this.map.isDefine) { - //If setting exports via 'module' is in play, - //favor that over return value and exports. After that, - //favor a non-undefined return value over exports use. + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { cjsModule = this.module; - if (cjsModule && - cjsModule.exports !== undefined && - //Make sure it is not already the exports value - cjsModule.exports !== this.exports) { + if (cjsModule) { exports = cjsModule.exports; - } else if (exports === undefined && this.usingExports) { + } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } @@ -862,8 +893,8 @@ var requirejs, require, define; if (err) { err.requireMap = this.map; - err.requireModules = [this.map.id]; - err.requireType = 'define'; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; return onError((this.error = err)); } @@ -883,7 +914,7 @@ var requirejs, require, define; } //Clean up - delete registry[id]; + cleanRegistry(id); this.defined = true; } @@ -914,6 +945,7 @@ var requirejs, require, define; on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, + bundleId = getOwn(bundlesMap, this.map.id), name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { @@ -959,6 +991,14 @@ var requirejs, require, define; return; } + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true @@ -1049,6 +1089,7 @@ var requirejs, require, define; }, enable: function () { + enabledRegistry[this.map.id] = this; this.enabled = true; //Set flag mentioning that the module is enabling, @@ -1080,12 +1121,22 @@ var requirejs, require, define; this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { + if (this.undefed) { + return; + } this.defineDep(i, depExports); this.check(); })); if (this.errback) { - on(depMap, 'error', this.errback); + on(depMap, 'error', bind(this, this.errback)); + } else if (this.events.error) { + // No direct errback on this module, but something + // else is listening for errors, so be sure to + // propagate the error correctly. + on(depMap, 'error', bind(this, function(err) { + this.emit('error', err); + })); } } @@ -1189,13 +1240,15 @@ var requirejs, require, define; while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { - return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } + context.defQueueMap = {}; } context = { @@ -1205,9 +1258,11 @@ var requirejs, require, define; defined: defined, urlFetched: urlFetched, defQueue: defQueue, + defQueueMap: {}, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, + onError: onError, /** * Set a configuration for the context. @@ -1221,28 +1276,38 @@ var requirejs, require, define; } } - //Save off the paths and packages since they require special processing, + //Save off the paths since they require special processing, //they are additive. - var pkgs = config.pkgs, - shim = config.shim, + var shim = config.shim, objs = { paths: true, + bundles: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { - if (prop === 'map') { - mixin(config[prop], value, true, true); - } else { - mixin(config[prop], value, true); + if (!config[prop]) { + config[prop] = {}; } + mixin(config[prop], value, true, true); } else { config[prop] = value; } }); + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { @@ -1263,29 +1328,25 @@ var requirejs, require, define; //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { - var location; + var location, name; - pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; + pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; + + name = pkgObj.name; location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } - //Create a brand new object on pkgs, since currentPackages can - //be passed in again, and config.pkgs is the internal transformed - //state for all package configs. - pkgs[pkgObj.name] = { - name: pkgObj.name, - location: location || pkgObj.name, - //Remove leading dot in main, so main paths are normalized, - //and remove any trailing .js, since different package - //envs have different conventions: some use a module name, - //some use a file name. - main: (pkgObj.main || 'main') - .replace(currDirRegExp, '') - .replace(jsSuffixRegExp, '') - }; + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); }); - - //Done with modifications, assing packages back to context config - config.pkgs = pkgs; } //If there are any "waiting to execute" modules in the registry, @@ -1296,7 +1357,7 @@ var requirejs, require, define; //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { - mod.map = makeModuleMap(id); + mod.map = makeModuleMap(id, null, true); } }); @@ -1345,7 +1406,7 @@ var requirejs, require, define; //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { - return req.get(context, deps, relMap); + return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. @@ -1396,7 +1457,7 @@ var requirejs, require, define; * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { - var ext, url, + var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; @@ -1408,9 +1469,8 @@ var requirejs, require, define; moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } - url = context.nameToUrl(normalize(moduleNamePlusExt, - relMap && relMap.id, true), ext || '.fake'); - return ext ? url : url.substring(0, url.length - 5); + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); }, defined: function (id) { @@ -1433,10 +1493,23 @@ var requirejs, require, define; var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); + mod.undefed = true; + removeScript(id); + delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if (args[0] === id) { + defQueue.splice(i, 1); + } + }); + delete context.defQueueMap[id]; + if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded @@ -1456,7 +1529,7 @@ var requirejs, require, define; /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, - * is passed in for context, when this method is overriden by + * is passed in for context, when this method is overridden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { @@ -1497,6 +1570,7 @@ var requirejs, require, define; callGetModule(args); } + context.defQueueMap = {}; //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. @@ -1529,9 +1603,20 @@ var requirejs, require, define; * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ - nameToUrl: function (moduleName, ext) { - var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, - parentPath; + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) @@ -1545,7 +1630,6 @@ var requirejs, require, define; } else { //A module that needs to be converted to a path. paths = config.paths; - pkgs = config.pkgs; syms = moduleName.split('/'); //For each module name segment, see if there is a path @@ -1553,7 +1637,7 @@ var requirejs, require, define; //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); - pkg = getOwn(pkgs, parentModule); + parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, @@ -1563,22 +1647,12 @@ var requirejs, require, define; } syms.splice(0, i, parentPath); break; - } else if (pkg) { - //If module name is just the package name, then looking - //for the main module. - if (moduleName === pkg.name) { - pkgPath = pkg.location + '/' + pkg.main; - } else { - pkgPath = pkg.location; - } - syms.splice(0, i, pkgPath); - break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); - url += (ext || (/\?/.test(url) ? '' : '.js')); + url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } @@ -1594,7 +1668,7 @@ var requirejs, require, define; }, /** - * Executes a module callack function. Broken out as a separate function + * Executes a module callback function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * @@ -1632,7 +1706,7 @@ var requirejs, require, define; onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { - return onError(makeError('scripterror', 'Script error', evt, [data.id])); + return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); } } }; @@ -1761,8 +1835,19 @@ var requirejs, require, define; * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ - req.onError = function (err) { - throw err; + req.onError = defaultOnError; + + /** + * Creates the node for the load command. Only used in browser envs. + */ + req.createNode = function (config, moduleName, url) { + var node = config.xhtml ? + document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : + document.createElement('script'); + node.type = config.scriptType || 'text/javascript'; + node.charset = 'utf-8'; + node.async = true; + return node; }; /** @@ -1779,12 +1864,10 @@ var requirejs, require, define; node; if (isBrowser) { //In the browser so use a script tag - node = config.xhtml ? - document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : - document.createElement('script'); - node.type = config.scriptType || 'text/javascript'; - node.charset = 'utf-8'; - node.async = true; + node = req.createNode(config, moduleName, url); + if (config.onNodeCreated) { + config.onNodeCreated(node, config, moduleName, url); + } node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); @@ -1817,7 +1900,7 @@ var requirejs, require, define; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before - //the error handler, so that does not help. If addEvenListener + //the error handler, so that does not help. If addEventListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, @@ -1846,16 +1929,24 @@ var requirejs, require, define; return node; } else if (isWebWorker) { - //In a web worker, use importScripts. This is not a very - //efficient use of importScripts, importScripts will block until - //its script is downloaded and evaluated. However, if web workers - //are in play, the expectation that a build has been done so that - //only one script needs to be loaded anyway. This may need to be - //reevaluated if other use cases become common. - importScripts(url); + try { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation that a build has been done so that + //only one script needs to be loaded anyway. This may need to be + //reevaluated if other use cases become common. + importScripts(url); - //Account for anonymous modules - context.completeLoad(moduleName); + //Account for anonymous modules + context.completeLoad(moduleName); + } catch (e) { + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); + } } }; @@ -1873,7 +1964,7 @@ var requirejs, require, define; } //Look for a data-main script attribute, which could also adjust the baseUrl. - if (isBrowser) { + if (isBrowser && !cfg.skipDataMain) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by @@ -1887,24 +1978,31 @@ var requirejs, require, define; //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { + //Preserve dataMain in case it is a path (i.e. contains '?') + mainScript = dataMain; + //Set final baseUrl if there is not already an explicit one. if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. - src = dataMain.split('/'); + src = mainScript.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; - dataMain = mainScript; } - //Strip off any trailing .js since dataMain is now + //Strip off any trailing .js since mainScript is now //like a module name. - dataMain = dataMain.replace(jsSuffixRegExp, ''); + mainScript = mainScript.replace(jsSuffixRegExp, ''); + + //If mainScript is still a path, fall back to dataMain + if (req.jsExtRegExp.test(mainScript)) { + mainScript = dataMain; + } //Put the data-main script in the files to load. - cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain]; + cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; return true; } @@ -1932,12 +2030,13 @@ var requirejs, require, define; //This module may not have dependencies if (!isArray(deps)) { callback = deps; - deps = []; + deps = null; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. - if (!deps.length && isFunction(callback)) { + if (!deps && isFunction(callback)) { + deps = []; //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. @@ -1976,14 +2075,18 @@ var requirejs, require, define; //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. - (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); + if (context) { + context.defQueue.push([name, deps, callback]); + context.defQueueMap[name] = true; + } else { + globalDefQueue.push([name, deps, callback]); + } }; define.amd = { jQuery: true }; - /** * Executes the text. Normally just uses eval, but can be modified * to use a better, environment-specific call. Only used for transpiling diff --git a/scripts/lib/reqwest.js b/scripts/lib/reqwest.js new file mode 100644 index 0000000..4def3bc --- /dev/null +++ b/scripts/lib/reqwest.js @@ -0,0 +1,632 @@ +/*! + * Reqwest! A general purpose XHR connection manager + * license MIT (c) Dustin Diaz 2015 + * https://github.com/ded/reqwest + */ + +!function (name, context, definition) { + if (typeof module != 'undefined' && module.exports) module.exports = definition() + else if (typeof define == 'function' && define.amd) define(definition) + else context[name] = definition() +}('reqwest', this, function () { + + var context = this + + if ('window' in context) { + var doc = document + , byTag = 'getElementsByTagName' + , head = doc[byTag]('head')[0] + } else { + var XHR2 + try { + // prevent browserify including xhr2 + var xhr2 = 'xhr2' + XHR2 = require(xhr2) + } catch (ex) { + throw new Error('Peer dependency `xhr2` required! Please npm install xhr2') + } + } + + + var httpsRe = /^http/ + , protocolRe = /(^\w+):\/\// + , twoHundo = /^(20\d|1223)$/ //http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + , readyState = 'readyState' + , contentType = 'Content-Type' + , requestedWith = 'X-Requested-With' + , uniqid = 0 + , callbackPrefix = 'reqwest_' + (+new Date()) + , lastValue // data stored by the most recent JSONP callback + , xmlHttpRequest = 'XMLHttpRequest' + , xDomainRequest = 'XDomainRequest' + , noop = function () {} + + , isArray = typeof Array.isArray == 'function' + ? Array.isArray + : function (a) { + return a instanceof Array + } + + , defaultHeaders = { + 'contentType': 'application/x-www-form-urlencoded' + , 'requestedWith': xmlHttpRequest + , 'accept': { + '*': 'text/javascript, text/html, application/xml, text/xml, */*' + , 'xml': 'application/xml, text/xml' + , 'html': 'text/html' + , 'text': 'text/plain' + , 'json': 'application/json, text/javascript' + , 'js': 'application/javascript, text/javascript' + } + } + + , xhr = function(o) { + // is it x-domain + if (o['crossOrigin'] === true) { + var xhr = context[xmlHttpRequest] ? new XMLHttpRequest() : null + if (xhr && 'withCredentials' in xhr) { + return xhr + } else if (context[xDomainRequest]) { + return new XDomainRequest() + } else { + throw new Error('Browser does not support cross-origin requests') + } + } else if (context[xmlHttpRequest]) { + return new XMLHttpRequest() + } else if (XHR2) { + return new XHR2() + } else { + return new ActiveXObject('Microsoft.XMLHTTP') + } + } + , globalSetupOptions = { + dataFilter: function (data) { + return data + } + } + + function succeed(r) { + var protocol = protocolRe.exec(r.url) + protocol = (protocol && protocol[1]) || context.location.protocol + return httpsRe.test(protocol) ? twoHundo.test(r.request.status) : !!r.request.response + } + + function handleReadyState(r, success, error) { + return function () { + // use _aborted to mitigate against IE err c00c023f + // (can't read props on aborted request objects) + if (r._aborted) return error(r.request) + if (r._timedOut) return error(r.request, 'Request is aborted: timeout') + if (r.request && r.request[readyState] == 4) { + r.request.onreadystatechange = noop + if (succeed(r)) success(r.request) + else + error(r.request) + } + } + } + + function setHeaders(http, o) { + var headers = o['headers'] || {} + , h + + headers['Accept'] = headers['Accept'] + || defaultHeaders['accept'][o['type']] + || defaultHeaders['accept']['*'] + + var isAFormData = typeof FormData === 'function' && (o['data'] instanceof FormData); + // breaks cross-origin requests with legacy browsers + if (!o['crossOrigin'] && !headers[requestedWith]) headers[requestedWith] = defaultHeaders['requestedWith'] + if (!headers[contentType] && !isAFormData) headers[contentType] = o['contentType'] || defaultHeaders['contentType'] + for (h in headers) + headers.hasOwnProperty(h) && 'setRequestHeader' in http && http.setRequestHeader(h, headers[h]) + } + + function setCredentials(http, o) { + if (typeof o['withCredentials'] !== 'undefined' && typeof http.withCredentials !== 'undefined') { + http.withCredentials = !!o['withCredentials'] + } + } + + function generalCallback(data) { + lastValue = data + } + + function urlappend (url, s) { + return url + (/\?/.test(url) ? '&' : '?') + s + } + + function handleJsonp(o, fn, err, url) { + var reqId = uniqid++ + , cbkey = o['jsonpCallback'] || 'callback' // the 'callback' key + , cbval = o['jsonpCallbackName'] || reqwest.getcallbackPrefix(reqId) + , cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)') + , match = url.match(cbreg) + , script = doc.createElement('script') + , loaded = 0 + , isIE10 = navigator.userAgent.indexOf('MSIE 10.0') !== -1 + + if (match) { + if (match[3] === '?') { + url = url.replace(cbreg, '$1=' + cbval) // wildcard callback func name + } else { + cbval = match[3] // provided callback func name + } + } else { + url = urlappend(url, cbkey + '=' + cbval) // no callback details, add 'em + } + + context[cbval] = generalCallback + + script.type = 'text/javascript' + script.src = url + script.async = true + if (typeof script.onreadystatechange !== 'undefined' && !isIE10) { + // need this for IE due to out-of-order onreadystatechange(), binding script + // execution to an event listener gives us control over when the script + // is executed. See http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html + script.htmlFor = script.id = '_reqwest_' + reqId + } + + script.onload = script.onreadystatechange = function () { + if ((script[readyState] && script[readyState] !== 'complete' && script[readyState] !== 'loaded') || loaded) { + return false + } + script.onload = script.onreadystatechange = null + script.onclick && script.onclick() + // Call the user callback with the last value stored and clean up values and scripts. + fn(lastValue) + lastValue = undefined + head.removeChild(script) + loaded = 1 + } + + // Add the script to the DOM head + head.appendChild(script) + + // Enable JSONP timeout + return { + abort: function () { + script.onload = script.onreadystatechange = null + err({}, 'Request is aborted: timeout', {}) + lastValue = undefined + head.removeChild(script) + loaded = 1 + } + } + } + + function getRequest(fn, err) { + var o = this.o + , method = (o['method'] || 'GET').toUpperCase() + , url = typeof o === 'string' ? o : o['url'] + // convert non-string objects to query-string form unless o['processData'] is false + , data = (o['processData'] !== false && o['data'] && typeof o['data'] !== 'string') + ? reqwest.toQueryString(o['data']) + : (o['data'] || null) + , http + , sendWait = false + + // if we're working on a GET request and we have data then we should append + // query string to end of URL and not post data + if ((o['type'] == 'jsonp' || method == 'GET') && data) { + url = urlappend(url, data) + data = null + } + + if (o['type'] == 'jsonp') return handleJsonp(o, fn, err, url) + + // get the xhr from the factory if passed + // if the factory returns null, fall-back to ours + http = (o.xhr && o.xhr(o)) || xhr(o) + + http.open(method, url, o['async'] === false ? false : true) + setHeaders(http, o) + setCredentials(http, o) + if (context[xDomainRequest] && http instanceof context[xDomainRequest]) { + http.onload = fn + http.onerror = err + // NOTE: see + // http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e + http.onprogress = function() {} + sendWait = true + } else { + http.onreadystatechange = handleReadyState(this, fn, err) + } + o['before'] && o['before'](http) + if (sendWait) { + setTimeout(function () { + http.send(data) + }, 200) + } else { + http.send(data) + } + return http + } + + function Reqwest(o, fn) { + this.o = o + this.fn = fn + + init.apply(this, arguments) + } + + function setType(header) { + // json, javascript, text/plain, text/html, xml + if (header === null) return undefined; //In case of no content-type. + if (header.match('json')) return 'json' + if (header.match('javascript')) return 'js' + if (header.match('text')) return 'html' + if (header.match('xml')) return 'xml' + } + + function init(o, fn) { + + this.url = typeof o == 'string' ? o : o['url'] + this.timeout = null + + // whether request has been fulfilled for purpose + // of tracking the Promises + this._fulfilled = false + // success handlers + this._successHandler = function(){} + this._fulfillmentHandlers = [] + // error handlers + this._errorHandlers = [] + // complete (both success and fail) handlers + this._completeHandlers = [] + this._erred = false + this._responseArgs = {} + + var self = this + + fn = fn || function () {} + + if (o['timeout']) { + this.timeout = setTimeout(function () { + timedOut() + }, o['timeout']) + } + + if (o['success']) { + this._successHandler = function () { + o['success'].apply(o, arguments) + } + } + + if (o['error']) { + this._errorHandlers.push(function () { + o['error'].apply(o, arguments) + }) + } + + if (o['complete']) { + this._completeHandlers.push(function () { + o['complete'].apply(o, arguments) + }) + } + + function complete (resp) { + o['timeout'] && clearTimeout(self.timeout) + self.timeout = null + while (self._completeHandlers.length > 0) { + self._completeHandlers.shift()(resp) + } + } + + function success (resp) { + var type = o['type'] || resp && setType(resp.getResponseHeader('Content-Type')) // resp can be undefined in IE + resp = (type !== 'jsonp') ? self.request : resp + // use global data filter on response text + var filteredResponse = globalSetupOptions.dataFilter(resp.responseText, type) + , r = filteredResponse + try { + resp.responseText = r + } catch (e) { + // can't assign this in IE<=8, just ignore + } + if (r) { + switch (type) { + case 'json': + try { + resp = context.JSON ? context.JSON.parse(r) : eval('(' + r + ')') + } catch (err) { + return error(resp, 'Could not parse JSON in response', err) + } + break + case 'js': + resp = eval(r) + break + case 'html': + resp = r + break + case 'xml': + resp = resp.responseXML + && resp.responseXML.parseError // IE trololo + && resp.responseXML.parseError.errorCode + && resp.responseXML.parseError.reason + ? null + : resp.responseXML + break + } + } + + self._responseArgs.resp = resp + self._fulfilled = true + fn(resp) + self._successHandler(resp) + while (self._fulfillmentHandlers.length > 0) { + resp = self._fulfillmentHandlers.shift()(resp) + } + + complete(resp) + } + + function timedOut() { + self._timedOut = true + self.request.abort() + } + + function error(resp, msg, t) { + resp = self.request + self._responseArgs.resp = resp + self._responseArgs.msg = msg + self._responseArgs.t = t + self._erred = true + while (self._errorHandlers.length > 0) { + self._errorHandlers.shift()(resp, msg, t) + } + complete(resp) + } + + this.request = getRequest.call(this, success, error) + } + + Reqwest.prototype = { + abort: function () { + this._aborted = true + this.request.abort() + } + + , retry: function () { + init.call(this, this.o, this.fn) + } + + /** + * Small deviation from the Promises A CommonJs specification + * http://wiki.commonjs.org/wiki/Promises/A + */ + + /** + * `then` will execute upon successful requests + */ + , then: function (success, fail) { + success = success || function () {} + fail = fail || function () {} + if (this._fulfilled) { + this._responseArgs.resp = success(this._responseArgs.resp) + } else if (this._erred) { + fail(this._responseArgs.resp, this._responseArgs.msg, this._responseArgs.t) + } else { + this._fulfillmentHandlers.push(success) + this._errorHandlers.push(fail) + } + return this + } + + /** + * `always` will execute whether the request succeeds or fails + */ + , always: function (fn) { + if (this._fulfilled || this._erred) { + fn(this._responseArgs.resp) + } else { + this._completeHandlers.push(fn) + } + return this + } + + /** + * `fail` will execute when the request fails + */ + , fail: function (fn) { + if (this._erred) { + fn(this._responseArgs.resp, this._responseArgs.msg, this._responseArgs.t) + } else { + this._errorHandlers.push(fn) + } + return this + } + , 'catch': function (fn) { + return this.fail(fn) + } + } + + function reqwest(o, fn) { + return new Reqwest(o, fn) + } + + // normalize newline variants according to spec -> CRLF + function normalize(s) { + return s ? s.replace(/\r?\n/g, '\r\n') : '' + } + + function serial(el, cb) { + var n = el.name + , t = el.tagName.toLowerCase() + , optCb = function (o) { + // IE gives value="" even where there is no value attribute + // 'specified' ref: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-862529273 + if (o && !o['disabled']) + cb(n, normalize(o['attributes']['value'] && o['attributes']['value']['specified'] ? o['value'] : o['text'])) + } + , ch, ra, val, i + + // don't serialize elements that are disabled or without a name + if (el.disabled || !n) return + + switch (t) { + case 'input': + if (!/reset|button|image|file/i.test(el.type)) { + ch = /checkbox/i.test(el.type) + ra = /radio/i.test(el.type) + val = el.value + // WebKit gives us "" instead of "on" if a checkbox has no value, so correct it here + ;(!(ch || ra) || el.checked) && cb(n, normalize(ch && val === '' ? 'on' : val)) + } + break + case 'textarea': + cb(n, normalize(el.value)) + break + case 'select': + if (el.type.toLowerCase() === 'select-one') { + optCb(el.selectedIndex >= 0 ? el.options[el.selectedIndex] : null) + } else { + for (i = 0; el.length && i < el.length; i++) { + el.options[i].selected && optCb(el.options[i]) + } + } + break + } + } + + // collect up all form elements found from the passed argument elements all + // the way down to child elements; pass a '
' or form fields. + // called with 'this'=callback to use for serial() on each element + function eachFormElement() { + var cb = this + , e, i + , serializeSubtags = function (e, tags) { + var i, j, fa + for (i = 0; i < tags.length; i++) { + fa = e[byTag](tags[i]) + for (j = 0; j < fa.length; j++) serial(fa[j], cb) + } + } + + for (i = 0; i < arguments.length; i++) { + e = arguments[i] + if (/input|select|textarea/i.test(e.tagName)) serial(e, cb) + serializeSubtags(e, [ 'input', 'select', 'textarea' ]) + } + } + + // standard query string style serialization + function serializeQueryString() { + return reqwest.toQueryString(reqwest.serializeArray.apply(null, arguments)) + } + + // { 'name': 'value', ... } style serialization + function serializeHash() { + var hash = {} + eachFormElement.apply(function (name, value) { + if (name in hash) { + hash[name] && !isArray(hash[name]) && (hash[name] = [hash[name]]) + hash[name].push(value) + } else hash[name] = value + }, arguments) + return hash + } + + // [ { name: 'name', value: 'value' }, ... ] style serialization + reqwest.serializeArray = function () { + var arr = [] + eachFormElement.apply(function (name, value) { + arr.push({name: name, value: value}) + }, arguments) + return arr + } + + reqwest.serialize = function () { + if (arguments.length === 0) return '' + var opt, fn + , args = Array.prototype.slice.call(arguments, 0) + + opt = args.pop() + opt && opt.nodeType && args.push(opt) && (opt = null) + opt && (opt = opt.type) + + if (opt == 'map') fn = serializeHash + else if (opt == 'array') fn = reqwest.serializeArray + else fn = serializeQueryString + + return fn.apply(null, args) + } + + reqwest.toQueryString = function (o, trad) { + var prefix, i + , traditional = trad || false + , s = [] + , enc = encodeURIComponent + , add = function (key, value) { + // If value is a function, invoke it and return its value + value = ('function' === typeof value) ? value() : (value == null ? '' : value) + s[s.length] = enc(key) + '=' + enc(value) + } + // If an array was passed in, assume that it is an array of form elements. + if (isArray(o)) { + for (i = 0; o && i < o.length; i++) add(o[i]['name'], o[i]['value']) + } else { + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for (prefix in o) { + if (o.hasOwnProperty(prefix)) buildParams(prefix, o[prefix], traditional, add) + } + } + + // spaces should be + according to spec + return s.join('&').replace(/%20/g, '+') + } + + function buildParams(prefix, obj, traditional, add) { + var name, i, v + , rbracket = /\[\]$/ + + if (isArray(obj)) { + // Serialize array item. + for (i = 0; obj && i < obj.length; i++) { + v = obj[i] + if (traditional || rbracket.test(prefix)) { + // Treat each array item as a scalar. + add(prefix, v) + } else { + buildParams(prefix + '[' + (typeof v === 'object' ? i : '') + ']', v, traditional, add) + } + } + } else if (obj && obj.toString() === '[object Object]') { + // Serialize object item. + for (name in obj) { + buildParams(prefix + '[' + name + ']', obj[name], traditional, add) + } + + } else { + // Serialize scalar item. + add(prefix, obj) + } + } + + reqwest.getcallbackPrefix = function () { + return callbackPrefix + } + + // jQuery and Zepto compatibility, differences can be remapped here so you can call + // .ajax.compat(options, callback) + // reqwest.compat = function (o, fn) { + // if (o) { + // o['type'] && (o['method'] = o['type']) && delete o['type'] + // o['dataType'] && (o['type'] = o['dataType']) + // o['jsonpCallback'] && (o['jsonpCallbackName'] = o['jsonpCallback']) && delete o['jsonpCallback'] + // o['jsonp'] && (o['jsonpCallback'] = o['jsonp']) + // } + // return new Reqwest(o, fn) + // } + + // reqwest.ajaxSetup = function (options) { + // options = options || {} + // for (var k in options) { + // globalSetupOptions[k] = options[k] + // } + // } + + return reqwest +}); diff --git a/scripts/lib/signals-1.0.0.js b/scripts/lib/signals-1.0.0.js deleted file mode 100755 index 2615d26..0000000 --- a/scripts/lib/signals-1.0.0.js +++ /dev/null @@ -1,445 +0,0 @@ -/*jslint onevar:true, undef:true, newcap:true, regexp:true, bitwise:true, maxerr:50, indent:4, white:false, nomen:false, plusplus:false */ -/*global define:false, require:false, exports:false, module:false, signals:false */ - -/** @license - * JS Signals - * Released under the MIT license - * Author: Miller Medeiros - * Version: 1.0.0 - Build: 268 (2012/11/29 05:48 PM) - */ - -(function(global){ - - // SignalBinding ------------------------------------------------- - //================================================================ - - /** - * Object that represents a binding between a Signal and a listener function. - *
- This is an internal constructor and shouldn't be called by regular users. - *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. - * @author Miller Medeiros - * @constructor - * @internal - * @name SignalBinding - * @param {Signal} signal Reference to Signal object that listener is currently bound to. - * @param {Function} listener Handler function bound to the signal. - * @param {boolean} isOnce If binding should be executed just once. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. (default = 0). - */ - function SignalBinding(signal, listener, isOnce, listenerContext, priority) { - - /** - * Handler function bound to the signal. - * @type Function - * @private - */ - this._listener = listener; - - /** - * If binding should be executed just once. - * @type boolean - * @private - */ - this._isOnce = isOnce; - - /** - * Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @memberOf SignalBinding.prototype - * @name context - * @type Object|undefined|null - */ - this.context = listenerContext; - - /** - * Reference to Signal object that listener is currently bound to. - * @type Signal - * @private - */ - this._signal = signal; - - /** - * Listener priority - * @type Number - * @private - */ - this._priority = priority || 0; - } - - SignalBinding.prototype = { - - /** - * If binding is active and should be executed. - * @type boolean - */ - active : true, - - /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) - * @type Array|null - */ - params : null, - - /** - * Call listener passing arbitrary parameters. - *

If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.

- * @param {Array} [paramsArr] Array of parameters that should be passed to the listener - * @return {*} Value returned by the listener. - */ - execute : function (paramsArr) { - var handlerReturn, params; - if (this.active && !!this._listener) { - params = this.params? this.params.concat(paramsArr) : paramsArr; - handlerReturn = this._listener.apply(this.context, params); - if (this._isOnce) { - this.detach(); - } - } - return handlerReturn; - }, - - /** - * Detach binding from signal. - * - alias to: mySignal.remove(myBinding.getListener()); - * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached. - */ - detach : function () { - return this.isBound()? this._signal.remove(this._listener, this.context) : null; - }, - - /** - * @return {Boolean} `true` if binding is still bound to the signal and have a listener. - */ - isBound : function () { - return (!!this._signal && !!this._listener); - }, - - /** - * @return {boolean} If SignalBinding will only be executed once. - */ - isOnce : function () { - return this._isOnce; - }, - - /** - * @return {Function} Handler function bound to the signal. - */ - getListener : function () { - return this._listener; - }, - - /** - * @return {Signal} Signal that listener is currently bound to. - */ - getSignal : function () { - return this._signal; - }, - - /** - * Delete instance properties - * @private - */ - _destroy : function () { - delete this._signal; - delete this._listener; - delete this.context; - }, - - /** - * @return {string} String representation of the object. - */ - toString : function () { - return '[SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; - } - - }; - - -/*global SignalBinding:false*/ - - // Signal -------------------------------------------------------- - //================================================================ - - function validateListener(listener, fnName) { - if (typeof listener !== 'function') { - throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) ); - } - } - - /** - * Custom event broadcaster - *
- inspired by Robert Penner's AS3 Signals. - * @name Signal - * @author Miller Medeiros - * @constructor - */ - function Signal() { - /** - * @type Array. - * @private - */ - this._bindings = []; - this._prevParams = null; - - // enforce dispatch to aways work on same context (#47) - var self = this; - this.dispatch = function(){ - Signal.prototype.dispatch.apply(self, arguments); - }; - } - - Signal.prototype = { - - /** - * Signals Version Number - * @type String - * @const - */ - VERSION : '1.0.0', - - /** - * If Signal should keep record of previously dispatched parameters and - * automatically execute listener during `add()`/`addOnce()` if Signal was - * already dispatched before. - * @type boolean - */ - memorize : false, - - /** - * @type boolean - * @private - */ - _shouldPropagate : true, - - /** - * If Signal is active and should broadcast events. - *

IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.

- * @type boolean - */ - active : true, - - /** - * @param {Function} listener - * @param {boolean} isOnce - * @param {Object} [listenerContext] - * @param {Number} [priority] - * @return {SignalBinding} - * @private - */ - _registerListener : function (listener, isOnce, listenerContext, priority) { - - var prevIndex = this._indexOfListener(listener, listenerContext), - binding; - - if (prevIndex !== -1) { - binding = this._bindings[prevIndex]; - if (binding.isOnce() !== isOnce) { - throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.'); - } - } else { - binding = new SignalBinding(this, listener, isOnce, listenerContext, priority); - this._addBinding(binding); - } - - if(this.memorize && this._prevParams){ - binding.execute(this._prevParams); - } - - return binding; - }, - - /** - * @param {SignalBinding} binding - * @private - */ - _addBinding : function (binding) { - //simplified insertion sort - var n = this._bindings.length; - do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); - this._bindings.splice(n + 1, 0, binding); - }, - - /** - * @param {Function} listener - * @return {number} - * @private - */ - _indexOfListener : function (listener, context) { - var n = this._bindings.length, - cur; - while (n--) { - cur = this._bindings[n]; - if (cur._listener === listener && cur.context === context) { - return n; - } - } - return -1; - }, - - /** - * Check if listener was attached to Signal. - * @param {Function} listener - * @param {Object} [context] - * @return {boolean} if Signal has the specified listener. - */ - has : function (listener, context) { - return this._indexOfListener(listener, context) !== -1; - }, - - /** - * Add a listener to the signal. - * @param {Function} listener Signal handler function. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - * @return {SignalBinding} An Object representing the binding between the Signal and listener. - */ - add : function (listener, listenerContext, priority) { - validateListener(listener, 'add'); - return this._registerListener(listener, false, listenerContext, priority); - }, - - /** - * Add listener to the signal that should be removed after first execution (will be executed only once). - * @param {Function} listener Signal handler function. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - * @return {SignalBinding} An Object representing the binding between the Signal and listener. - */ - addOnce : function (listener, listenerContext, priority) { - validateListener(listener, 'addOnce'); - return this._registerListener(listener, true, listenerContext, priority); - }, - - /** - * Remove a single listener from the dispatch queue. - * @param {Function} listener Handler function that should be removed. - * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). - * @return {Function} Listener handler function. - */ - remove : function (listener, context) { - validateListener(listener, 'remove'); - - var i = this._indexOfListener(listener, context); - if (i !== -1) { - this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal - this._bindings.splice(i, 1); - } - return listener; - }, - - /** - * Remove all listeners from the Signal. - */ - removeAll : function () { - var n = this._bindings.length; - while (n--) { - this._bindings[n]._destroy(); - } - this._bindings.length = 0; - }, - - /** - * @return {number} Number of listeners attached to the Signal. - */ - getNumListeners : function () { - return this._bindings.length; - }, - - /** - * Stop propagation of the event, blocking the dispatch to next listeners on the queue. - *

IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.

- * @see Signal.prototype.disable - */ - halt : function () { - this._shouldPropagate = false; - }, - - /** - * Dispatch/Broadcast Signal to all listeners added to the queue. - * @param {...*} [params] Parameters that should be passed to each handler. - */ - dispatch : function (params) { - if (! this.active) { - return; - } - - var paramsArr = Array.prototype.slice.call(arguments), - n = this._bindings.length, - bindings; - - if (this.memorize) { - this._prevParams = paramsArr; - } - - if (! n) { - //should come after memorize - return; - } - - bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch - this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. - - //execute all callbacks until end of the list or until a callback returns `false` or stops propagation - //reverse loop since listeners with higher priority will be added at the end of the list - do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); - }, - - /** - * Forget memorized arguments. - * @see Signal.memorize - */ - forget : function(){ - this._prevParams = null; - }, - - /** - * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). - *

IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.

- */ - dispose : function () { - this.removeAll(); - delete this._bindings; - delete this._prevParams; - }, - - /** - * @return {string} String representation of the object. - */ - toString : function () { - return '[Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; - } - - }; - - - // Namespace ----------------------------------------------------- - //================================================================ - - /** - * Signals namespace - * @namespace - * @name signals - */ - var signals = Signal; - - /** - * Custom event broadcaster - * @see Signal - */ - // alias for backwards compatibility (see #gh-44) - signals.Signal = Signal; - - - - //exports to multiple environments - if(typeof define === 'function' && define.amd){ //AMD - define(function () { return signals; }); - } else if (typeof module !== 'undefined' && module.exports){ //node - module.exports = signals; - } else { //browser - //use string because of Google closure compiler ADVANCED_MODE - /*jslint sub:true */ - global['signals'] = signals; - } - -}(this)); diff --git a/scripts/models/controlsmodel.js b/scripts/models/controlsmodel.js new file mode 100644 index 0000000..b6ddca4 --- /dev/null +++ b/scripts/models/controlsmodel.js @@ -0,0 +1,109 @@ +/*global define*/ +define( + [ 'util/object', 'util/addpublishers' ], + function ( objectHelper, addPublishers ) { + // the controlsmodel stores and manages all + // values of the input sliders + function ControlsModel ( initialValues ) { + if ( ! ( this instanceof ControlsModel ) ) { + return new ControlsModel( initialValues ); + } + + var self = this; + var publishers = addPublishers( self, [ 'update' ] ); + var limits = getLimits( initialValues ) || { }; + var values = getValues( initialValues ) || { }; + + function updateValues ( newValues ) { + if ( newValues ) { + newValues = objectHelper.getCopy( newValues ); + + var referenceValue; + var newValue; + + for ( var key in newValues ) { + limit = limits[key]; + newValue = newValues[key]; + + if ( + typeof limit !== 'undefined' && + typeof newValue === 'number' && + ! isNaN( newValue ) && + newValue >= limit.min && + newValue <= limit.max && + values[key] !== newValue + ) { + values[key] = newValue; + publishers.update.dispatch( key, values[key] ); + } + } + } + + return self; + } + + function setValue ( key, newValue ) { + if ( + typeof values[key] === 'number' && + typeof newValue === 'number' && + ! isNaN( newValue ) + ) { + values[key] = newValue; + + publishers.update.dispatch( key, values[key] ); + } + + return self; + } + + function randomizeValues () { + var randomValues = { }; + + for ( var key in limits ) { + randomValues[key] = parseInt( + Math.random() * ( limits[key].max - limits[key].min ) + limits[key].min, + 10 + ); + } + + updateValues( randomValues ); + + return self; + } + + function getValues ( vals ) { + var result = { }; + vals = vals || values; + + for ( var key in vals ) { + if ( typeof vals[key].value === 'number' ) { + result[key] = vals[key].value; + } else { + result[key] = vals[key]; + } + } + + return objectHelper.getCopy( result ); + } + + function getLimits ( vals ) { + var result = { }; + + for ( var key in vals ) { + result[key] = { + min: vals[key].min, + max: vals[key].max + }; + } + + return objectHelper.getCopy( result ); + } + + self.randomizeValues = randomizeValues; + self.setValue = setValue; + self.getValues = getValues; + } + + return ControlsModel; + } +); \ No newline at end of file diff --git a/scripts/models/glitchmodel.js b/scripts/models/glitchmodel.js new file mode 100644 index 0000000..08cec0a --- /dev/null +++ b/scripts/models/glitchmodel.js @@ -0,0 +1,81 @@ +/*global define*/ +define( + [ 'config', 'lib/glitch-canvas-with-worker', 'util/addpublishers', 'util/canvas' ], + function ( config, canvasGlitcher, addPublishers, canvasHelper ) { + // the glitchModel takes care of glitching the image and passing it along as imageData + function GlitchModel () { + if ( ! ( this instanceof GlitchModel ) ) { + return new GlitchModel(); + } + + var self = this; + var publishers = addPublishers( self, 'glitch' ); + var params = { }; + var originalImageData; + var glitchedImageData; + var thumbnailCanvas = document.createElement( 'canvas' ); + var thumbnailImg = new Image(); + var glitchTimeoutId = NaN; + + var glitcher = canvasGlitcher( config.workers.glitch ).init(); + + function updateGlitch () { + if ( params && originalImageData ) { + glitcher.glitch( originalImageData, params, glitchComplete ); + } + } + + function glitchComplete ( glitchData ) { + glitchedImageData = glitchData; + publishers.glitch.dispatch( glitchData ); + } + + function setValue ( key, newValue ) { + if ( params[key] !== newValue ) { + params[key] = newValue; + glitchTimeoutId = setTimeout( updateGlitch, 10 ); + } + } + + function setImageData ( newImageData ) { + originalImageData = newImageData; + updateGlitch() + } + + function generateImageURL ( callback, size, args ) { + if ( originalImageData ) { + size = size || { width: 50, height: 50 }; + + if ( typeof size === 'string' && size === 'original' ) { + size = { + width: glitchedImageData.width, + height: glitchedImageData.height + }; + } + + canvasHelper.resizeImage( glitchedImageData, size, function ( imageUrl ) { + args = Array.prototype.slice.call( args || [ ] ); + args.unshift( imageUrl ); + + callback.apply( callback, args ); + }, 'asDataURL' ); + } + + return self; + } + + function getImageGenerationFn ( callback, size ) { + return function () { + generateImageURL( callback, size, arguments ) + }; + } + + self.setValue = setValue; + self.setImageData = setImageData; + self.generateImageURL = generateImageURL; + self.getImageGenerationFn = getImageGenerationFn; + } + + return GlitchModel; + } +) \ No newline at end of file diff --git a/scripts/models/imagemodel.js b/scripts/models/imagemodel.js new file mode 100644 index 0000000..c24e8ba --- /dev/null +++ b/scripts/models/imagemodel.js @@ -0,0 +1,169 @@ +/*global define*/ +define( + [ 'util/browser', 'util/addpublishers', 'util/time', 'util/canvas', 'util/localizetext' ], + function ( browser, addPublishers , timeHelper, canvasHelper, loc ) { + // the imageModel loads and stores the latest open image file + // (the original, not the glitched version) and converts it into + // a imageData object + function ImageModel () { + if ( ! ( this instanceof ImageModel ) ) { + return new ImageModel(); + } + + var self = this; + var publishers = addPublishers( self, [ 'load', 'update', 'error', 'statusmessage' ] ); + + var canvasEl = document.createElement( 'canvas' ); + var ctx = canvasEl.getContext( '2d' ); + var imageEl = new Image(); + + var fileReader; + var canHandleFileImport = false; + var lastImageSrc; + var lastFileName; + + // max image import filesize in megabytes. + // because of not 100% clear base64 url size constraints + // if the uploaded image is bigger, resize + // var maxFileSize = Math.pow(1024, 2) * 1.5; + var maxFileSize = 0.8 * Math.pow( 1000, 2 ); + var isScalingDown = true; + + if ( fileReader = browser.getFeature( window, 'FileReader' ) ) { + fileReader = new fileReader(); + canHandleFileImport = true; + fileReader.addEventListener( 'load', fileLoaded ); + fileReader.addEventListener( 'error', fileLoadFailed ); + } + + imageEl.addEventListener( 'load', imageLoaded ); + imageEl.addEventListener( 'error', imageLoadFailed ); + + function loadFromFile ( file ) { + if ( canHandleFileImport ) { + lastFileName = file.name; + fileReader.readAsDataURL( file ); + } + + return self; + } + + function loadFromVideo ( videoEl ) { + clearCanvas(); + canvasEl.width = videoEl.width || videoEl.videoWidth || videoEl.clientWidth; + canvasEl.height = videoEl.height || videoEl.videoHeight || videoEl.clientHeight; + + ctx.translate( canvasEl.width, 0 ); + ctx.scale( -1, 1 ); + ctx.drawImage( videoEl, 0, 0 ); + + lastImageSrc = canvasEl.toDataURL( 'image/png' ); + lastFileName = loc( 'webcam.picture', timeHelper.dateTimeToLocalStr( new Date() ) ); + + checkImageData( ctx.getImageData( 0, 0, canvasEl.width, canvasEl.height ), publishers.load.dispatch ); + + return self; + } + + function loadFromURL ( url, fileName ) { + if ( fileName ) { + lastFileName = fileName; + } + + url = decodeURIComponent( url ); + + publishers.update.dispatch( 'img', url, fileName ); + + if ( url && imageEl.src !== url ) { + imageEl.src = ''; + lastImageSrc = url; + imageEl.src = url; + } else { + imageLoaded(); + } + + return self; + } + + function clearCanvas () { + ctx.clearRect( 0, 0, canvasEl.width, canvasEl.height ); + } + + function imageLoaded () { + var imageData = getImageData( imageEl ); + + checkImageData( imageData, publishers.load.dispatch ); + } + + function imageLoadFailed ( err ) { + publishers.error.dispatch( 'file.error.openimage', imageEl.src ); + } + + function fileLoaded ( event ) { + loadFromURL( event.target.result ); + } + + function fileLoadFailed ( error ) { + publishers.error.dispatch( 'file.error.openfile' ); + } + + function checkImageData ( imageData, callback ) { + if ( isScalingDown && imageData.data && imageData.data.length / 4 > maxFileSize ) { + var widthToHeightRatio = imageData.width / imageData.height; + var heightTiWidthRatio = imageData.height / imageData.width; + + var newWidth = Math.round( Math.sqrt( maxFileSize / widthToHeightRatio ) ); + var newHeight = Math.round( newWidth * heightTiWidthRatio ); + var newSize = { + width: newWidth, + height: newHeight + }; + + publishers.statusmessage.dispatch( 'file.message.resize' ); + + canvasHelper.resizeImage( imageData, newSize, function ( result ) { + callback( result.imageData ); + + if ( typeof result.dataURL === 'string' ) { + lastImageSrc = result.dataURL; + } + }, 'both' ); + } else { + callback( imageData ); + } + } + + function settingUpdated ( key, value ) { + if ( key === 'resizeUploadedImages' && typeof value === 'boolean' ) { + isScalingDown = value; + } + } + + function getImageData ( img ) { + clearCanvas(); + canvasEl.width = img.naturalWidth; + canvasEl.height = img.naturalHeight; + ctx.drawImage( img, 0, 0, img.naturalWidth, img.naturalHeight ); + + return ctx.getImageData( 0, 0, img.naturalWidth, img.naturalHeight ); + } + + function getLastImageSRC ( img ) { + return lastImageSrc; + } + + function getLastFileName ( img ) { + return lastFileName; + } + + self.loadFromFile = loadFromFile; + self.loadFromVideo = loadFromVideo; + self.getLastImageSRC = getLastImageSRC; + self.getLastFileName = getLastFileName; + self.loadFromURL = loadFromURL; + self.settingUpdated = settingUpdated; + } + + return ImageModel; + } +); \ No newline at end of file diff --git a/scripts/models/localisationmodel.js b/scripts/models/localisationmodel.js new file mode 100644 index 0000000..e50065a --- /dev/null +++ b/scripts/models/localisationmodel.js @@ -0,0 +1,159 @@ +/*global define*/ +define( + [ 'config', 'util/dom', 'util/object', 'util/string', 'util/addpublishers', 'lib/reqwest' ], + function ( config, domHelper, objectHelper, stringHelper, addPublishers, reqwest ) { + function LocalisationModel () { + if ( ! ( this instanceof LocalisationModel ) ) { + return new LocalisationModel(); + } + + var self = this; + + var publishers = addPublishers( self, 'error' ); + + var textElData = [ ]; + var texts = ''; + var currentLanguage = ''; + + var animationFrameId = NaN; + var languageWasLoaded = false; + + var linkOptions = { links: { newTab: true } }; + + function setLanguage ( newLanguage ) { + if ( newLanguage !== currentLanguage && newLanguage in config.availableLanguages ) { + loadLanguage( newLanguage ); + } + } + + function loadLanguage ( languageName ) { + languageWasLoaded = false; + + reqwest( { + url: config.language.dir + '/' + languageName + '.json', + type: 'json', + method: 'get', + error: function ( err, one, two ) { + // if this is the first language to load, that's really bad. + languageWasLoaded = true; + publishers.error.dispatch( 'I\'m really sorry. I failed to load the language file for ' + languageName + '. This is a serious error that makes the app very hard to use. Maybe you can try reloading?' ); + + }, + success: function ( res ) { + languageLoaded( languageName, res ); + } + } ); + } + + function languageLoaded ( newLanguageName, newTexts ) { + currentLanguage = newLanguageName; + languageWasLoaded = true; + texts = newTexts; + resetAllTexts(); + updateAllTexts(); + } + + function updateAllTexts () { + if ( languageWasLoaded ) { + cancelAnimationFrame( animationFrameId ); + + animationFrameId = requestAnimationFrame( function () { + var item; + var args; + + for ( var i = textElData.length - 1; i >= 0; i-- ) { + item = textElData[i]; + + if ( domHelper.isElement( item.el ) ) { + if ( ! item.wasUpdated ) { + if ( item.attribute === 'innerHTML' ) { + item.el.innerHTML = stringHelper.markdownToHtml( getTextForKey( item.key, item.args ), linkOptions ); + } else { + item.el[item.attribute] = getTextForKey( item.key, item.args ); + } + + item.wasUpdated = true; + } + } + else { + textElData.splice( i, 1 ); + } + } + } ); + } + } + + function resetAllTexts () { + textElData.forEach( function ( item ) { + item.wasUpdated = false; + } ); + } + + function getTextForKey ( key, args ) { + var result = ''; + + try { + result = objectHelper.getObjectByString( key, texts ); + } catch ( e ) { + if ( languageWasLoaded ) { + result = key + } + }; + + if ( args && args.length ) { + var regex; + + args.forEach( function ( arg, index ) { + regex = new RegExp( '{\\$' + ( index + 1 ) + '}' ); + result = result.replace( regex, arg ); + } ); + } + + return result; + } + + // http://mzl.la/1RDxjVO + function getArgs ( args, firstIndex ) { + firstIndex = firstIndex || 3; + var result; + + if ( args.length > firstIndex ) { + result = [ ]; + } + + for ( var i = firstIndex, len = args.length; i < len; i++ ) { + result[result.length] = args[i]; + } + + return result; + } + + function settingUpdated ( name, value ) { + if ( name === 'language' && value !== currentLanguage ) { + loadLanguage( value ); + } + } + + function localizeText ( el, attribute, key ) { + if ( el && attribute && key ) { + textElData.push( { el: el, attribute: attribute, key: key, wasUpdated: false, args: getArgs( arguments ) } ); + } else { + if ( typeof el === 'string' ) { + return getTextForKey( el, getArgs( arguments, 1 ) ); + } + } + + updateAllTexts(); + } + + self.setLanguage = setLanguage; + self.localizeText = localizeText; + self.settingUpdated = settingUpdated; + self.randomNumber = ~~( Math.random() * 1000 ); + } + + LocalisationModel.sharedInstance = LocalisationModel(); + + return LocalisationModel; + } +); \ No newline at end of file diff --git a/scripts/models/networkmodel.js b/scripts/models/networkmodel.js new file mode 100644 index 0000000..f11fb7c --- /dev/null +++ b/scripts/models/networkmodel.js @@ -0,0 +1,39 @@ +/*global define*/ +define( + [ 'util/addpublishers' ], + function ( addPublishers ) { + // the NetworkModel updates the app if the device connectivity changed + function NetworkModel () { + if ( ! ( this instanceof NetworkModel ) ) { + return new NetworkModel(); + } + + var self = this; + var publishers = addPublishers( self, 'connectivitychange', 'disconnect', 'connect' ); + var isConnected; + + window.addEventListener( 'online', checkConnectivity ); + window.addEventListener( 'offline', checkConnectivity ); + + function checkConnectivity () { + if ( navigator.onLine !== isConnected ) { + isConnected = navigator.onLine; + + publishers.connectivitychange.dispatch( isConnected ); + + if ( isConnected ) { + publishers.connect.dispatch(); + } else { + publishers.disconnect.dispatch(); + } + } + + return self; + } + + self.checkConnectivity = checkConnectivity; + } + + return NetworkModel; + } +); \ No newline at end of file diff --git a/scripts/models/settingsmodel.js b/scripts/models/settingsmodel.js new file mode 100644 index 0000000..0d7469f --- /dev/null +++ b/scripts/models/settingsmodel.js @@ -0,0 +1,178 @@ +/*global define*/ +define( + [ 'config', 'util/browser', 'util/object', 'util/addpublishers', 'lib/localforage.nopromises' ], + function ( config, browser, objectHelper, addPublishers, localforage ) { + function SettingsModel ( storageKey ) { + if ( ! ( this instanceof SettingsModel ) ) { + return new SettingsModel( storageKey ); + } + + var self = this; + var publisherNames = [ 'update', 'error' ]; + var publishers = addPublishers( self, publisherNames ); + var useLocalForage = browser.test( 'localforage' ) && localforage; + var worker; + var defaultSettings = config.settings; + var userLanguage = ( navigator.language || navigator.userLanguage || '' ).toLowerCase(); + + if ( userLanguage !== '' && defaultSettings.language.options.indexOf( userLanguage ) > -1 ) { + defaultSettings.language.value = userLanguage; + } + + var settings = { }; + + storageKey = storageKey || 'settings'; + + if ( useLocalForage && browser.test( 'webworker' ) && browser.test( 'browserdb' ) && ! browser.test( 'safari' ) ) { + worker = new Worker( config.workers.settings ); + worker.addEventListener( 'message', workerResponded, false ); + sendMessageToWorker( 'setStorageKey', storageKey ); + sendMessageToWorker( 'setDefaultSettings', defaultSettings ); + } else { + settingsUpdated( defaultSettings ); + } + + function getSetting ( key ) { + return settings[key]; + } + + function getSettingValue ( key ) { + var setting = getSetting( key ); + + if ( setting ) { + return setting.value; + } else { + return; + } + } + + function getSettings () { + return objectHelper.getCopy( settings ); + } + + function setValue ( key, value ) { + var wasUpdated = false; + + if ( + typeof key === 'string' && + typeof settings[key] !== 'undefined' && + typeof value === typeof settings[key].value && + value !== settings[key].value + ) { + settings[key].value = value; + wasUpdated = true; + } + + if ( wasUpdated ) { + if ( useLocalForage ) { + save( settings ); + } else { + settingsUpdated( settings ); + } + } + + return self; + } + + function save ( newSettings ) { + if ( useLocalForage ) { + if ( worker ) { + sendMessageToWorker( 'save', newSettings ); + } else { + localforage.setItem( storageKey, newSettings, function ( err, savedSettings ) { + if ( err ) { + sendError( 'settings.error.save' ); + console && console.log( 'localforage error', err ); + } else { + if ( savedSettings ) { + settingsUpdated( savedSettings ); + } else { + console && console.log( 'no data was saved', savedSettings ); + } + } + } ); + } + } + } + + function load () { + if ( useLocalForage ) { + if ( worker ) { + sendMessageToWorker( 'load' ); + } else { + localforage.getItem( storageKey, function ( err, loadedSettings ) { + if ( err ) { + sendError( 'settings.error.load' ); + console && console.log( 'localforage error', err ); + } else { + settingsUpdated( loadedSettings ); + } + } ); + } + } else { + settingsUpdated( settings || defaultSettings ); + } + } + + function sendMessageToWorker ( type, data ) { + if ( typeof type === 'string' ) { + if ( typeof data === 'undefined' ) { + data = type; + } + + var message = { }; + message[type] = data; + worker.postMessage( message ); + } + } + + function workerResponded ( event ) { + if ( event && event.data ) { + publisherNames.forEach( function ( type ) { + if ( typeof event.data[type] !== 'undefined' ) { + if ( type === 'update' ) { + settingsUpdated( event.data[type] ); + } else { + if ( publishers[type] === type ) { + publishers[type].dispatch() + } else { + publishers[type].dispatch( event.data[type] ) + } + } + } + } ); + } + } + + function settingsUpdated ( newSettings ) { + if ( newSettings ) { + settings = newSettings || defaultSettings; + + if ( settings !== defaultSettings ) { + for ( var name in defaultSettings ) { + if ( ! settings[name] ) { + settings[name] = defaultSettings[name]; + } + } + } + + for ( var name in settings ) { + publishers.update.dispatch( name, settings[name].value, settings[name].options ); + } + + } else { + settings = defaultSettings; + save( settings ); + } + } + + self.getSetting = getSetting; + self.getSettingValue = getSettingValue; + self.getSettings = getSettings; + self.setValue = setValue; + self.load = load; + } + + return SettingsModel; + } +); \ No newline at end of file diff --git a/scripts/models/sharemodel.js b/scripts/models/sharemodel.js new file mode 100644 index 0000000..b7e92f6 --- /dev/null +++ b/scripts/models/sharemodel.js @@ -0,0 +1,107 @@ +/*global define*/ +define( + [ 'config', 'lib/reqwest', 'util/addpublishers' ], + function ( config, reqwest, addPublishers ) { + // the ShareModel uploads and removes images from Imgur + function ShareModel () { + if ( ! ( this instanceof ShareModel ) ) { + return new ShareModel(); + } + + var self = this; + var base64Url; + var publishers = addPublishers( self, + 'uploadstart', 'uploadend', 'uploadcomplete', + 'removestart', 'removeend', 'removecomplete', + 'error', 'statusmessage' + ); + + // http://stackoverflow.com/questions/17805456/upload-a-canvas-image-to-imgur-api-v3-with-javascript + function upload () { + if ( base64Url ) { + publishers.uploadstart.dispatch(); + + reqwest( { + url: 'https://api.imgur.com/3/image.json', + method: 'POST', + headers: { + Authorization: 'Client-ID ' + config.keys.imgur + }, + data: { + image: base64Url.split( ',' )[1], + type: 'base64' + }, + type: 'json', + crossOrigin: true, + success: uploadSuceeded, + error: uploadFailed + } ); + } else { + uploadFailed( new Error( 'share.error.base64' ) ); + } + + return self; + } + + function uploadSuceeded ( res ) { + publishers.uploadend.dispatch(); + + if ( res.status === 200 && res.data && res.data.link ) { + var link = res.data.link.replace( 'http://', 'https://' ); + + publishers.uploadcomplete.dispatch( link, res.data.id, res.data.deletehash ); + publishers.statusmessage.dispatch( 'share.message.upload', { innerHTML: true, args: [ link ] } ); + } + } + + function uploadFailed ( err ) { + publishers.uploadend.dispatch(); + publishers.error.dispatch( 'share.error.upload', { type: 'imguruploadfail' } ); + console && console.log( err.message || err ); + } + + function updateUrl ( url ) { + base64Url = url; + + return self; + } + + function remove ( uid, deleteHash ) { + if ( deleteHash ) { + publishers.removestart.dispatch( uid ); + + reqwest( { + url: 'https://api.imgur.com/3/image/' + deleteHash, + method: 'DELETE', + headers: { + Authorization: 'Client-ID ' + config.keys.imgur + }, + crossOrigin: true, + success: function () { removeSucceeded( uid ); }, + error: function ( err ) { removeFailed( uid, err ); } + } ); + } + + return self; + } + + function removeSucceeded ( uid ) { + publishers.removeend.dispatch( uid ); + publishers.removecomplete.dispatch( uid ); + publishers.statusmessage.dispatch( 'share.message.del' ); + } + + function removeFailed ( uid, err ) { + publishers.removeend.dispatch( uid ); + publishers.error.dispatch( 'share.error.del', { type: 'imgurremovefail', uid: uid } ); + console && console.log( err.message || err ); + } + + self.upload = upload; + self.updateUrl = updateUrl; + self.remove = remove + } + + return ShareModel; + } +); \ No newline at end of file diff --git a/scripts/models/storagemodel.js b/scripts/models/storagemodel.js new file mode 100644 index 0000000..5ffaba6 --- /dev/null +++ b/scripts/models/storagemodel.js @@ -0,0 +1,300 @@ +/*global define*/ +define( + [ 'config', 'util/browser', 'util/addpublishers', 'lib/md5', 'lib/localforage.nopromises', 'models/localisationmodel' ], + function ( config, browser, addPublishers, md5, localforage, LocalisationModel ) { + // the StorageModel takes care of loading and saving data to localStorage. + // It stores the used glitch values as well as the imgur address if the + // image was shared. + // It generares a UID for each image to avoid having to save the + // same image multiple times. + // If an image was updated (shared/deleted), it updates the corresponding + // object in localstorage + function StorageModel () { + if ( ! ( this instanceof StorageModel ) ) { + return new StorageModel(); + } + + var self = this; + var isFirstVisit = false; + var entries = { }; + var useLocalForage = browser.test( 'localforage' ) && localforage; + var worker; + + var publisherNames = [ + 'update', 'save', 'loaditem', + 'removeall', 'removelocaldata', 'removeimgurdata', + 'firstvisit', 'error', 'statusmessage' + ]; + + var publishers = addPublishers( self, publisherNames ); + + storageKey = config.keys.storage; + + if ( useLocalForage && browser.test( 'webworker' ) && browser.test( 'browserdb' ) && ! browser.test( 'safari' ) ) { + worker = new Worker( config.workers.storage ); + worker.addEventListener( 'message', workerResponded, false ); + sendMessageToWorker( 'setStorageKey', storageKey ); + } + + function add ( item ) { + if ( useLocalForage && item ) { + if ( worker ) { + sendMessageToWorker( 'add', item ); + } else { + var uid = createUID( item ); + + if ( + entries[uid] && + entries[uid].deleteHash === item.deleteHash && + entries[uid].publicUrl === item.publicUrl && + entries[uid].imgurID === item.imgurID + ) { + publishers.statusmessage.dispatch( 'file.message.before' ); + } else { + item.timestamp = Date.now(); + entries[uid] = item; + + save( function () { + publishers.statusmessage.dispatch( 'file.message.save' ); + } ); + } + } + } + + return self; + } + + function removeCompletely ( uid ) { + if ( useLocalForage && uid ) { + if ( worker ) { + sendMessageToWorker( 'removeCompletely', uid ); + } else { + if ( + entries[uid] && + ( + entries[uid].deleteHash || + entries[uid].publicUrl || + entries[uid].imgurID || + entries[uid].values || + entries[uid].src + ) + ) { + console && console.log( 'cant delete storage item because theres still some data left', entries[uid] ); + } else { + publishers.removeall.dispatch( entries[uid] ); + delete entries[uid]; + + save( function () { + publishers.statusmessage.dispatch( 'file.message.del' ); + } ); + } + } + } + } + + function removeLocalData ( uid ) { + if ( useLocalForage && uid ) { + if ( worker ) { + sendMessageToWorker( 'removeLocalData', uid ); + } else { + if ( entries[uid] ) { + if ( entries[uid].src ) { + delete entries[uid].src; + + publishers.removelocaldata.dispatch( entries[uid] ); + } + + if ( entries[uid].values ) { + delete entries[uid].values; + } + + if ( ! ( entries[uid].deleteHash || entries[uid].publicUrl || entries[uid].imgurID ) ) { + removeCompletely( uid ); + } + + save(); + } + } + } + + return self; + } + + function removeImgurData ( uid ) { + if ( useLocalForage && uid ) { + if ( worker ) { + sendMessageToWorker( 'removeImgurData', uid ); + } else { + if ( entries[uid] ) { + if ( entries[uid].deleteHash ) { + publishers.removeimgurdata.dispatch( entries[uid] ); + delete entries[uid].deleteHash; + } + + if ( entries[uid].publicUrl ) { + delete entries[uid].publicUrl; + } + + if ( entries[uid].imgurID ) { + delete entries[uid].imgurID; + } + + if ( ! ( entries[uid].src || entries[uid].values ) ) { + removeCompletely( uid ); + } + + save(); + } + } + } + + return self; + } + + function load ( callback ) { + if ( useLocalForage ) { + if ( worker ) { + sendMessageToWorker( 'load' ); + } else { + localforage.getItem( storageKey, function ( err, loadedData ) { + if ( err ) { + publishers.error.dispatch( 'file.error.load' ); + console && console.log( 'localforage error', err ); + } else { + entries = loadedData && loadedData.entries ? loadedData.entries : { }; + publishers.update.dispatch( entries ); + + isFirstVisit = ( loadedData && loadedData.lastVisit ) ? false : true; + + if ( isFirstVisit ) { + publishers.firstvisit.dispatch(); + save(); + } + + if ( typeof callback === 'function' ) { + callback(); + } + } + } ); + } + } + + return self; + } + + function save ( callback ) { + if ( useLocalForage ) { + if ( worker ) { + sendMessageToWorker( 'save' ); + } else { + localforage.setItem( storageKey, { entries: entries, lastVisit: Date.now() }, function ( err, savedData ) { + if ( err ) { + publishers.error.dispatch( 'file.error.save' ); + console && console.log( 'localforage error', err ); + } else { + if ( savedData ) { + entries = savedData.entries; + publishers.update.dispatch( entries ); + publishers.save.dispatch(); + + if ( typeof callback === 'function' ) { + callback(); + } + } else { + console && console.log( 'no data was saved', savedData ); + } + } + } ); + } + } + + return self; + } + + function loadItem ( uid ) { + if ( useLocalForage ) { + if ( worker ) { + sendMessageToWorker( 'loadItem', uid ); + } else { + if ( entries[uid] ) { + publishers.loaditem.dispatch( uid, entries[uid] ); + } + } + } + + return self; + } + + function workerResponded ( event ) { + if ( event && event.data ) { + publisherNames.forEach( function ( type ) { + if ( typeof event.data[type] !== 'undefined' ) { + if ( type === 'loaditem' ) { + publishers[type].dispatch( event.data[type].uid, event.data[type].entries ); + } else { + if ( publishers[type] === type ) { + // if message is empty, the worker sends the type as data. + publishers[type].dispatch() + } else { + publishers[type].dispatch( event.data[type] ) + } + } + } + } ); + } + } + + function sendMessageToWorker ( type, data ) { + if ( typeof type === 'string' ) { + if ( typeof data === 'undefined' ) { + data = type; + } + + var message = { }; + message[type] = data; + worker.postMessage( message ); + } + } + + function createUID ( item ) { + var inputStr = 'N' + item.name + 'S' + item.src + 'L' + item.thumbnail.length || 0 + 'V'; + + for ( var key in item.values ) { + inputStr += key.substr( 0, 2 ); + inputStr += item.values[key]; + } + + return md5( inputStr ); + } + + function getLatestUID () { + var latestUid; + var latestTimestamp; + var timestamp; + + for ( var uid in entries ) { + timestamp = entries[uid].timestamp; + + if ( timestamp ) { + if ( ! latestUid || timestamp > latestTimestamp ) { + latestUid = uid; + latestTimestamp = timestamp; + } + } + } + + return latestUid; + } + + self.add = add; + self.removeImgurData = removeImgurData; + self.removeLocalData = removeLocalData; + self.load = load; + self.loadItem = loadItem; + self.removeImgurData = removeImgurData; + self.getLatestUID = getLatestUID; + } + + return StorageModel; + } +); \ No newline at end of file diff --git a/scripts/src/controls.js b/scripts/src/controls.js deleted file mode 100644 index cb8c3e0..0000000 --- a/scripts/src/controls.js +++ /dev/null @@ -1,53 +0,0 @@ -/*global define*/ -define( - function() - { - var values = { }; - var is_initialized = false; - var signals; - - function init( shared ) - { - signals = shared.signals; - - if ( shared.feature['query-selector-all'] ) - { - var wrapper = document.getElementById( 'controls' ); - var controls = document.querySelectorAll( '.control-input' ); - - wrapper.className += ' is-active'; - - for ( var i = 0; i < controls.length; i++ ) - { - var control = controls[i]; - - control.addEventListener( 'change', controlUpdated, false ); - updateValue( control.id, control.value ); - } - - is_initialized = true; - - signals['control-updated'].dispatch( values ); - } - } - - function controlUpdated( event ) - { - var target = event.target; - - updateValue( target.id, target.value ); - } - - function updateValue( key, value ) - { - values[key] = value; - - if ( is_initialized ) - { - signals['control-updated'].dispatch( values ); - } - } - - return { init: init }; - } -); \ No newline at end of file diff --git a/scripts/src/dragdrop.js b/scripts/src/dragdrop.js deleted file mode 100644 index 158a386..0000000 --- a/scripts/src/dragdrop.js +++ /dev/null @@ -1,43 +0,0 @@ -/*global define*/ -define( - function() - { - var signals; - var reader; - var feature; - - function init( shared ) - { - feature = shared.feature; - signals = shared.signals; - - if ( feature['drag-drop' ] && feature['file-api' ] ) - { - document.addEventListener( 'drop', dropped, false ); - document.addEventListener( 'dragover', preventDefault, false ); - document.addEventListener( 'dragleave', preventDefault, false ); - - reader = new FileReader(); - reader.addEventListener( 'load', fileLoaded, false ); - } - } - - function preventDefault( event ) - { - event.preventDefault(); - } - - function dropped( event ) - { - event.preventDefault(); - reader.readAsDataURL( event.dataTransfer.files[0] ); - } - - function fileLoaded( event ) - { - signals['set-new-src'].dispatch( event.target.result ); - } - - return { init: init }; - } -); \ No newline at end of file diff --git a/scripts/src/export-png.js b/scripts/src/export-png.js deleted file mode 100644 index 2bad560..0000000 --- a/scripts/src/export-png.js +++ /dev/null @@ -1,31 +0,0 @@ -/*global define*/ -define( - function() - { - var signals; - var png_button; - - function init( shared ) - { - signals = shared.signals; - png_button = document.getElementById( 'png-button' ); - - signals['export-png'].add( generatePNG ); - signals['control-updated'].add( hideLink ); - png_button.addEventListener( 'click', hideLink, false ); - } - - function generatePNG( data_url ) - { - png_button.href = data_url; - png_button.classList.add( 'is-active' ); - } - - function hideLink() - { - png_button.classList.remove( 'is-active' ); - } - - return { init: init }; - } -); \ No newline at end of file diff --git a/scripts/src/image.js b/scripts/src/image.js deleted file mode 100644 index dfb7419..0000000 --- a/scripts/src/image.js +++ /dev/null @@ -1,45 +0,0 @@ -/*global define*/ -define( - function() - { - var signals; - var image; - var initialized = false; - - function init( shared ) - { - signals = shared.signals; - image = new Image(); - - signals['set-new-src'].add( setSrc ); - - image.addEventListener( 'load', imageLoaded, false ); - - // the image "Abraham Lincoln November 1863" is public domain: - // https://en.wikipedia.org/wiki/File:Abraham_Lincoln_November_1863.jpg - setSrc( 'lincoln.jpg' ); - } - - function imageLoaded() - { - signals['image-loaded'].dispatch( image ); - initialized = true; - } - - function setSrc( src ) - { - image.src = src; - - if ( - initialized && - image.naturalWidth !== undefined && - image.naturalWidth !== 0 - ) - { - signals['image-loaded'].dispatch( image ); - } - } - - return { init: init }; - } -); \ No newline at end of file diff --git a/scripts/src/main.js b/scripts/src/main.js deleted file mode 100644 index eea64c7..0000000 --- a/scripts/src/main.js +++ /dev/null @@ -1,75 +0,0 @@ -/*global require, requirejs, define, Modernizr, _basepath_ */ -// http://requirejs.org/docs/api.html#config -var path = typeof _basepath_ === 'string' ? _basepath_ + '/' : ''; -requirejs.config( - { - baseUrl: path + 'scripts/', - waitSeconds: 5, - urlArgs: 'bust=' + ( new Date() ).getTime(), - shim: { - 'lib/delaunay': { exports: 'triangulate' } - } - } -); - -require( - [ - 'src/process', - 'src/image', - 'src/dragdrop', - 'src/controls', - 'src/export-png', - 'src/save-button', - 'aux/feature-test', - 'lib/signals-1.0.0', - 'lib/html5slider' - ], - function( - process, - image, - dragdrop, - controls, - png, - save_button, - testFeatures, - Signal - ) - { - testFeatures( init, showError ); - - function init( supported_features ) - { - var shared = { - feature: supported_features, - signals: { - 'image-loaded' : new Signal(), - 'set-new-src' : new Signal(), - 'control-updated' : new Signal(), - 'export-png' : new Signal(), - 'saved' : new Signal() - } - }; - - process.init( shared ); - dragdrop.init( shared ); - controls.init( shared ); - png.init( shared ); - save_button.init( shared ); - image.init( shared ); - } - - function showError( required_features ) - { - var message = document.createElement( 'div' ); - - var message_text = 'sorry. it looks like your browser is missing some of the features '; - message_text += '(' + required_features.join( ', ' ) + ') that are required to run this '; - message_text += 'experiment.'; - - message.innerText = message_text; - message.className = 'missing-feature'; - - document.getElementsByTagName( 'body' )[0].appendChild( message ); - } - } -); \ No newline at end of file diff --git a/scripts/src/process.js b/scripts/src/process.js deleted file mode 100644 index e2a96b2..0000000 --- a/scripts/src/process.js +++ /dev/null @@ -1,113 +0,0 @@ -/*global define, requestAnimationFrame*/ -define( - [ 'aux/glitch', 'aux/canvas', 'lib/raf' ], - function( glitch, canvas_helper ) - { - var tmp_canvas = document.createElement( 'canvas' ); - var tmp_ctx = tmp_canvas.getContext( '2d' ); - - var canvas = document.getElementById( 'canvas' ); - var ctx = canvas.getContext( '2d' ); - - var is_processing = false; - var values; - var image; - var signals; - var image_data; - var canvas_size; - - function init( shared ) - { - signals = shared.signals; - - signals['image-loaded'].add( generate ); - signals['control-updated'].add( controlsUpdated ); - signals['saved'].add( exportData ); - } - - function controlsUpdated( new_values ) - { - values = getAdjustedValues( new_values ); - - update(); - } - - function generate( img ) - { - if ( ! is_processing ) - { - image = img; - processImage( image ); - } - } - - function requestTick() - { - if ( ! is_processing ) - { - requestAnimationFrame( update ); - } - - is_processing = true; - } - - function update() - { - if ( image ) - { - processImage( image ); - } - - else - { - is_processing = false; - } - } - - function processImage( img ) - { - is_processing = true; - - canvas_helper.clear( tmp_canvas, tmp_ctx ); - canvas_helper.clear( canvas, ctx ); - canvas_helper.resize( tmp_canvas, img ); - canvas_helper.resize( canvas, img ); - - tmp_ctx.drawImage( img, 0, 0 ); - - image_data = tmp_ctx.getImageData( 0, 0, tmp_canvas.width, tmp_canvas.height ); - - glitch( image_data, values, draw ); - } - - function draw( image_data ) - { - canvas_helper.resize( canvas, image_data ); - ctx.putImageData( image_data, 0, 0 ); - - is_processing = false; - image_data = null; - } - - function exportData() - { - signals['export-png'].dispatch( canvas.toDataURL( 'image/png' ) ); - } - - function getAdjustedValues( new_values ) - { - var result = { }; - - for ( var key in new_values ) - { - result[key] = parseInt( new_values[key], 10 ); - } - - key = null; - - return result; - } - - return { init: init }; - } -); \ No newline at end of file diff --git a/scripts/src/save-button.js b/scripts/src/save-button.js deleted file mode 100644 index 089cf5a..0000000 --- a/scripts/src/save-button.js +++ /dev/null @@ -1,25 +0,0 @@ -/*global define*/ -define( - function() - { - var signals; - var save_button; - - function init( shared ) - { - signals = shared.signals; - save_button = document.getElementById( 'save-button' ); - - save_button.addEventListener( 'click', buttonClicked, false ); - } - - function buttonClicked( event ) - { - event.preventDefault(); - - signals['saved'].dispatch(); - } - - return { init: init }; - } -); \ No newline at end of file diff --git a/scripts/util/addpublishers.js b/scripts/util/addpublishers.js new file mode 100644 index 0000000..2850ca0 --- /dev/null +++ b/scripts/util/addpublishers.js @@ -0,0 +1,128 @@ +/*global define*/ +define( + [ 'util/object' ], + function ( objectHelper ) { + // adds publishers to an object that + // other objects can subscribe to. + // only the trigger object can + // publish new messages + // eg: trigger = addPublushers( obj1, 'test' ); + // obj1.on( 'test', obj2.doStuff ); + // trigger.test.dispatch( 'YOLO' ); + + function addPublishers () { + var publishers = { }; + var allowedKeys = [ ]; + var args = Array.prototype.slice.call( arguments ); + var obj = args.shift(); + + if ( obj && args.length ) { + args.forEach( addKey ); + } + + allowedKeys.forEach( function ( key ) { + if ( ! obj[key] ) { + obj[key] = { }; + } + + obj[key].dispatch = function () { + dispatch.apply( dispatch, [ key ].concat( Array.prototype.slice.call( arguments ) ) ); + }; + + if ( ! publishers[key] ) { + publishers[key] = [ ]; + } + + publishers[key].dispatch = function () { + dispatch.apply( dispatch, [ key ].concat( Array.prototype.slice.call( arguments ) ) ); + }; + } ); + + function addKey ( newItem ) { + var newKeys = [ ]; + var existingKeys = Object.keys( obj ); + + if ( typeof newItem === 'string' ) { + newKeys = newKeys.concat( newItem.split( ' ' ) ); + } + + if ( Array.isArray( newItem ) ) { + newKeys = newKeys.concat( newItem ); + } + + newKeys = newKeys.filter( function ( key ) { + if ( + existingKeys.indexOf( key ) === -1 && + allowedKeys.indexOf( key ) === -1 + ) { + return true; + } else { + return false; + } + } ); + + allowedKeys = allowedKeys.concat( newKeys ); + } + + function on ( key, fn ) { + // on( 'my.sub.ev' ) -> obj.my.sub.on( 'ev' ); + if ( typeof key === 'string' && key.indexOf( '.' ) !== -1 ) { + var keyArr = key.split( '.' ); + var key = keyArr.pop(); + var subObj = objectHelper.getObjectByString( keyArr.join( '.' ), obj ); + + if ( subObj && typeof subObj.on === 'function' ) { + subObj.on( key, fn ); + } + } else { + if ( isKeyAllowed( key ) && typeof fn === 'function' ) { + publishers[key].push( fn ); + } + } + + return obj; + } + + function off ( key, fn ) { + if ( + typeof key === 'string' && + typeof fn === 'function' && + publishers[key] + ) { + for ( var i = publishers[key].length; i >= 0; i-- ) { + if ( publishers[key][i] === fn ) { + publishers[key].splice( i, 1 ); + } + } + } + + return obj; + } + + function dispatch ( key ) { + // http://debuggable.com/posts/turning-javascript-s-arguments-object-into-an-array:4ac50ef8-3bd0-4a2d-8c2e-535ccbdd56cb + var args = Array.prototype.slice.call( arguments ).slice( 1 ); + + if ( Array.isArray( publishers[key] ) ) { + publishers[key].forEach( function ( fn ) { + fn.apply( fn, args ); + } ); + } + + return obj; + } + + function isKeyAllowed ( key ) { + return allowedKeys ? allowedKeys.indexOf( key ) > -1 : true; + } + + publishers.dispatch = dispatch; + obj.on = on; + obj.off = off; + + return publishers; + } + + return addPublishers; + } +); \ No newline at end of file diff --git a/scripts/util/browser.js b/scripts/util/browser.js new file mode 100644 index 0000000..6542d44 --- /dev/null +++ b/scripts/util/browser.js @@ -0,0 +1,80 @@ +/*global define*/ +define( + [ 'util/string' ], + function ( strUtil ) { + + var prefixes = [ 'webkit', 'moz', 'ms', 'o' ]; + var results = { }; + + var tests = { + getusermedia: function () { + return navigator.getUserMedia = ( + navigator.getUserMedia || + navigator.webkitGetUserMedia || + navigator.mozGetUserMedia || + navigator.msGetUserMedia + ); + }, + fullscreen: function () { + return !! ( + getFeature( document, 'fullScreenEnabled' ) || + getFeature( document, 'fullscreenEnabled' ) + ); + }, + browserdb: function() { + return ( + getFeature( window, 'indexedDB' ) || + getFeature( window, 'openDatabase' ) + ); + }, + browserstorage: function() { + return ( + test( 'browserdb' ) || + getFeature( window, 'localStorage' ) + ); + }, + draganddrop: function () { return 'draggable' in document.createElement( 'span' ); }, + touch: function () { return !!( 'ontouchstart' in window ); }, + webworker: function () { return !! ( 'Worker' in window ); }, + promise: function () { return !! ( 'Promise' in window ); }, + localforage: function () { + return ( test( 'promise' ) && test( 'browserstorage' ) ); + }, + safari: function () { return /^((?!chrome|android).)*safari/i.test( navigator.userAgent ); } + }; + + function test ( featureName ) { + if ( typeof results[featureName] !== 'undefined' ) { + return results[featureName]; + } else { + results[featureName] = tests[featureName] ? tests[featureName]() : false; + return results[featureName]; + } + } + + function getFeature ( obj, propertyName ) { + var result = testProperty( obj, propertyName ); + + if ( ! result ) { + for ( var i = 0, len = prefixes.length; i < len; i++ ) { + if ( ! result ) { + result = testProperty( obj, strUtil.toCamelCase( prefixes[i] + '-' + propertyName ) ); + } else { + break; + } + } + } + + return result; + } + + function testProperty ( obj, propertyName ) { + return obj[propertyName]; + } + + return { + getFeature: getFeature, + test: test + }; + } +); \ No newline at end of file diff --git a/scripts/util/canvas.js b/scripts/util/canvas.js new file mode 100644 index 0000000..37e0727 --- /dev/null +++ b/scripts/util/canvas.js @@ -0,0 +1,85 @@ +/*global define*/ +define( + function () { + var canvas = document.createElement( 'canvas' ); + var ctx = canvas.getContext( '2d' ); + + function resizeImage ( content, size, callback, returnType ) { + var image = new Image(); + var scale = 1; + var isImageData = false; + var isString = false; + + image.addEventListener( 'load', imageLoaded ); + + // url + if ( typeof content === 'string' ) { + isString = true; + image.src = content; + } + + // imagedata + if ( content.width && content.height && content.data && content.data.length ) { + isImageData = true; + canvas.width = content.width; + canvas.height = content.height; + + scale = Math.min( + size.width / content.width, + size.height / content.height + ); + + ctx.putImageData( content, 0, 0 ); + image.src = canvas.toDataURL( 'image/png', 1 ); + } + + if ( ! isString && ! isImageData ) { + callback( false ); + } + + function imageLoaded () { + if ( isString && image.src === content ) { + // src loaded + canvas.width = image.naturalWidth; + canvas.height = image.naturalHeight; + + scale = Math.min( + size.width / image.naturalWidth, + size.height / image.naturalHeight + ); + + ctx.drawImage( image, 0, 0 ); + image.src = canvas.toDataURL( 'image/png', 1 ); + } else { + // imageData loaded + canvas.width = size.width; + canvas.height = size.height; + + ctx.scale( scale, scale ); + ctx.drawImage( image, 0, 0 ); + + if ( returnType === 'both' ) { + callback( { + dataURL: canvas.toDataURL( 'image/png', 1 ), + imageData: ctx.getImageData( 0, 0, canvas.width, canvas.height ) + } ); + } else { + if ( isString || returnType === 'asDataURL' ) { + callback( canvas.toDataURL( 'image/png', 1 ) ); + } else { + if ( isImageData || returnType === 'asImageData' ) { + callback( ctx.getImageData( 0, 0, canvas.width, canvas.height ) ); + } else { + callback(); + } + } + } + } + } + } + + return { + resizeImage: resizeImage + }; + } +); \ No newline at end of file diff --git a/scripts/util/css.js b/scripts/util/css.js new file mode 100644 index 0000000..885de04 --- /dev/null +++ b/scripts/util/css.js @@ -0,0 +1,43 @@ +/*global define*/ +define( + function () { + function getCSSMatrix ( el ) { + var style = window.getComputedStyle( el ); + + return style.getPropertyValue( '-webkit-transform' ) || + style.getPropertyValue( '-moz-transform' ) || + style.getPropertyValue( '-ms-transform' ) || + style.getPropertyValue( '-o-transform' ) || + style.getPropertyValue( 'transform' ); + } + + function cssMatrixToTransformObj ( matrix ) { + // this happens when there was no rotation yet in CSS + if ( matrix === 'none' ) { + matrix = 'matrix(0,0,0,0,0)'; + } + + var obj = { }; + var values = matrix.match( /([-+]?[\d\.]+)/g ); + + obj.rotate = ( Math.round( + Math.atan2( + parseFloat( values[1] ), + parseFloat( values[0] ) ) * ( 180 / Math.PI ) + ) || 0 + ).toString() + 'deg'; + + obj.translateStr = values[5] ? values[4] + 'px, ' + values[5] + 'px' : ( values[4] ? values[4] + 'px' : '' ); + + obj.translateX = parseFloat( values[4] ); + obj.translateY = values[5] ? parseFloat( values[5] ) : 0; + + return obj; + } + + return { + getCSSMatrix: getCSSMatrix, + cssMatrixToTransformObj: cssMatrixToTransformObj + } + } +); \ No newline at end of file diff --git a/scripts/util/dom.js b/scripts/util/dom.js new file mode 100644 index 0000000..70d0a8d --- /dev/null +++ b/scripts/util/dom.js @@ -0,0 +1,37 @@ +/*global define*/ +define( + function () { + function setTransform ( el, transformStr ) { + el.style.transform = el.style.webkitTransform = el.style.msTransform = transformStr; + } + + // http://stackoverflow.com/a/2234986/229189 + function isDescendant ( parent, child ) { + var node = child.parentNode; + + while ( node != null ) { + if ( node == parent ) { + return true; + } + + node = node.parentNode; + } + + return false; + } + + // http://stackoverflow.com/a/384380/229189 + function isElement ( obj ) { + return ( + typeof HTMLElement === 'object' ? obj instanceof HTMLElement : + obj && typeof obj === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string' + ); + } + + return { + setTransform: setTransform, + isDescendant: isDescendant, + isElement: isElement + }; + } +); \ No newline at end of file diff --git a/scripts/util/el.js b/scripts/util/el.js new file mode 100644 index 0000000..048345d --- /dev/null +++ b/scripts/util/el.js @@ -0,0 +1,107 @@ +/*global define*/ +define( + [ 'util/dom', 'util/localizeText' ], + function ( domHelper, loc ) { + var svgEls = [ 'g', 'svg', 'rect' ]; + var svgNameSpace = 'http://www.w3.org/2000/svg'; + + function createEl ( elementStr, cssClasses, parentEl ) { + var hasNameSpace = svgEls.indexOf( elementStr ) !== -1; + var el = hasNameSpace ? document.createElementNS( svgNameSpace, elementStr ) : document.createElement( elementStr ); + + if ( hasNameSpace ) { + document.createElementNS( 'http://www.w3.org/2000/svg', 'rect' ); + } + + cssClasses = typeof cssClasses === 'string' ? [ ].concat( cssClasses.split( ' ' ) ) : cssClasses; + + if ( Array.isArray( cssClasses ) ) { + cssClasses.forEach( function ( cssClass ) { + el.classList.add( cssClass ); + } ); + } + + if ( parentEl && parentEl.appendChild ) { + parentEl.appendChild( el ); + } + + return el; + } + + function createButton ( content, title, cssClasses, parentEl, onClick ) { + var btnEl = createEl( 'button', cssClasses, parentEl ); + + if ( typeof content === 'string' ) { + // btnEl.textContent = content; + loc( btnEl, 'textContent', content ); + } else { + if ( domHelper.isElement( content ) ) { + btnEl.appendChild( content ); + } + } + + // btnEl.title = title; + loc( btnEl, 'title', title ); + + if ( typeof onClick === 'function' ) { + btnEl.addEventListener( 'click', onClick ); + } + + return btnEl; + } + + function createLink ( content, title, href, target, cssClasses, parentEl ) { + var linkEl = createEl( 'a', cssClasses, parentEl ); + + if ( typeof content === 'string' ) { + // linkEl.textContent = content; + loc( linkEl, 'textContent', content ); + } else { + if ( domHelper.isElement( content ) ) { + linkEl.appendChild( content ); + } + } + + if ( title ) { + // linkEl.title = title; + loc( linkEl, 'title', title ); + } + + if ( href ) { + linkEl.href = href; + } + + if ( target ) { + linkEl.target = target; + } + + return linkEl; + } + + function createLabel ( content, forId, cssClasses, parentEl ) { + var labelEl = createEl( 'label', cssClasses, parentEl ); + + if ( typeof content === 'string' ) { + // labelEl.textContent = content; + loc( labelEl, 'textContent', content ); + } else { + if ( domHelper.isElement( content ) ) { + labelEl.appendChild( content ); + } + } + + if ( forId ) { + labelEl.setAttribute( 'for', forId ); + } + + return labelEl; + } + + return { + createEl: createEl, + createButton: createButton, + createLink: createLink, + createLabel: createLabel + } + } +); \ No newline at end of file diff --git a/scripts/util/localizetext.js b/scripts/util/localizetext.js new file mode 100644 index 0000000..a7c8fa6 --- /dev/null +++ b/scripts/util/localizetext.js @@ -0,0 +1,11 @@ +/*global define*/ +define( + [ 'models/localisationmodel' ], + function ( LocalisationModel ) { + function loc () { + return LocalisationModel.sharedInstance.localizeText.apply( LocalisationModel.sharedInstance, arguments ); + } + + return loc; + } +); \ No newline at end of file diff --git a/scripts/util/math.js b/scripts/util/math.js new file mode 100644 index 0000000..8855636 --- /dev/null +++ b/scripts/util/math.js @@ -0,0 +1,22 @@ +/*global define*/ +define( + function () { + function mapRange ( value, inMin, inMax, outMin, outMax, clampResult ) { + var result = ( ( value - inMin ) / ( inMax - inMin ) * ( outMax - outMin ) + outMin ); + + if ( clampResult ) { + if ( outMin > outMax ) { + result = Math.min( Math.max( result, outMax ), outMin ); + } else { + result = Math.min( Math.max( result, outMin ), outMax ); + } + } + + return result; + } + + return { + mapRange: mapRange + }; + } +); \ No newline at end of file diff --git a/scripts/util/mediastream.js b/scripts/util/mediastream.js new file mode 100644 index 0000000..5d3fb85 --- /dev/null +++ b/scripts/util/mediastream.js @@ -0,0 +1,24 @@ +/*global define*/ +define( + function () { + // http://stackoverflow.com/a/11646945 + var MediaStream = window.MediaStream; + + if ( typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined' ) { + MediaStream = webkitMediaStream; + } + + /*global MediaStream:true */ + if ( typeof MediaStream !== 'undefined' && !( 'stop' in MediaStream.prototype ) ) { + MediaStream.prototype.stop = function () { + this.getAudioTracks().forEach( function ( track ) { + track.stop(); + } ); + + this.getVideoTracks().forEach( function ( track ) { + track.stop(); + } ); + }; + } + } +) \ No newline at end of file diff --git a/scripts/util/object.js b/scripts/util/object.js new file mode 100644 index 0000000..8e0572b --- /dev/null +++ b/scripts/util/object.js @@ -0,0 +1,35 @@ +/*global define*/ +define( + function () { + // http://stackoverflow.com/a/6491621/229189 + function getObjectByString ( str, obj ) { + if ( typeof str === 'string' ) { + str = str.replace( /\[(\w+)\]/g, '.$1' ); // convert indexes to properties + str = str.replace( /^\./, '' ); // strip a leading dot + + var keys = str.split( '.' ); + + for ( var i = 0, len = keys.length; i < len; ++i ) { + var key = keys[i]; + + if ( key in obj ) { + obj = obj[key]; + } else { + return; + } + } + } + + return obj; + } + + function getCopy ( obj ) { + return JSON.parse( JSON.stringify( obj ) ); + } + + return { + getObjectByString: getObjectByString, + getCopy: getCopy + }; + } +); \ No newline at end of file diff --git a/scripts/util/string.js b/scripts/util/string.js new file mode 100644 index 0000000..9dc11b6 --- /dev/null +++ b/scripts/util/string.js @@ -0,0 +1,79 @@ +/*global define*/ +define( + function () { + function toCamelCase ( str ) { + // if array was passed + if ( str && Array.isArray( str ) ) { + str = str.join( ' ' ); + } + + var parts = str.split( /(-|\s|_)/gmi ); + var result = ''; + + parts.forEach( function ( item, index ) { + if ( ! item.match( /(-|\s|_)/gmi ) ) { + if ( index > 0 && item.length > 1 ) { + result += item.charAt( 0 ).toUpperCase() + item.slice( 1 ); + } else { + result += item; + } + } + } ); + + return result; + } + + function markdownToHtml ( str, options ) { + return autop( + markdownLinksToHtml( str, options.links ), + options.autop + ); + } + + function markdownLinksToHtml ( str, options ) { + var attributes = [ ]; + var attributeStr = ''; + + if ( options ) { + if ( options.newTab ) { + attributes.push( 'target="_blank"' ); + } + + if ( options.cssClasses ) { + attributes.push( 'class="' + cssClasses + '"' ); + } + } + + attributeStr = attributes.length ? ' ' + attributes.join( ' ' ) : ''; + + var linkHTML = '$1'; + + return str + .replace( /\\n/gm, '\n') + .replace( /\[(.*?)\]\((.+?)\)/g, linkHTML ); + } + + function autop ( str, options ) { + var tag = ( options && options.tag ) ? options.tag : 'p'; + var lineBreakTag = ( options && options.linebreak ) ? '<' + options.linebreak + '>' : '
'; + var startTag = '<' + tag + '>'; + var endTag = ''; + + if ( options && options.cssClasses && typeof options.cssClasses === 'string' ) { + startTag = '<' + tag + ' class="' + options.cssClasses + '">'; + } + + return startTag + str + .replace( /\n{2}/g, ' ' + endTag + startTag ) + .replace(/\n/g, ' ' + lineBreakTag ) + + endTag; + } + + return { + toCamelCase: toCamelCase, + autop: autop, + markdownToHtml: markdownToHtml, + markdownLinksToHtml: markdownLinksToHtml + }; + } +) \ No newline at end of file diff --git a/scripts/util/time.js b/scripts/util/time.js new file mode 100644 index 0000000..18a5586 --- /dev/null +++ b/scripts/util/time.js @@ -0,0 +1,82 @@ +/*global define*/ +define( + function () { + var lang = navigator.language || navigator.userLanguage || 'en-us'; + var intlIsSupported = !! window.Intl; + + function dateToStr ( date ) { + return date.toISOString(); + } + + function timestampToDate ( str ) { + return new Date( parseInt( str, 10 ) ); + } + + function dateTimeToLocalStr ( date ) { + if ( + intlIsSupported && + Intl.DateTimeFormat.supportedLocalesOf( [ lang ] ).length && + date.toLocaleDateString && + date.toLocaleTimeString + ) { + return date.toLocaleDateString( lang ) + ' ' + date.toLocaleTimeString( lang ); + } else { + return dateToLocalStr( date ) + ' ' + timeToLocalStr( date ); + } + } + + function dateToLocalStr ( date ) { + if ( + intlIsSupported && + Intl.DateTimeFormat.supportedLocalesOf( [ lang ] ).length && + date.toLocaleDateString + ) { + return date.toLocaleDateString( lang ); + } else { + if ( navigator.language.toLowerCase() === 'en-us' ) { + return ( date.getMonth() + 1 ) + '/' + date.getDate() + '/' + date.getFullYear(); + } else { + return ( date.getDate() + '.' + date.getMonth() + 1 ) + '.' + date.getFullYear(); + } + } + } + + function timeToLocalStr ( date ) { + if ( + intlIsSupported && + Intl.DateTimeFormat.supportedLocalesOf( [ lang ] ).length && + date.toLocaleTimeString + ) { + return date.toLocaleTimeString( lang ); + } else { + var hours = date.getHours(); + var minutes = date.getMinutes(); + + if ( hours < 10 ) { hours = '0' + hours; } + if ( minutes < 10 ) { minutes = '0' + minutes; } + + if ( navigator.language.toLowerCase().indexOf( 'en' ) >= 0 ) { + var amPm = 'AM'; + + if ( hours > 12 ) { + hours -= 12; + amPm = 'PM'; + } + + return hours + ':' + minutes + ' ' + amPm; + + } else { + return hours + ':' + minutes; + } + } + } + + return { + dateToStr: dateToStr, + dateToLocalStr: dateToLocalStr, + timeToLocalStr: timeToLocalStr, + dateTimeToLocalStr: dateTimeToLocalStr, + timestampToDate: timestampToDate + }; + } +); \ No newline at end of file diff --git a/scripts/views/aboutview.js b/scripts/views/aboutview.js new file mode 100644 index 0000000..81c8ec4 --- /dev/null +++ b/scripts/views/aboutview.js @@ -0,0 +1,25 @@ +/*global define*/ +define( + [ 'util/el', 'views/dialog', 'models/localisationmodel', 'util/localizetext' ], + function ( elHelper, Dialog, Localisationmodel, loc ) { + function AboutView ( parentEl ) { + if ( ! ( this instanceof AboutView ) ) { + return new AboutView ( parentEl ); + } + + var self = this; + var buttonEl = elHelper.createButton( 'about.info', 'about.infotitle', 'nav-button info-button', parentEl ); + var dialog = Dialog( 'about-dialog', parentEl, buttonEl ); + var aboutEl = elHelper.createEl( 'div', 'about-content' ); + var textEl = document.querySelector( '.description' ); + + loc( textEl, 'innerHTML', 'index.description' ); + + aboutEl.appendChild( textEl ); + + dialog.add( aboutEl ); + } + + return AboutView; + } +); \ No newline at end of file diff --git a/scripts/views/appview.js b/scripts/views/appview.js new file mode 100644 index 0000000..663eadb --- /dev/null +++ b/scripts/views/appview.js @@ -0,0 +1,34 @@ +/*global define*/ +define( + [ 'util/el' ], + function ( elHelper ) { + // the app view, wrapping element of the app + // also updates the html element classes + function AppView ( parentEl ) { + if ( ! ( this instanceof AppView ) ) { + return new AppView( parentEl ); + } + + var self = this; + var el = elHelper.createEl( 'div', 'app', parentEl ); + + function showOnlineOptions () { + document.documentElement.classList.add( 'is-online' ); + + return self; + } + + function hideOnlineOptions () { + document.documentElement.classList.remove( 'is-online' ); + + return self; + } + + self.el = el; + self.showOnlineOptions = showOnlineOptions; + self.hideOnlineOptions = hideOnlineOptions; + } + + return AppView; + } +); \ No newline at end of file diff --git a/scripts/views/canvascontrolsview.js b/scripts/views/canvascontrolsview.js new file mode 100644 index 0000000..bc9dd1b --- /dev/null +++ b/scripts/views/canvascontrolsview.js @@ -0,0 +1,71 @@ +/*global define*/ +define( + [ 'util/addpublishers', 'util/el' ], + function ( addPublishers, elHelper ) { + // the controls for the workspace at the bottom of the screen + // zoom range and center buttons + function CanvasControlsView ( parentEl ) { + if ( ! ( this instanceof CanvasControlsView ) ) { + return new CanvasControlsView( parentEl ); + } + + var self = this; + var publishers = addPublishers( self, 'update', 'center', 'scale' ); + var isIgnoringInput = false; + var el = elHelper.createEl( 'div', 'workspace-controls clear', parentEl ); + + elHelper.createButton( 'controls.center', 'controls.centertitle', 'center-button button', el, centerButtonClicked ); + elHelper.createButton( 'controls.original', 'controls.originaltitle', 'scale-to-original-button button', el, scaleToOriginalButtonClicked ); + elHelper.createLabel( 'controls.zoom', 'control.zoomtitle', 'scale-label', el ); + + var scaleSliderEl = elHelper.createEl( 'input', 'scale-slider', el ); + scaleSliderEl.id = 'zoom' + scaleSliderEl.type = 'range' + scaleSliderEl.min = 0.01; + scaleSliderEl.max = 5; + scaleSliderEl.step = 0.001; + scaleSliderEl.addEventListener( 'input', scaleSliderChanged ); + scaleSliderEl.addEventListener( 'change', scaleSliderChanged ); + + function centerButtonClicked ( event ) { + publishers.center.dispatch(); + } + + function scaleSliderChanged ( event ) { + if ( ! isIgnoringInput ) { + publishers.scale.dispatch( parseFloat( scaleSliderEl.value ) ); + publishers.update.dispatch( 'scale', parseFloat( scaleSliderEl.value ) ); + } + } + + function scaleToOriginalButtonClicked ( event ) { + publishers.scale.dispatch( 1.00 ); + publishers.update.dispatch( 'scale', 1.00 ); + } + + // when setting scale, prevent infinite + // loop by ignoring input element + function setScale ( scale ) { + isIgnoringInput = true; + scaleSliderEl.value = scale; + isIgnoringInput = false; + + return self; + } + + function setValue ( key, value ) { + if ( key === 'scale' ) { + setScale( value ); + } + + return self; + } + + self.setScale = setScale; + self.setValue = setValue; + self.el = el; + } + + return CanvasControlsView; + } +) \ No newline at end of file diff --git a/scripts/views/canvasview.js b/scripts/views/canvasview.js new file mode 100644 index 0000000..49a2838 --- /dev/null +++ b/scripts/views/canvasview.js @@ -0,0 +1,86 @@ +/*global define*/ +define( + [ 'util/addpublishers', 'util/el', 'views/panzoom' ], + function ( addPublishers, elHelper, PanZoom ) { + // canvasview: a wrapper for the PanZoom workspace element + function CanvasView ( parentEl, buttonParentEl ) { + if ( ! ( this instanceof CanvasView ) ) { + return new CanvasView( parentEl, buttonParentEl ); + } + + var self = this; + var publishers = addPublishers( self, 'update', 'imagesizechange', 'scale', 'dblclick' ); + var imageSize = { width: 0, height: 0 }; + + var workspaceEl = elHelper.createEl( 'div', 'panzoom', parentEl ); + var canvasWrapperEl = elHelper.createEl( 'div', 'canvas-wrapper', workspaceEl ); + var canvasEl = elHelper.createEl( 'canvas', 'glitch-canvas', canvasWrapperEl ); + + var ctx = canvasEl.getContext( '2d' ); + + var panZoom = PanZoom( canvasWrapperEl, workspaceEl ) + .on( 'scale', function ( scale ) { + publishers.scale.dispatch( scale ); + publishers.update.dispatch( 'scale', scale ); + } ); + + var hideShowTimeoutId = NaN; + var lastClickTime = Date.now(); + + workspaceEl.addEventListener( 'dblclick', workspaceDoubleClicked ); + + function workspaceDoubleClicked ( event ) { + publishers.dblclick.dispatch(); + } + + function putImageData ( imageData ) { + canvasWrapperEl.style.width = imageData.width + 'px'; + canvasWrapperEl.style.height = imageData.height + 'px'; + + if ( imageSize.width !== imageData.width || imageSize.height !== imageData.height ) { + canvasEl.width = imageData.width; + canvasEl.height = imageData.height; + imageSize.width = imageData.width; + imageSize.height = imageData.height; + panZoom.animateToCenter(); + publishers.imagesizechange.dispatch(); + } + + ctx.putImageData( imageData, 0, 0 ); + panZoom.updateContainerBounds(); + } + + function createImageUrl ( callback ) { + return function () { + callback( canvasEl.toDataURL( 'image/jpeg', 100 ) ); + } + } + + function hide () { + clearTimeout( hideShowTimeoutId ); + workspaceEl.classList.remove( 'is-visible' ); + } + + function show () { + clearTimeout( hideShowTimeoutId ); + + hideShowTimeoutId = setTimeout( function () { + workspaceEl.classList.add( 'is-visible' ); + }, 400 ); + } + + self.putImageData = putImageData; + self.moveToCenter = panZoom.moveToCenter; + self.animateToCenter = panZoom.animateToCenter; + self.setScale = panZoom.setScale; + self.createImageUrl = createImageUrl; + self.hide = hide; + self.show = show; + self.resized = panZoom.resized; + self.el = workspaceEl; + self.panZoom = panZoom; + } + + return CanvasView; + } +); \ No newline at end of file diff --git a/scripts/views/controlsview.js b/scripts/views/controlsview.js new file mode 100644 index 0000000..0e0af01 --- /dev/null +++ b/scripts/views/controlsview.js @@ -0,0 +1,156 @@ +/*global define*/ +define( + [ 'util/addpublishers', 'util/el' ], + function ( addPublishers, elHelper ) { + // the control elements are used to change the appearance of the image + function ControlsView ( parentEl, buttonParentEl, params ) { + if ( ! ( this instanceof ControlsView ) ) { + return new ControlsView( parentEl, buttonParentEl, params ); + } + + params = params || { }; + + var self = this; + var publishers = addPublishers( self, 'update', 'random' ); + + var isIgnoringInput = false; + var isActive = true; + var activeTimeoutId = 0; + + var inputEls = { }; + var valueEls = { }; + + var controlsEl = elHelper.createEl( 'div', 'controls', parentEl ); + var controlsWrapperEl = elHelper.createEl( 'div', 'controls-wrapper', controlsEl ); + var buttonEl = elHelper.createButton( 'controls.controls', 'controls.controlstitle', 'controls-toggle-button button is-active', buttonParentEl, toggleControls ); + + for ( var key in params ) { + addControl( key, params[key] ); + } + + show(); + + elHelper.createButton( 'controls.randomize', 'controls.randomizetitle', 'random-button button', controlsWrapperEl, randomButtonClicked ); + + function loadInitialValues () { + // dispatch initial values when model is listening + var controlValues = getInputValues(); + + for ( var key in controlValues ) { + publishers.update.dispatch( key, controlValues[key] ); + } + } + + function addControl ( key, params ) { + var controlEl = elHelper.createEl( 'div', 'control', controlsWrapperEl ); + + elHelper.createLabel( 'controls.' + key, 'input-' + key, 'control-label', controlEl ); + + var inputEl = elHelper.createEl( 'input', 'control-input', controlEl ); + inputEl.setAttribute( 'data-key', key ); + inputEl.setAttribute( 'id', 'input-' + key ); + inputEl.type = 'range'; + inputEl.value = params.value || 0; + inputEl.min = params.min || 0; + inputEl.max = params.max || 100; + inputEl.addEventListener( 'input', inputUpdated ); + inputEl.addEventListener( 'change', inputUpdated ); + + inputEls[key] = inputEl; + + var valueEl = elHelper.createEl( 'input', 'control-value', controlEl ); + valueEl.setAttribute( 'data-key', key ); + valueEl.type = 'number'; + valueEl.value = params.value || 0; + valueEl.min = params.min || 0; + valueEl.max = params.max || 100; + valueEl.addEventListener( 'input', inputUpdated ); + valueEl.addEventListener( 'change', inputUpdated ); + + valueEls[key] = valueEl; + + inputUpdated( { target: inputEl } ); + } + + function inputUpdated ( event ) { + if ( isActive && ! isIgnoringInput ) { + var key = event.target.getAttribute( 'data-key' ); + var controlValues = getInputValues(); + + if ( controlValues[key] !== event.target.value ) { + controlValues[key] = parseInt( event.target.value, 10 ); + + publishers.update.dispatch( key, controlValues[key] ); + } + } + } + + function randomButtonClicked ( event ) { + if ( isActive ) { + publishers.random.dispatch(); + } + } + + function toggleControls () { + if ( isActive ) { + hide(); + } else { + show(); + } + } + + function hide () { + controlsEl.classList.remove( 'is-active' ); + buttonEl.classList.remove( 'is-active' ); + buttonParentEl.classList.remove( 'controls-enabled' ); + isActive = false; + + clearTimeout( activeTimeoutId ); + + activeTimeoutId = setTimeout( function () { + controlsEl.classList.remove( 'is-visible' ); + }, 500 ); + } + + function show () { + controlsEl.classList.add( 'is-visible' ); + isActive = true; + + clearTimeout( activeTimeoutId ); + + activeTimeoutId = setTimeout( function () { + controlsEl.classList.add( 'is-active' ); + buttonEl.classList.add( 'is-active' ); + buttonParentEl.classList.add( 'controls-enabled' ); + }, 10 ); + } + + function getInputValues () { + var result = { }; + + for ( var key in inputEls ) { + result[key] = parseInt( inputEls[key].value, 10 ); + } + + return result; + } + + // when setting a value, prevent dispatching + // of elements to avoid an infinite loop of + // input events + function setValue ( key, newValue ) { + isIgnoringInput = true; + + inputEls[key].value = newValue; + valueEls[key].value = newValue; + + isIgnoringInput = false; + } + + self.loadInitialValues = loadInitialValues; + self.setValue = setValue; + } + + return ControlsView; + } +); \ No newline at end of file diff --git a/scripts/views/dialog.js b/scripts/views/dialog.js new file mode 100644 index 0000000..d2e4fa6 --- /dev/null +++ b/scripts/views/dialog.js @@ -0,0 +1,121 @@ +/*global define*/ +define( + [ 'util/el', 'util/dom', 'util/addpublishers' ], + function ( elHelper, domHelper, addPublishers ) { + + var dialogInstances = [ ]; + + function closeOpenDialogInstances () { + dialogInstances.forEach( function ( instance ) { + instance.hide(); + } ); + } + + function Dialog ( cssClassName, parentEl, toggleEl ) { + if ( ! ( this instanceof Dialog ) ) { + return new Dialog( cssClassName, parentEl, toggleEl ); + } + + var self = this; + var publishers = addPublishers( self, 'hide show' ); + var isActive = false; + var animationTimeoutId = NaN; + var hasToggleEl = false; + + var dialogEl = elHelper.createEl( 'div', 'dialog color-bg-light ' + cssClassName, parentEl ); + + if ( toggleEl && domHelper.isElement( toggleEl ) ) { + hasToggleEl = true; + toggleEl.addEventListener( 'click', toggle ); + } + + function show () { + if ( ! isActive ) { + closeOpenDialogInstances(); + dialogEl.classList.add( 'is-visible' ); + isActive = true; + publishers.show.dispatch(); + + clearTimeout( animationTimeoutId ); + + animationTimeoutId = setTimeout( function () { + dialogEl.classList.add( 'is-active' ); + + if ( hasToggleEl ) { + toggleEl.classList.add( 'is-active' ); + } + }, 10 ); + } + + return self; + } + + function hide () { + if ( isActive ) { + dialogEl.classList.remove( 'is-active' ); + isActive = false; + publishers.hide.dispatch(); + + if ( hasToggleEl ) { + toggleEl.classList.remove( 'is-active' ); + } + + clearTimeout( animationTimeoutId ); + + animationTimeoutId = setTimeout( function () { + dialogEl.classList.remove( 'is-visible' ); + }, 500 ); + } + + return self; + } + + function toggle () { + if ( isActive ) { + hide(); + } else { + show(); + } + + return self; + } + + function add () { + var wrapperEl = document.createElement( 'div' ); + wrapperEl.classList.add( 'dialog-item' ); + dialogEl.appendChild( wrapperEl ); + + for ( var i = 0, len = arguments.length; i < len; i++ ) { + if ( typeof arguments[i] === 'string' ) { + arguments[i].split( ' ' ).forEach( function ( cssClassName ) { + wrapperEl.classList.add( cssClassName ); + } ); + } else { + arguments[i].wrapperEl = wrapperEl; + wrapperEl.appendChild( arguments[i] ); + } + } + + return self; + } + + function remove ( el ) { + el.parentNode.parentNode.removeChild( el.parentNode ); + return self; + } + + self.add = add; + self.remove = remove; + self.show = show; + self.hide = hide; + self.toggle = toggle; + self.el = dialogEl; + + dialogInstances.push( self ); + } + + Dialog.closeAll = closeOpenDialogInstances; + + return Dialog; + } +); \ No newline at end of file diff --git a/scripts/views/draganddropview.js b/scripts/views/draganddropview.js new file mode 100644 index 0000000..7304baa --- /dev/null +++ b/scripts/views/draganddropview.js @@ -0,0 +1,61 @@ +/*global define*/ +define( + [ 'util/browser', 'util/addpublishers' ], + function ( browser, addPublishers ) { + // the DragAndDropView handles the drag + drop events + // over the workspace and passes the uploaded file + function DragAndDropView ( el ) { + if ( ! ( this instanceof DragAndDropView ) ) { + return new DragAndDropView( el ); + } + + var self = this; + var publishers = addPublishers( self, 'drop' ); + var isOver = false; + + if ( browser.test( 'draganddrop' ) ) { + document.addEventListener( 'drop', dropped, false ); + document.addEventListener( 'dragover', dragHovered, false ); + document.addEventListener( 'dragleave', dragLeft, false ); + } + + function preventDefault ( event ) { + event.preventDefault(); + } + + function dragHovered ( event ) { + if ( ! isOver ) { + el.classList.add( 'drag-over' ); + isOver = true; + } + + preventDefault( event ); + } + + function dragLeft ( event ) { + if ( isOver ) { + el.classList.remove( 'drag-over' ); + isOver = false; + } + + preventDefault( event ); + } + + function dropped ( event ) { + preventDefault( event ); + + if ( + event.dataTransfer && + event.dataTransfer.files && + event.dataTransfer.files[0] + ) { + publishers.drop.dispatch( event.dataTransfer.files[0] ); + } + + el.classList.remove( 'drag-over' ); + } + } + + return DragAndDropView; + } +); \ No newline at end of file diff --git a/scripts/views/fullscreenview.js b/scripts/views/fullscreenview.js new file mode 100644 index 0000000..076022a --- /dev/null +++ b/scripts/views/fullscreenview.js @@ -0,0 +1,68 @@ +/*global define*/ +define( + [ 'util/browser', 'util/el' ], + function ( browser, elHelper ) { + // the fullscreen button + // includes a lot of code to account for the different browser implementations + function FullscreenView ( parentEl ) { + if ( ! ( this instanceof FullscreenView ) ) { + return new FullscreenView( parentEl ); + } + + var self = this; + var isInFullScreen = false; + var fullscreenButtonEl; + + if ( browser.test( 'fullscreen' ) ) { + fullscreenButtonEl = elHelper.createButton( 'controls.fullscreen', 'controls.fullscreentitle', 'fullscreen-button', parentEl, toggleFullscreen ); + + document.addEventListener( 'webkitfullscreenchange', fullscreenChanged, false ); + document.addEventListener( 'mozfullscreenchange', fullscreenChanged, false ); + document.addEventListener( 'fullscreenchange', fullscreenChanged, false ); + document.addEventListener( 'MSFullscreenChange', fullscreenChanged, false ); + } + + function fullscreenChanged ( event ) { + isInFullScreen = document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen; + + if ( isInFullScreen ) { + document.documentElement.classList.add( 'is-fullscreen' ); + } else { + document.documentElement.classList.remove( 'is-fullscreen' ); + } + } + + function toggleFullscreen () { + if ( isInFullScreen ) { + exitFullscreen(); + } else { + requestFullScreen( document.documentElement ); + } + } + + function requestFullScreen ( el ) { + if ( el.requestFullscreen ) { + el.requestFullscreen(); + } else if ( el.mozRequestFullScreen ) { + el.mozRequestFullScreen(); + } else if ( el.webkitRequestFullscreen ) { + el.webkitRequestFullscreen(); + } else if ( el.msRequestFullscreen ) { + el.msRequestFullscreen(); + } + } + + function exitFullscreen () { + if ( document.exitFullscreen ) { + document.exitFullscreen(); + } else if ( document.mozCancelFullScreen ) { + document.mozCancelFullScreen(); + } else if ( document.webkitExitFullscreen ) { + document.webkitExitFullscreen(); + } + } + } + + return FullscreenView; + } +); \ No newline at end of file diff --git a/scripts/views/indicatorview.js b/scripts/views/indicatorview.js new file mode 100644 index 0000000..071862b --- /dev/null +++ b/scripts/views/indicatorview.js @@ -0,0 +1,128 @@ +/*global define*/ +define( + [ 'util/el', 'util/localizetext' ], + function ( elHelper, loc ) { + // the indiecator view diesplays errors and warnings in the top right + // corner. they disappear after a while. the user can also click + // on them to make them go away + function IndicatorView ( parentEl ) { + if ( ! ( this instanceof IndicatorView ) ) { + return new IndicatorView( parentEl ); + } + + var self = this; + var addQueue = [ ]; + var removeQueue = [ ]; + var visibleNotificationCount = 0; + var isAdding = false; + + var timeToFadeOut = { + message: 3500, + error: 6000, + welcome: 7000 + }; + + var notificationsEl = elHelper.createEl( 'div', 'notifications', parentEl ); + + function showWelcome ( message, data, fadeOutDelay ) { + showNotification( 'welcome', message, data, fadeOutDelay ); + } + + function showMessage ( message, data ) { + showNotification( 'message', message, data ); + } + + function showError ( message, data ) { + showNotification( 'error', message, data ); + } + + function showNotification ( type, message, data, fadeOutDelay ) { + fadeOutDelay = fadeOutDelay || timeToFadeOut[type] || 7000; + + if ( isAdding ) { + addQueue.push( { type: type, message: message, data: data, fadeOutDelay: fadeOutDelay } ); + } else { + addNotification( type, { message: message, data: data, fadeOutDelay: fadeOutDelay } ); + } + } + + function addNotification ( type, params ) { + var notificationEl = elHelper.createEl( 'div', 'notification notification-' + type, notificationsEl ); + + if ( params.data && params.data.innerHTML && params.data.args && params.data.args.length ) { + loc.apply( null, [ notificationEl, 'innerHTML', params.message ].concat( params.data.args ) ); + } else { + loc( notificationEl, 'textContent', params.message ); + } + + notificationEl.id = 'notification-' + Date.now(); + notificationEl.addEventListener( 'click', notificationClicked ); + + notificationsEl.classList.add( 'is-active' ); + + isAdding = true; + + requestAnimationFrame( function () { + notificationEl.classList.add( 'is-active' ); + notificationEl.classList.add( 'is-visible' ); + visibleNotificationCount++; + } ); + + setTimeout( function () { + isAdding = false; + addMessagesFromQueue(); + }, 400 ); + + setTimeout( function () { + removeNotification( notificationEl ); + }, params.fadeOutDelay ); + } + + function addMessagesFromQueue () { + if ( addQueue.length && visibleNotificationCount < 4 ) { + var nextMessage = addQueue.shift(); + addNotification( nextMessage.type, { message: nextMessage.message, data: nextMessage.data } ); + } + } + + function removeNotification ( notificationEl ) { + if ( removeQueue.indexOf( notificationEl.id ) === -1 ) { + removeQueue.push( notificationEl.id ); + + requestAnimationFrame( function () { + notificationEl.classList.remove( 'is-active' ); + } ); + + setTimeout( function () { + requestAnimationFrame( function () { + removeQueue.splice( removeQueue.indexOf( notificationEl.id ), 1 ); + + notificationsEl.removeChild( notificationEl ); + visibleNotificationCount--; + addMessagesFromQueue(); + + if ( ! notificationsEl.children.length ) { + notificationsEl.classList.remove( 'is-active' ); + } + } ); + }, 500 ); + } + } + + function notificationClicked ( event ) { + if ( + event.target.classList.contains( 'notification' ) && + ! event.target.classList.contains( 'notification-error' ) + ) { + removeNotification( event.target ); + } + } + + self.showMessage = showMessage; + self.showError = showError; + self.showWelcome = showWelcome; + } + + return IndicatorView; + } +); \ No newline at end of file diff --git a/scripts/views/navview.js b/scripts/views/navview.js new file mode 100644 index 0000000..71340de --- /dev/null +++ b/scripts/views/navview.js @@ -0,0 +1,277 @@ +/*global define*/ +define( + [ 'util/el', 'util/dom', 'views/dialog', 'util/addpublishers', 'util/math', 'util/localizetext' ], + function ( elHelper, domHelper, Dialog, addPublishers, mathHelpers, loc ) { + function NavView ( parentEl ) { + if ( ! ( this instanceof NavView ) ) { + return new NavView( parentEl ); + } + + var isActive = false; + var self = this; + var el = elHelper.createEl( 'nav', 'nav color-bg', parentEl ); + var publishers = addPublishers( self, 'togglestart', 'toggleend' ); + + var buttonTextEl = elHelper.createEl( 'span', 'nav-toggle-button-text' ) + loc( buttonTextEl, 'textContent', 'nav.menu' ); + loc( buttonTextEl, 'title', 'nav.menutitle' ); + + var buttonSVGWrapperEl = document.createElement( 'div' ); + buttonSVGWrapperEl.classList.add( 'svg-wrapper' ); + + var svgEl = document.getElementById( 'svg' ); + svgEl.setAttribute( 'viewBox', '0 0 24 24' ); + + buttonSVGWrapperEl.appendChild( svgEl ); + + var svgGroupEl = document.createElementNS( 'http://www.w3.org/2000/svg', 'g' ); + svgGroupEl.setAttribute( 'id', 'menu' ); + svgGroupEl.setAttributeNS( null, 'fill', '#000' ); + svgEl.appendChild( svgGroupEl ); + + var svgRect1El = elHelper.createEl( 'rect', null, svgGroupEl ); + svgRect1El.setAttribute( 'id', 'rect-1' ); + svgRect1El.setAttributeNS( null, 'x', '3' ); + svgRect1El.setAttributeNS( null, 'y', '6' ); + svgRect1El.setAttributeNS( null, 'width', '18' ); + svgRect1El.setAttributeNS( null, 'height', '2' ); + + var svgRect2El = elHelper.createEl( 'rect', null, svgGroupEl ); + svgRect2El.setAttributeNS( null, 'id', 'rect-2' ); + svgRect2El.setAttributeNS( null, 'x', '3' ); + svgRect2El.setAttributeNS( null, 'y', '11' ); + svgRect2El.setAttributeNS( null, 'width', '18' ); + svgRect2El.setAttributeNS( null, 'height', '2' ); + + var svgRect3El = elHelper.createEl( 'rect', null, svgGroupEl ); + svgRect3El.setAttributeNS( null, 'id', 'rect-3' ); + svgRect3El.setAttributeNS( null, 'x', '3' ); + svgRect3El.setAttributeNS( null, 'y', '16' ); + svgRect3El.setAttributeNS( null, 'width', '18' ); + svgRect3El.setAttributeNS( null, 'height', '2' ); + + buttonSVGWrapperEl.appendChild( svgEl ); + + var buttonEl = elHelper.createButton( buttonTextEl, 'nav.menutitle', 'nav-toggle-button', parentEl ); + buttonEl.appendChild( buttonSVGWrapperEl ); + buttonEl.addEventListener( 'click', toggle, false ); + + var headlineEl = elHelper.createEl( 'h1', 'nav-headline', el ); + headlineEl.textContent = document.title; + + var navBreakPoint = 600; + var navWidth = 300; + var navTouchPadding = 60; + var isSwiping = false; + var touchStartPos = { x: 0, y: 0 }; + var touchPos = { x: 0, y: 0 }; + var touchId = 0; + var translateX = -navWidth; + var i = 0, len = 0; + var touch; + + parentEl.addEventListener( 'touchstart', touchStarted ); + + function toggle () { + if ( ! isActive ) { + activate() + } else { + deactivate() + } + } + + function activate () { + isActive = true; + + requestAnimationFrame( function () { + el.classList.add( 'is-active' ); + buttonEl.classList.add( 'is-active' ); + } ); + + publishers.togglestart.dispatch( true ); + + setTimeout( function () { + publishers.toggleend.dispatch( true ); + }, 300 ); + } + + function deactivate () { + isActive = false; + Dialog.closeAll(); + + requestAnimationFrame( function () { + el.classList.remove( 'is-active' ); + buttonEl.classList.remove( 'is-active' ); + } ); + + publishers.togglestart.dispatch( false ); + + setTimeout( function () { + publishers.toggleend.dispatch( false ); + }, 300 ); + } + + function closeSmallScreenNav () { + if ( window.innerWidth <= navBreakPoint ) { + deactivate(); + } + } + + function swipeStarted ( x, y, identifier ) { + if ( ! isSwiping ) { + parentEl.addEventListener( 'touchmove', touchMoved ); + parentEl.addEventListener( 'touchend', touchEnded ); + + isSwiping = true; + touchIdentifier = identifier; + touchStartPos.x = x; + touchStartPos.y = y; + touchPos.x = x; + touchPos.y = y; + + requestAnimationFrame( function () { + el.classList.add( 'is-swiping' ); + buttonEl.classList.add( 'is-swiping' ); + } ); + } + } + + function swipeStopped () { + if ( isSwiping ) { + parentEl.removeEventListener( 'touchmove', touchMoved ); + parentEl.addEventListener( 'touchend', touchEnded ); + isSwiping = false; + + requestAnimationFrame( function () { + el.classList.remove( 'is-swiping' ); + buttonEl.classList.remove( 'is-swiping' ); + + // remove inline style, so that item can move to + // transform values from css file + domHelper.setTransform( el, '' ); + domHelper.setTransform( buttonEl, '' ); + domHelper.setTransform( svgRect1El, '' ); + domHelper.setTransform( svgRect2El, '' ); + domHelper.setTransform( svgRect3El, '' ); + domHelper.setTransform( svgGroupEl, '' ); + svgGroupEl.style.fill = ''; + buttonTextEl.style.width = ''; + buttonTextEl.style.opacity = ''; + } ); + + var dx = touchPos.x - touchStartPos.x; + + if ( translateX > -navWidth && translateX < 0 && Math.abs( dx ) > 0 ) { + if ( translateX < -navWidth / 2 ) { + deactivate(); + } else { + activate(); + } + } + } + } + + function swiped ( x, y, identifier ) { + touchPos.x = x; + touchPos.y = y; + + var dx = touchPos.x - touchStartPos.x; + var wasTranslateUpdated = false; + + if ( isActive ) { + if ( dx < 0 && dx >= -navWidth ) { + wasTranslateUpdated = true; + translateX = Math.round( Math.max( dx, -navWidth ) ); + } else { + swipeStopped(); + } + } else { + if ( dx > 0 && dx <= navWidth ) { + wasTranslateUpdated = true; + translateX = -navWidth + Math.round( Math.min( dx, navWidth ) ); + } else { + swipeStopped(); + } + } + + if ( wasTranslateUpdated ) { + requestAnimationFrame( function () { + domHelper.setTransform( el, 'translateX(' + translateX + 'px)' ); + + var buttonTransform = 'translateX(' + mathHelpers.mapRange( translateX, -navWidth, 0, 0, 242 ) + 'px)'; + domHelper.setTransform( buttonEl, buttonTransform ); + + var rect1Transform = [ + 'rotateZ(' + mathHelpers.mapRange( translateX, -navWidth, 0, 0, 45 ) + 'deg)', + 'translateY(' + mathHelpers.mapRange( translateX, -navWidth, 0, 0, 5.1 ) + 'px)' + ].join( ' ' ); + + domHelper.setTransform( svgRect1El, rect1Transform ); + + domHelper.setTransform( svgRect2El, 'scaleX(' + mathHelpers.mapRange( translateX, -navWidth, 0, 1, 0 ) + ')' ); + + var rect3Transform = [ + 'rotateZ(' + mathHelpers.mapRange( translateX, -navWidth, 0, 0, -45 ) + 'deg)', + 'translateY(' + mathHelpers.mapRange( translateX, -navWidth, 0, 0, -5.1 ) + 'px)' + ].join( ' ' ); + + domHelper.setTransform( svgRect3El, rect3Transform ); + + domHelper.setTransform( svgGroupEl, 'rotateZ(' + mathHelpers.mapRange( translateX, -navWidth, 0, 0, -90 ) + 'deg)' ); + svgGroupEl.style.fill = 'hsl(0, 0%, ' + mathHelpers.mapRange( translateX, -navWidth, 0, 0, 100 ) + '%)'; + + buttonTextEl.style.width = mathHelpers.mapRange( translateX, -navWidth, 0, 50, 0 ) + 'px'; + buttonTextEl.style.opacity = mathHelpers.mapRange( translateX, -navWidth, 0, 1.5, 0, true ).toFixed( 2 ); + } ); + } + } + + function touchStarted ( event ) { + if ( window.innerWidth <= navBreakPoint && ! isSwiping ) { + for ( i = 0, len = event.touches.length; i < len; i++ ) { + touch = event.touches[i]; + + if ( + ( ! isActive && touch.clientX <= navTouchPadding ) || + ( isActive && touch.clientX <= navTouchPadding + navWidth ) + ) { + swipeStarted( touch.clientX, touch.clientY, touch.identifier ); + break; + } + } + } + } + + function touchMoved ( event ) { + if ( event.changedTouches ) { + var hasTouch = false; + + for ( i = 0, len = event.touches.length; i < len; i++ ) { + touch = event.touches[i]; + + if ( touch.identifier === touchIdentifier ) { + swiped( touch.clientX, touch.clientY, touch.identifier ); + hasTouch = true; + break; + } + } + + if ( ! hasTouch ) { + swipeStopped(); + } + } else { + swipeStopped(); + } + } + + function touchEnded ( event ) { + swipeStopped(); + } + + self.el = el; + self.closeSmallScreenNav = closeSmallScreenNav; + } + + return NavView; + } +) \ No newline at end of file diff --git a/scripts/views/openfileview.js b/scripts/views/openfileview.js new file mode 100644 index 0000000..5a84768 --- /dev/null +++ b/scripts/views/openfileview.js @@ -0,0 +1,234 @@ +/*global define*/ +define( + [ 'util/browser', 'util/addpublishers', 'util/el', 'util/time', 'util/localizetext', 'views/dialog' ], + function ( browser, addPublishers, elHelper, timeHelper, loc, Dialog ) { + function OpenFileView ( parentEl ) { + if ( ! ( this instanceof OpenFileView ) ) { + return new OpenFileView( parentEl ); + } + + var self = this; + var fileOpenEl; + var storageListEl; + var emptyListEl; + var navButtonEl; + var dialog; + + var publishers = addPublishers( self, 'openfile', 'deletefromlocalstorage', 'openfromlocalstorage', 'deletefromimgur' ); + + // check if the browser supports the filereader API + // before displaying upload button + if ( browser.getFeature( window, 'FileReader' ) ) { + navButtonEl = elHelper.createButton( 'file.open', 'file.opentitle', 'open-button nav-button', parentEl ); + dialog = Dialog( 'open-file-dialog', parentEl, navButtonEl ); + + var fileLabelEl = elHelper.createLabel( 'file.importtitle', 'input-file', 'file-label label' ); + + fileInputEl = document.createElement( 'input' ); + fileInputEl.classList.add( 'file-input' ); + fileInputEl.type = 'file'; + fileInputEl.id = 'input-file'; + fileInputEl.accept = 'image/*'; + + fileInputEl.addEventListener( 'change', fileSelected ); + + var fileLabelButtonEl = elHelper.createLabel( 'file.import', 'input-file', 'file-button button' ); + + dialog.add( fileLabelEl, fileInputEl, fileLabelButtonEl ); + + self.fileinput = fileInputEl; + } + + if ( browser.test( 'localforage' ) ) { + storageListEl = elHelper.createEl( 'ul', 'storage-list dialog-list' ); + + var storageLabelEl = elHelper.createLabel( 'file.recent', 'file.recenttitle', 'load-label label' ); + + dialog.add( storageLabelEl, storageListEl ); + } + + function fileSelected ( event ) { + if ( + event.target && + event.target.files && + event.target.files[0] + ) { + publishers.openfile.dispatch( event.target.files[0] ); + } + } + + // compare all items in the list with what's in localstorage + // and add, remove and edit them accordingly, + // including images shared on imgur + function updateList ( entries ) { + if ( storageListEl ) { + if ( entries && Object.keys( entries ).length ) { + if ( emptyListEl ) { + removeListItem( emptyListEl ); + emptyListEl = null; + } + + var storageListItemEl; + var offlineLinkEl; + + for ( var uid in entries ) { + storageListItemEl = storageListEl.querySelector( '[data-uid="' + uid + '"]' ); + + updateListItem( storageListItemEl, uid, entries[uid] ); + } + + var storageListItemEls = storageListEl.querySelectorAll( '[data-uid]' ); + + for ( var i = 0, len = storageListItemEls.length; i < len; i++ ) { + var itemUid = storageListItemEls[i].getAttribute( 'data-uid' ); + + if ( itemUid && ! entries[itemUid] ) { + removeListItem( storageListItemEls[i] ); + } + } + + } else { + // no entries but there are still elements in dom + if ( entries && Object.keys( entries ).length === 0 ) { + var storageListItemEls = storageListEl.querySelectorAll( '[data-uid]' ); + + for ( var i = 0, len = storageListItemEls.length; i < len; i++ ) { + removeListItem( storageListItemEls[i] ); + } + } + + if ( ! emptyListEl ) { + emptyListEl = elHelper.createEl( 'li', 'no-items' ); + loc( emptyListEl, 'textContent', 'file.norecent' ); + storageListEl.appendChild( emptyListEl ); + } + } + } + + return self; + } + + function updateListItem ( listItemEl, uid, entry ) { + if ( entry.src && entry.values && ! listItemEl ) { + addListItem( uid, entry ); + } else { + if ( listItemEl ) { + if ( ! entry.src && ! entry.values ) { + removeListItem( listItemEl ); + } else { + var offlineLinkEl = listItemEl.querySelector( '.entry-shared-button-wrapper' ); + + if ( ! entry.deleteHash && offlineLinkEl ) { + offlineLinkEl.parentNode.removeChild( offlineLinkEl ); + listItemEl.classList.remove( 'has-offline-button' ); + } + + // add link el to open item online instead + if ( entry.deleteHash && ! offlineLinkEl ) { + addOnlineButtons( listItemEl, entry.deleteHash, entry.publicUrl, uid ); + } + } + } + } + } + + function addListItem ( uid, entry ) { + if ( entry ) { + var date = timeHelper.timestampToDate( entry.timestamp ); + + var listItemEl = elHelper.createEl( 'li', 'entry clear dialog-list-item', storageListEl ); + listItemEl.setAttribute( 'data-uid', uid ); + + var listItemThumbnailEl = elHelper.createEl( 'img', 'entry-thumb', listItemEl ); + listItemThumbnailEl.src = entry.thumbnail; + listItemThumbnailEl.addEventListener( 'click', loadItemFn( uid ) ); + + var textWrapperEl = elHelper.createEl( 'p', 'entry-text', listItemEl ); + + var listItemNameEl = elHelper.createEl( 'p', 'entry-name', textWrapperEl ); + + if ( entry.name ) { + listItemNameEl.textContent = entry.name; + } else { + loc( listItemNameEl, 'textContent', 'file.untitled' ); + } + + var listItemDateEl = elHelper.createEl( 'time', 'entry-datetime', textWrapperEl ); + listItemDateEl.setAttribute( 'datetime', date.toISOString() ); + + var dateEl = elHelper.createEl( 'span', 'entry-date', listItemDateEl ); + dateEl.textContent = timeHelper.dateToLocalStr( date ); + + var timeEl = elHelper.createEl( 'span', 'entry-time', listItemDateEl ); + timeEl.textContent = timeHelper.timeToLocalStr( date ); + + var buttonWrapperEl = elHelper.createEl( 'div', 'entry-button-wrapper', listItemEl ); + + elHelper.createButton( 'file.del', 'file.deltitle', 'item-delete-button button', buttonWrapperEl, removeItemFn( uid ) ); + elHelper.createButton( 'file.openimage', 'file.openimagetitle', 'item-load-button button', buttonWrapperEl, loadItemFn( uid ) ); + + if ( entry.deleteHash && entry.publicUrl ) { + addOnlineButtons( listItemEl, entry.deleteHash, entry.publicUrl, uid ); + } + } + } + + function addOnlineButtons ( listEl, deleteHash, publicUrl, uid ) { + var sharedButtonWrapperEl = elHelper.createEl( 'div', 'entry-shared-button-wrapper is-online-only', listEl ); + + listEl.classList.add( 'has-offline-button' ); + + elHelper.createButton( + 'file.offline', + 'file.offlinetitle', + 'item-offline-button button', + sharedButtonWrapperEl, + removeItemFromImgurFn( uid, deleteHash ) + ); + + elHelper.createLink( + 'file.openlink', + 'file.openlinktitle', + publicUrl, + '_blank', + 'entry-shared-link button', + sharedButtonWrapperEl + ); + } + + function removeListItem ( itemEl ) { + itemEl.parentNode.removeChild( itemEl ); + } + + function removeItemFn ( uid ) { + return function () { + publishers.deletefromlocalstorage.dispatch( uid ); + } + } + + function removeItemFromImgurFn ( uid, deleteHash ) { + return function () { + var buttonEl = storageListEl.querySelector( '[data-uid="' + uid + '"] .item-offline-button' ); + + if ( buttonEl ) { + buttonEl.setAttribute( 'disabled', 'disabled' ); + } + + publishers.deletefromimgur.dispatch( uid, deleteHash ); + } + } + + function loadItemFn ( uid ) { + return function () { + dialog.hide(); + publishers.openfromlocalstorage.dispatch( uid ); + } + } + + self.updateList = updateList; + self.dialog = dialog; + } + + return OpenFileView; + } +); \ No newline at end of file diff --git a/scripts/views/panzoom.js b/scripts/views/panzoom.js new file mode 100644 index 0000000..d9dd6b9 --- /dev/null +++ b/scripts/views/panzoom.js @@ -0,0 +1,371 @@ +/*global define*/ +// most of this was shamelessly taken from @jakearchibald's svgomg ui: +// https://github.com/jakearchibald/svgomg/blob/master/src/js/page/ui/pan-zoom.js +define( + [ 'util/css', 'util/dom', 'util/addpublishers' ], + function ( cssHelper, domHelper, addPublishers ) { + function getXY ( obj ) { + return { + x: obj.pageX, + y: obj.pageY + }; + } + + function touchDistance ( touch1, touch2 ) { + var x = Math.abs( touch2.x - touch1.x ); + var y = Math.abs( touch2.y - touch1.y ); + return Math.sqrt( x * x + y * y ); + } + + function getMidpoint ( point1, point2 ) { + return { + x: ( point1.x + point2.x ) / 2, + y: ( point1.y + point2.y ) / 2 + }; + } + + function getPoints ( event ) { + if ( event.touches ) { + return Array.prototype.map.call( event.touches, getXY ); + } else { + return [ getXY( event ) ]; + } + } + + function PanZoom ( containerEl, targetEl, opts ) { + if ( ! ( this instanceof PanZoom ) ) { + return new PanZoom ( targetEl, containerEl, opts ); + } + + var self = this; + var canZoomWithPonter = true; + var publishers = addPublishers( self, 'scale' ); + opts = opts || { } + + var shouldCaptureFn = opts.shouldCaptureFn || function ( el ) { return true; }; + var limitToContainer = typeof opts.limitToContainer === 'boolean' ? opts.limitToContainer : true; + var limitPadding = opts.limitPadding || 50; + + var matrix = cssHelper.getCSSMatrix( targetEl ); + var transform = cssHelper.cssMatrixToTransformObj( matrix ); + + var x = transform.translateX || 0; + var y = transform.translateY || 0; + var scale = 1; + var active = 0; + var lastPoints = [ ]; + var containerBounds; + var updateAnimationFrameId = NaN; + var scaleAnimationFrameId = NaN; + var centerAnimationFrameId = NaN; + var resizeTimeoutId = NaN; + var targetElSize = { width: 100, height: 100 }; + var containerElSize = { width: 100, height: 100 }; + var centerScale = 1; + + containerEl.addEventListener( 'mousedown', pointerPressed ); + containerEl.addEventListener( 'touchstart', pointerPressed ); + containerEl.addEventListener( 'wheel', wheelTurned ); + + window.addEventListener( 'resize', resized ); + + targetEl.style.WebkitTransformOrigin = targetEl.style.transformOrigin = '0 0'; + + updateContainerBounds(); + + function reset () { + // x = transform.translateX || 0; + // y = transform.translateY || 0; + + updateValues ( transform.translateX || 0, transform.translateY || 0, 1 ); + } + + function updateValues ( newX, newY, newScale, targetBounds ) { + cancelAnimationFrame( updateAnimationFrameId ); + + if ( limitToContainer && targetEl !== containerEl && containerBounds ) { + targetBounds = targetBounds || targetEl.getBoundingClientRect(); + + if ( newX !== x || newY !== y || newScale !== scale ) { + var scaleDelta = 1 / ( scale / newScale ); + + if ( newX + targetBounds.width * scaleDelta < limitPadding ) { + newX = limitPadding - targetBounds.width * scaleDelta; + } + + if ( newX > containerBounds.width - limitPadding ) { + newX = containerBounds.width - limitPadding; + } + + if ( newY + targetBounds.height * scaleDelta < limitPadding ) { + newY = limitPadding - targetBounds.height * scaleDelta; + } + + if ( newY > containerBounds.height - limitPadding ) { + newY = containerBounds.height - limitPadding; + } + } + } + + newScale = Math.min( 5, Math.max( 0.01, newScale ) ); + + if ( scale === newScale && newScale === 5 ) { + return; + } + + x = newX; + y = newY; + scale = newScale + + publishers.scale.dispatch( scale ); + + updateAnimationFrameId = requestAnimationFrame( update ); + } + + function update () { + targetEl.style.WebkitTransform = targetEl.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0) scale(' + scale + ')'; + } + + function wheelTurned ( event ) { + if ( ! shouldCaptureFn( event.target ) ) { return; } + if ( ! canZoomWithPonter ) { return; } + event.preventDefault(); + + var targetBounds = targetEl.getBoundingClientRect(); + var delta = event.deltaY; + + if ( event.deltaMode === 1 ) { // 1 is "lines", 0 is "pixels" + // Firefox uses "lines" when mouse is connected + delta *= 15; + } + + // stop mouse wheel producing huge values + delta = Math.max( Math.min( delta, 60 ), -60 ); + + var scaleDiff = ( delta / 300 ) + 1; + + // avoid to-small values + if ( scale * scaleDiff < 0.05 ) { return; } + + updateValues( + x - ( event.pageX - targetBounds.left ) * ( scaleDiff - 1 ), + y - ( event.pageY - targetBounds.top ) * ( scaleDiff - 1 ), + scale * scaleDiff, + targetBounds + ); + } + + function firstPointerPressed ( event ) { + document.addEventListener( 'mousemove', pointerMoved ); + document.addEventListener( 'mouseup', pointerReleased ); + document.addEventListener( 'touchmove', pointerMoved ); + document.addEventListener( 'touchend', pointerReleased ); + } + + function pointerPressed ( event ) { + if ( event.type == 'mousedown' && event.which != 1 ) { + return; + } + + if ( ! shouldCaptureFn( event.target ) ) { + return; + } + + if ( domHelper.isDescendant( containerEl, event.target ) ) { + event.preventDefault(); + + lastPoints = getPoints( event ); + active++; + + if ( active === 1 ) { + firstPointerPressed( event ); + } + } + } + + function pointerMoved ( event ) { + if ( event && event.target && domHelper.isDescendant( containerEl, event.target ) ) { + event.preventDefault(); + + var points = getPoints( event ); + var averagePoint = points.reduce( getMidpoint ); + var averageLastPoint = lastPoints.reduce( getMidpoint ); + var targetBounds = targetEl.getBoundingClientRect(); + + var tmpX = x + averagePoint.x - averageLastPoint.x; + var tmpY = y + averagePoint.y - averageLastPoint.y; + + if ( points[1] ) { + if ( ! canZoomWithPonter ) { return; } + var scaleDiff = touchDistance( points[0], points[1] ) / touchDistance( lastPoints[0], lastPoints[1] ); + + updateValues( + tmpX - ( averagePoint.x - targetBounds.left ) * ( scaleDiff - 1 ), + tmpY - ( averagePoint.y - targetBounds.top ) * ( scaleDiff - 1 ), + scale * scaleDiff, + targetBounds + ); + } else { + updateValues( tmpX, tmpY, scale ); + } + + lastPoints = points; + } + } + + function pointerReleased ( event ) { + event.preventDefault(); + active--; + lastPoints.pop(); + + if ( active ) { + lastPoints = getPoints( event ); + return; + } + + document.removeEventListener( 'mousemove', pointerMoved ); + document.removeEventListener( 'mouseup', pointerReleased ); + document.removeEventListener( 'touchmove', pointerMoved ); + document.removeEventListener( 'touchend', pointerReleased ); + } + + function updateContainerBounds () { + containerElSize = { + width: containerEl.clientWidth, + height: containerEl.clientHeight + } + + targetElSize = { + width: targetEl.clientWidth, + height: targetEl.clientHeight + }; + + containerBounds = containerEl.getBoundingClientRect(); + updateValues( x, y, scale ); + } + + function resized () { + clearTimeout( resizeTimeoutId ); + + resizeTimeoutId = setTimeout( function () { + updateContainerBounds(); + + if ( Math.abs( scale - centerScale ) <= 0.01 ) { + animateToCenter(); + } + }, 100 ); + } + + function setToCenter () { + var centerValues = getCenterValues(); + updateValues ( centerValues.x, centerValues.y, centerValues.scale ); + + return self; + } + + function animateToCenter () { + var deltaX = 0; + var deltaY = 0; + var deltaScale = 0; + var easing = 0.1; + var centerValues = getCenterValues(); + + centerScale = centerValues.scale; + + cancelAnimationFrame( scaleAnimationFrameId ); + cancelAnimationFrame( centerAnimationFrameId ); + + function centerAnimationStep () { + deltaX = centerValues.x - x; + deltaY = centerValues.y - y; + deltaScale = centerValues.scale - scale; + + if ( + Math.abs( deltaX ) > 1 || + Math.abs( deltaY ) > 1 || + Math.abs( deltaScale ) > 0.01 + ) { + updateValues( x + deltaX * easing, y + deltaY * easing, scale + deltaScale * easing ); + + centerAnimationFrameId = requestAnimationFrame( centerAnimationStep ); + } else { + updateValues( centerValues.x, centerValues.y, centerValues.scale ); + } + } + + centerAnimationFrameId = requestAnimationFrame( centerAnimationStep ); + + return self; + } + + function settingUpdated ( key, value ) { + if ( key === 'canZoomWithPointer' && typeof value === 'boolean' ){ + canZoomWithPonter = value; + } + } + + function setScale ( newScale ) { + var targetX = ( containerElSize.width - targetElSize.width * newScale ) / 2; + var targetY = ( containerElSize.height - targetElSize.height * newScale ) / 2; + var deltaX = 0; + var deltaY = 0; + var deltaScale = 0; + var easing = 0.2; + + cancelAnimationFrame( scaleAnimationFrameId ); + cancelAnimationFrame( centerAnimationFrameId ); + + function scaleAnimationStep () { + deltaX = targetX - x; + deltaY = targetY - y; + deltaScale = newScale - scale; + + if ( + Math.abs( deltaX ) > 1 || + Math.abs( deltaY ) > 1 || + Math.abs( deltaScale ) > 0.01 + ) { + updateValues( x + deltaX * easing, y + deltaY * easing, scale + deltaScale * easing ); + + scaleAnimationFrameId = requestAnimationFrame( scaleAnimationStep ); + } else { + updateValues( targetX, targetY, newScale ); + } + } + + scaleAnimationStep(); + + return self; + } + + function getCenterValues () { + updateContainerBounds(); + + var targetScale = 1; + + if ( targetElSize.width > containerElSize.width || targetElSize.height > containerElSize.height ) { + targetScale = Math.min( + containerElSize.width / targetElSize.width, + ( containerElSize.height - 80 ) / targetElSize.height + ); + } + + return { + x: ( containerElSize.width - targetElSize.width * targetScale ) / 2, + y: ( containerElSize.height - targetElSize.height * targetScale ) / 2, + scale: targetScale + }; + } + + this.updateContainerBounds = updateContainerBounds; + this.reset = reset; + this.setToCenter = setToCenter; + this.animateToCenter = animateToCenter; + this.setScale = setScale; + this.settingUpdated = settingUpdated; + this.resized = resized; + } + + return PanZoom; + } +); \ No newline at end of file diff --git a/scripts/views/saveview.js b/scripts/views/saveview.js new file mode 100644 index 0000000..8ee45d9 --- /dev/null +++ b/scripts/views/saveview.js @@ -0,0 +1,87 @@ +/*global define*/ +define( + [ 'util/el', 'util/addpublishers', 'util/browser', 'views/dialog', 'util/time' ], + function ( elHelper, addPublishers, browser, Dialog, timeHelper ) { + function SaveView ( parentEl ) { + if ( ! ( this instanceof SaveView ) ) { + return new SaveView( parentEl ); + } + + var self = this; + var publishers = addPublishers( self, 'savetolocalstorage', 'show' ); + + var saveButtonEl; + var navButtonEl; + var dialog; + var downloadLinkEl; + var date; + var fileId; + var isActive = false; + + if ( browser.test( 'localforage' ) ) { + navButtonEl = elHelper.createButton( 'file.saveinbrowser', 'file.saveinbrowsertitle', 'nav-button save-view-button', parentEl ); + + dialog = Dialog( 'save-dialog', parentEl, navButtonEl ); + + downloadLinkEl = elHelper.createLink( + 'file.download', + 'file.downloadtitle', + null, null, + 'download-link button' + ); + + downloadLinkEl.target = '_blank'; + + saveButtonEl = elHelper.createButton( 'file.save', 'file.savetitle', 'save-button button', null, saveButtonClicked ) + + dialog + .on( 'show', activate ) + .on( 'hide', deactivate ) + .add( saveButtonEl, downloadLinkEl ); + } + + function saveButtonClicked ( event ) { + dialog.toggle(); + publishers.savetolocalstorage.dispatch(); + } + + // the href attribute of the download link is updated every time + // we change a parameter + function updateDownloadLink ( newUrl, fileName ) { + fileName = fileName || 'glitched'; + + var newNameParts = fileName.split( '/' ); + var newName = newNameParts.length > 1 ? newNameParts.pop() : newNameParts[0]; + newName = newName.split( '.' ).shift(); + + date = new Date(); + fileId = timeHelper.dateTimeToLocalStr( date ); + var newFileName = ( newName + '-glitched-' + fileId + '.png' ) + newFileName = newFileName.replace( /(\s|\/|:)/gmi, '-' ); + + // setting the download attribute makes the browser + // download the link target instead of opening it + downloadLinkEl.setAttribute( 'download', newFileName ); + downloadLinkEl.href = newUrl; + } + + function activate () { + isActive = true; + publishers.show.dispatch(); + } + + function deactivate () { + isActive = false; + } + + function getActive () { + return isActive; + } + + self.updateDownloadLink = updateDownloadLink; + self.getActive = getActive; + } + + return SaveView; + } +); \ No newline at end of file diff --git a/scripts/views/settingsview.js b/scripts/views/settingsview.js new file mode 100644 index 0000000..174b59c --- /dev/null +++ b/scripts/views/settingsview.js @@ -0,0 +1,130 @@ +/*global define*/ +define( + [ 'util/el', 'views/dialog', 'util/addpublishers', 'util/localizetext' ], + function ( elHelper, Dialog, addPublishers, loc ) { + function SettingsView ( parentEl ) { + if ( ! ( this instanceof SettingsView ) ) { + return new SettingsView ( parentEl ); + } + + var self = this; + var publishers = addPublishers( self, 'settingchange' ); + + var buttonEl = elHelper.createButton( 'settings.settings', 'settings.settingstitle', 'nav-button settings-button', parentEl ); + var dialog = Dialog( 'settings-dialog', parentEl, buttonEl ); + var animationFrameIds = { }; + + function addSetting ( name, value, options ) { + if ( ! dialog.el.querySelector( '#setting-' + name ) ) { + if ( name === 'language' ) { + dialog.add( 'is-online-only', makeSettingEl( name, value, options ) ); + } else { + dialog.add( makeSettingEl( name, value, options ) ); + } + } + } + + function makeSettingEl ( name, value, options ) { + var wrapperEl = elHelper.createEl( 'div', 'setting' ); + var labelEl = elHelper.createLabel( 'settings.' + name.toLowerCase(), 'setting-' + name, 'setting-label', wrapperEl ); + var inputEl; + + if ( options ) { + if ( Array.isArray( options ) ) { + inputEl = elHelper.createEl( 'select', 'setting-input setting-select', wrapperEl ); + + var optionEl; + + options.forEach( function ( option ) { + optionEl = elHelper.createEl( 'option', null, inputEl ); + optionEl.value = option; + + loc( optionEl, 'textContent', 'settings.' + name + 'options.' + option ); + + if ( option === value ) { + optionEl.selected = true + } + } ); + } + } else { + if ( typeof value === 'boolean' ) { + inputEl = elHelper.createEl( 'input', 'setting-input setting-checkbox', wrapperEl ); + inputEl.type = 'checkbox'; + + if ( value === true ) { + inputEl.checked = true; + } + } + } + + if ( inputEl ) { + inputEl.id = 'setting-' + name; + inputEl.setAttribute( 'data-setting', name ); + inputEl.addEventListener( 'change', settingInputChanged ); + } + + return wrapperEl; + } + + function settingInputChanged ( event ) { + var target = event.target; + + if ( event.target.classList.contains( 'setting-input' ) ) { + var inputEl = event.target; + var settingName = inputEl.getAttribute( 'data-setting' ); + var inputValue; + + if ( inputEl.classList.contains( 'setting-checkbox' ) ) { + inputValue = inputEl.checked; + } else { + if ( inputEl.classList.contains( 'setting-select' ) ) { + inputValue = inputEl.value; + } + } + + if ( typeof inputValue !== 'undefined' ) { + publishers.settingchange.dispatch( settingName, inputValue ); + } + } + } + + function settingUpdated ( name, value, options ) { + cancelAnimationFrame( animationFrameIds[name] ); + animationFrameIds[name] = requestAnimationFrame( function () { + addSetting( name, value, options ); + + var inputEl = dialog.el.querySelector( '.setting-checkbox[data-setting="' + name + '"]' ); + + if ( inputEl ) { + if ( inputEl.classList.contains( 'setting-checkbox' ) && inputEl.checked !== value ) { + inputEl.checked = value; + } + + if ( inputEl.classList.contains( 'setting-select' ) && inputEl.value !== value ) { + var optionsEls = inputEl.querySelector( 'option' ); + var optionEl; + var optionValue; + + for ( var i = 0, len = optionsEls.length; i < len; i++ ) { + optionEl = optionsEls[i]; + optionValue = optionEl.value; + + if ( optionValue === value && ! optionEl.selected ) { + optionEl.selected = true; + } + + if ( optionValue !== value && optionEl.selected ) { + optionEl.selected = false; + } + } + } + } + } ); + } + + self.settingUpdated = settingUpdated; + } + + return SettingsView; + } +); \ No newline at end of file diff --git a/scripts/views/shareview.js b/scripts/views/shareview.js new file mode 100644 index 0000000..6c4d050 --- /dev/null +++ b/scripts/views/shareview.js @@ -0,0 +1,337 @@ +/*global define*/ +define( + [ 'util/addpublishers', 'views/dialog', 'util/el', 'util/browser', 'util/time', 'util/localizetext' ], + function ( addPublishers, Dialog, elHelper, browser, timeHelper, loc ) { + // shareview lets users upload their glitched image to imgur and + // share links on social media + function ShareView ( parentEl ) { + if ( ! ( this instanceof ShareView ) ) { + return new ShareView( parentEl ); + } + + var self = this; + var publishers = addPublishers( self, 'share', 'deletefromimgur' ); + var clearTimeoutId = NaN; + var dialog; + var canUpload = true; + + // storing some of the UI strings that we'll need a multiple times + // later on. + var isOnlineCssClass = 'is-online-only'; + var wasLoadedCssClass = 'was-loaded'; + var isLoadingCssClass = 'is-loading'; + var isEmptyCssClass = 'is-empty'; + var blankTargetStr = '_blank'; + var disabledAttr = 'disabled'; + + var navButtonEl = elHelper.createButton( 'share.share', 'share.sharetitle', 'nav-button share-toggle-button ' + isOnlineCssClass, parentEl ); + + var statusEl = elHelper.createEl( 'span', 'upload-status' ); + loc( statusEl, 'textContent', 'share.uploading' ); + + var uploadInfoEl = elHelper.createEl( 'p', 'share-info' ); + loc( uploadInfoEl, 'innerHTML', 'share.info' ); + + var uploadButtonEl = elHelper.createButton( 'share.upload', 'share.uploadtitle', 'upload-button button ' + isOnlineCssClass, null, uploadClicked ); + + var imgLinkLabel = elHelper.createLabel( 'share.imagelink', 'img-link-input', 'img-link-label label' ); + var imgLinkEl = elHelper.createLink( null, 'share.opennewtabtitle', null, blankTargetStr, 'img-link' ); + imgLinkEl.id = 'img-link-input'; + + var imgurLinkEl = elHelper.createLink( null, null, null, blankTargetStr, 'imgur-link button' ); + loc( imgurLinkEl, 'textContent', 'share.openon', 'Imgur' ); + loc( imgurLinkEl, 'title', 'share.openontitle', 'Imgur' ); + + var redditShareLinkEl = elHelper.createLink( null, null, null, blankTargetStr, 'reddit-link button' ); + loc( redditShareLinkEl, 'textContent', 'share.shareon', 'Reddit' ); + loc( redditShareLinkEl, 'title', 'share.shareontitle', 'Reddit' ); + + var twitterShareLinkEl = elHelper.createLink( null, null, null, blankTargetStr, 'twitter-link button' ); + loc( twitterShareLinkEl, 'textContent', 'share.shareon', 'Twitter' ); + loc( twitterShareLinkEl, 'title', 'share.shareontitle', 'Twitter' ); + + var facebookShareLinkEl = elHelper.createLink( null, null, null, blankTargetStr, 'facebook-link button' ); + loc( facebookShareLinkEl, 'textContent', 'share.shareon', 'Facebook' ); + loc( facebookShareLinkEl, 'title', 'share.shareontitle', 'Facebook' ); + + var pinterestShareLinkEl = elHelper.createLink( null, null, null, blankTargetStr, 'pinterest-link button' ); + loc( pinterestShareLinkEl, 'textContent', 'share.shareon', 'Pinterest' ); + loc( pinterestShareLinkEl, 'title', 'share.shareontitle', 'Pinterest' ); + + var sharedListEl; + + dialog = Dialog( 'share-dialog', parentEl, navButtonEl ) + .add( isOnlineCssClass, uploadInfoEl ) + .add( isOnlineCssClass, uploadButtonEl ) + .add( isOnlineCssClass, 'loader', statusEl ) + .add( isOnlineCssClass, imgLinkLabel, imgLinkEl ) + .add( isOnlineCssClass, imgurLinkEl ) + .add( isOnlineCssClass, redditShareLinkEl ) + .add( isOnlineCssClass, twitterShareLinkEl ) + .add( isOnlineCssClass, facebookShareLinkEl ) + .add( isOnlineCssClass, pinterestShareLinkEl ); + + if ( browser.test( 'localforage' ) ) { + sharedListEl = elHelper.createEl( 'ul', 'shared-list dialog-list' ); + + var storageLabelEl = elHelper.createLabel( 'share.recentlyshared', null, 'load-label label' ); + + dialog.add( 'has-list shared-list', storageLabelEl, sharedListEl ); + } + + function uploadClicked () { + if ( canUpload ) { + publishers.share.dispatch(); + hideShareLinks(); + } + } + + function updateShareUrl ( imgUrl, imgId ) { + clearTimeout( clearTimeoutId ); + + dialog.el.classList.add( 'has-links' ); + imgLinkEl.textContent = imgUrl; + imgLinkEl.href = imgUrl; + imgLinkEl.setAttribute( 'data-imgurid', imgId ); + imgurLinkEl.href = 'https://imgur.com/' + imgId; + + redditShareLinkEl.href = getRedditShareUrl( imgUrl ); + twitterShareLinkEl.href = getTwitterShareUrl( imgUrl ); + facebookShareLinkEl.href = getFacebookShareUrl( imgUrl ); + pinterestShareLinkEl.href = getPinterestShareUrl( imgUrl ); + } + + function clearShareUrl () { + dialog.el.classList.remove( 'has-links' ); + imgLinkEl.textContent = ''; + imgLinkEl.href = 'about:blank'; + redditShareLinkEl.href = 'about:blank'; + twitterShareLinkEl.href = 'about:blank'; + facebookShareLinkEl.href = 'about:blank'; + } + + function showUpload () { + dialog.el.classList.add( isLoadingCssClass ); + } + + function hideUpload () { + dialog.el.classList.remove( isLoadingCssClass ); + } + + function uploadComplete ( imgUrl, imgId, imgDeleteHash ) { + updateShareUrl( imgUrl, imgId ); + showShareLinks(); + } + + function hideShareLinks ( uid ) { + dialog.el.classList.remove( wasLoadedCssClass ); + + clearTimeout( clearTimeoutId ); + clearTimeoutId = setTimeout( clearShareUrl, 400 ); + + return self; + } + + function showShareLinks () { + dialog.el.classList.add( wasLoadedCssClass ); + + return self; + } + + function showOnlineOptions () { + canUpload = true; + uploadButtonEl.removeAttribute( disabledAttr ); + + return self; + } + + function hideOnlineOptions () { + canUpload = false; + uploadButtonEl.setAttribute( disabledAttr, disabledAttr ); + + return self; + } + + function updateList ( entries ) { + if ( sharedListEl ) { + if ( entries && Object.keys( entries ).length ) { + var sharedListItemEl; + + for ( var uid in entries ) { + sharedListItemEl = sharedListEl.querySelector( '[data-uid="' + uid + '"]' ); + + if ( entries[uid].deleteHash && ! sharedListItemEl ) { + addListItem( uid, entries[uid] ); + } else { + if ( ! entries[uid].deleteHash && sharedListItemEl ) { + removeListItem( sharedListItemEl ); + } + } + } + + var sharedListItemEls = sharedListEl.querySelectorAll( '[data-uid]' ); + + for ( var i = 0, len = sharedListItemEls.length; i < len; i++ ) { + var itemUid = sharedListItemEls[i].getAttribute( 'data-uid' ); + + if ( itemUid && ! entries[itemUid] ) { + removeListItem( sharedListItemEls[i] ); + } + } + } + + if ( hasSharedEntries( entries ) ) { + sharedListEl.wrapperEl.classList.remove( isEmptyCssClass ); + } else { + sharedListEl.wrapperEl.classList.add( isEmptyCssClass ); + } + } + + return self; + } + + function addListItem ( uid, entry ) { + if ( entry ) { + var date = timeHelper.timestampToDate( entry.timestamp ); + + var listItemEl = elHelper.createEl( 'li', 'entry clear dialog-list-item', sharedListEl ); + listItemEl.setAttribute( 'data-uid', uid ); + + var listItemThumbnailEl = elHelper.createEl( 'img', 'entry-thumb', listItemEl ); + listItemThumbnailEl.src = entry.thumbnail; + listItemThumbnailEl.addEventListener( 'click', loadItemFn( uid ) ); + + var textWrapperEl = elHelper.createEl( 'p', 'entry-text', listItemEl ); + + var listItemNameEl = elHelper.createEl( 'p', 'entry-name', textWrapperEl ); + + if ( entry.name ) { + listItemNameEl.textContent = entry.name;; + } else { + loc( listItemNameEl, 'textContent', 'file.untitled' ); + } + + var listItemDateEl = elHelper.createEl( 'time', 'entry-datetime', textWrapperEl ); + listItemDateEl.setAttribute( 'datetime', date.toISOString() ); + + var dateEl = elHelper.createEl( 'span', 'entry-date', listItemDateEl ); + dateEl.textContent = timeHelper.dateToLocalStr( date ); + + var timeEl = elHelper.createEl( 'span', 'entry-time', listItemDateEl ); + timeEl.textContent = timeHelper.timeToLocalStr( date ); + + var buttonWrapperEl = elHelper.createEl( 'div', 'entry-button-wrapper', listItemEl ); + + elHelper.createLink( + 'file.openlink', + 'file.openlinktitle', + entry.publicUrl, + blankTargetStr, + 'open-link-button button ' + isOnlineCssClass, + buttonWrapperEl + ); + + elHelper.createButton( + 'file.offline', + 'file.offlinetitle', + 'item-offline-button button ' + isOnlineCssClass, + buttonWrapperEl, + removeItemFromImgurFn( uid, entry.deleteHash ) + ); + } + } + + function removeListItem ( itemEl ) { + itemEl.parentNode.removeChild( itemEl ); + } + + function removeItemFromImgurFn ( uid, deleteHash ) { + return function () { + var buttonEl = sharedListEl.querySelector( '[data-uid="' + uid + '"] .item-offline-button' ); + + if ( buttonEl ) { + buttonEl.setAttribute( disabledAttr, disabledAttr ); + } + + publishers.deletefromimgur.dispatch( uid, deleteHash ); + } + } + + function loadItemFn ( uid ) { + return function () { + dialog.hide(); + publishers.openfromlocalstorage.dispatch( uid ); + } + } + + function hasSharedEntries ( entries ) { + var result = false; + + for ( var uid in entries ) { + if ( entries[uid].deleteHash ) { + result = true; + break; + } + } + return result; + } + + function handleError ( message, data ) { + if ( data.type === 'imgurremovefail' && data.uid ) { + var buttonEl = sharedListEl.querySelector( '[data-uid="' + data.uid + '"] .item-offline-button' ); + + if ( buttonEl ) { + buttonEl.removeAttribute( disabledAttr ); + } + } + } + + function getShareDescription ( imgUrl ) { + return 'Check out what I made with @snorpey’s glitch tool: ' + imgUrl + ' https://snorpey.github.io/jpg-glitch'; + } + + function getTwitterShareUrl ( imgUrl ) { + return 'https://twitter.com/intent/tweet?text=' + encodeURIComponent( getShareDescription( imgUrl ) ); + } + + function getRedditShareUrl ( imgUrl ) { + return 'https://www.reddit.com/submit?url=' + encodeURIComponent( imgUrl ) + '&title=Glitch!'; + } + + // http://ar.zu.my/how-to-really-customize-the-deprecated-facebook-sharer-dot-php/ + function getFacebookShareUrl ( imgUrl ) { + var text = 'Check out what I made with this glitch tool: https://snorpey.github.io/jpg-glitch'; + var shareUrl = 'https://www.facebook.com/sharer/sharer.php?s=100'; + shareUrl += '&p[url]=' + imgUrl; + shareUrl += '&p[title]=Glitch!'; + shareUrl += '&p[images][0]=' + imgUrl; + shareUrl += '&p[summary]=' + encodeURIComponent( text ); + + return shareUrl; + } + + function getPinterestShareUrl ( imgUrl ) { + var text = 'I made this with snorpey\'s glitch tool: https://snorpey.github.io/jpg-glitch'; + var link = 'https://snorpey.github.io/jpg-glitch'; + var shareUrl = 'https://pinterest.com/pin/create/button/'; + shareUrl += '?url=' + encodeURIComponent( link ); + shareUrl += '&media=' + encodeURIComponent( imgUrl ); + shareUrl += '&description=' + encodeURIComponent( text ); + + return shareUrl; + } + + self.showUpload = showUpload; + self.hideUpload = hideUpload; + self.showShareLinks = showShareLinks; + self.hideShareLinks = hideShareLinks; + self.uploadComplete = uploadComplete; + self.updateList = updateList; + self.showOnlineOptions = showOnlineOptions; + self.hideOnlineOptions = hideOnlineOptions; + self.handleError = handleError; + } + + return ShareView; + } +); \ No newline at end of file diff --git a/scripts/views/webcamview.js b/scripts/views/webcamview.js new file mode 100644 index 0000000..1965518 --- /dev/null +++ b/scripts/views/webcamview.js @@ -0,0 +1,133 @@ +/*global define*/ +define( + [ 'util/browser', 'util/addpublishers', 'util/el', 'util/dom', 'views/dialog', 'util/mediastream' ], + function ( browser, addPublishers, elHelper, domHelper, Dialog ) { + // Webcamview: allows to take a picture with the web cam (if supported by the browser) + function WebcamView ( parentEl ) { + if ( ! ( this instanceof WebcamView ) ) { + return new WebcamView( parentEl ); + } + + var self = this; + var isRecording = false; + var photoUIEl; + var videoEl; + var getUserMedia; + var stream; + + var camOptions = { + video: true + }; + + var urlLib; + var publishers = addPublishers( self, 'video', 'error' ); + var dialog; + + if ( browser.test( 'getusermedia' ) ) { + var toggleButtonEl = elHelper.createButton( 'webcam.webcam', 'webcam.webcamtitle', 'nav-button photo-button', parentEl ); + var labelEl = elHelper.createLabel( 'webcam.webcamlabel', null, 'webcam-label label' ); + var videoWrapperEl = elHelper.createEl( 'div', 'video-wrapper' ); + + var videoEl = document.createElement( 'video' ); + videoEl.classList.add( 'cam-video' ); + videoEl.controls = false; + domHelper.setTransform( videoEl, 'scale(-1, 1)' ); + videoEl.addEventListener( 'click', captureClicked ); + videoWrapperEl.appendChild( videoEl ); + + var triggerButtonEl = elHelper.createButton( 'webcam.trigger', 'webcam.triggertitle', 'cam-trigger-button button', null, captureClicked ); + + dialog = Dialog( 'webcam-dialog', parentEl, toggleButtonEl ) + .add( labelEl, videoWrapperEl, triggerButtonEl ) + .on( 'show', startVideo ) + .on( 'hide', closeVideo ); + } + + function startVideo ( event ) { + if ( ! isRecording ) { + navigator.getUserMedia( camOptions, gotCamStream, userMediaFailed ); + } + } + + function captureClicked ( event ) { + videoWrapperEl.classList.add( 'is-taking-picture' ); + + setTimeout( function () { + publishers.video.dispatch( videoEl ); + videoWrapperEl.classList.remove( 'is-taking-picture' ); + }, 50 ); + } + + function gotCamStream ( videoStream ) { + var itWorked = true; + + if ( videoEl.mozSrcObject !== undefined ) { + videoEl.mozSrcObject = videoStream; + } else { + if ( window.URL ) { + videoEl.src = window.URL.createObjectURL( videoStream ); + } else { + itWorked = false; + } + } + + if ( itWorked ) { + dialog.show(); + videoEl.play(); + updateVideoSize(); + + isRecording = true; + stream = videoStream; + } else { + dialog.hide(); + publishers.error.dispatch( 'webcam.error.access' ); + } + } + + function userMediaFailed () { + if ( stream ) { + stopStream(); + publishers.error.dispatch( 'webcam.error.access' ); + } + } + + function closeVideo () { + dialog.hide(); + stopStream(); + } + + function stopStream () { + if ( stream ) { + videoEl.pause(); + + if ( videoEl.mozSrcObject ) { + videoEl.mozSrcObject = null; + } + + if ( videoEl.src ) { + videoEl.src = null; + videoEl.src = ''; + } + + if ( stream.stop ) { + stream.stop(); + } + + stream = null; + isRecording = false; + } + } + + function updateVideoSize () { + if ( videoEl.videoHeight > 0 ) { + videoEl.width = videoEl.videoWidth; + videoEl.height = videoEl.videoHeight; + } else { + setTimeout( updateVideoSize, 100 ); + } + } + } + + return WebcamView; + } +); \ No newline at end of file diff --git a/scripts/views/welcomeview.js b/scripts/views/welcomeview.js new file mode 100644 index 0000000..78d704f --- /dev/null +++ b/scripts/views/welcomeview.js @@ -0,0 +1,36 @@ +/*global define*/ +define( + [ 'util/addpublishers' ], + function ( addPublishers ) { + // all the welcomeView does is + // show some welcome messages if the + // user is visiting the first time + function WelcomeView () { + if ( ! ( this instanceof WelcomeView ) ) { + return new WelcomeView(); + } + + var self = this; + + var publishers = addPublishers( self, 'message' ); + + function show () { + var messages = [ + 'welcome.firstvisit.0', + 'welcome.firstvisit.1', + 'welcome.firstvisit.2' + ]; + + messages.forEach( function ( message, index ) { + setTimeout( function () { + publishers.message.dispatch( message, 18000 ); + }, index * 3000 ); + } ); + } + + self.show = show; + } + + return WelcomeView; + } +); \ No newline at end of file diff --git a/scripts/views/workspacenavview.js b/scripts/views/workspacenavview.js new file mode 100644 index 0000000..f795dc1 --- /dev/null +++ b/scripts/views/workspacenavview.js @@ -0,0 +1,19 @@ +/*global define*/ +define( + [ 'util/el' ], + function ( elHelper ) { + // a container for the workespace nav items + function WorkspaceNavView ( parentEl ) { + if ( ! ( this instanceof WorkspaceNavView ) ) { + return new WorkspaceNavView( parentEl ); + } + + var self = this; + var el = elHelper.createEl( 'nav', 'workspace-nav', parentEl ); + + self.el = el; + } + + return WorkspaceNavView; + } +); \ No newline at end of file diff --git a/scripts/views/workspaceview.js b/scripts/views/workspaceview.js new file mode 100644 index 0000000..f235fc3 --- /dev/null +++ b/scripts/views/workspaceview.js @@ -0,0 +1,26 @@ +/*global define*/ +define( + [ 'util/addpublishers' ], + function ( addPublishers ) { + // the workspaceView is just a wrapper for the + // panZoom and the workspaceNav elements + function WorkspaceView ( parentEl ) { + if ( ! ( this instanceof WorkspaceView ) ) { + return new WorkspaceView( parentEl ); + } + + var self = this; + var publishers = addPublishers( self, 'click' ); + + var el = document.createElement( 'div' ); + el.classList.add( 'workspace' ); + parentEl.appendChild( el ); + + el.addEventListener( 'click', publishers.click.dispatch, true ); + + self.el = el; + } + + return WorkspaceView; + } +) \ No newline at end of file diff --git a/scripts/workers/glitchworker.js b/scripts/workers/glitchworker.js new file mode 100644 index 0000000..5a1be74 --- /dev/null +++ b/scripts/workers/glitchworker.js @@ -0,0 +1,139 @@ +self.addEventListener( 'message', receivedMessageEvent, false ); + +function receivedMessageEvent ( event ) { + if ( + event && + event.data && + event.data.glitch && + event.data.glitch.base64 && + event.data.glitch.parameters + ) { + self.postMessage( { glitched: getGlitchedImageData( event.data.glitch.base64, event.data.glitch.parameters ) } ); + } else { + self.postMessage( event.data ); + } +} + +var base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +var base64Map = base64Chars.split( '' ); +var reversedBase64Map = { }; +var base64ImageData; +var byteArrayImageData; +var jpgHeaderLength = 0; +var params; + +var i = 0; +var len = 0; + +base64Map.forEach( function ( val, key ) { + reversedBase64Map[val] = key; +} ); + +function getGlitchedImageData ( base64ImageData, parameters ) { + params = parameters; + byteArrayImageData = base64ToByteArray( base64ImageData ); + jpgHeaderLength = getJpegHeaderSize( byteArrayImageData ); + + for ( i = 0, len = params.iterations; i < len; i++ ) { + glitchJpegBytes( byteArrayImageData, jpgHeaderLength, params.seed, params.amount, i, params.iterations ); + } + + return byteArrayToBase64( byteArrayImageData ); +} + +function glitchJpegBytes ( byteArray, jpgHeaderLength, seed, amount, i, len ) { + var maxIndex = byteArray.length - jpgHeaderLength - 4; + var pxMin = parseInt( maxIndex / len * i, 10 ); + var pxMax = parseInt( maxIndex / len * ( i + 1 ), 10 ); + var delta = pxMax - pxMin; + var pxIndex = parseInt( pxMin + delta * seed, 10 ); + + if ( pxIndex > maxIndex ) { + pxIndex = maxIndex; + } + + var index = Math.floor( jpgHeaderLength + pxIndex ); + + byteArray[index] = Math.floor( amount * 256 ); +} + +function base64ToByteArray ( str ) { + var result = [ ]; + var digitNum; + var cur; + var prev; + for ( i = 23, len = str.length; i < len; i++ ) { + cur = reversedBase64Map[str.charAt( i )]; + digitNum = ( i - 23 ) % 4; + + switch ( digitNum ) { + case 1: + result.push( prev << 2 | cur >> 4 ); + break; + + case 2: + result.push( ( prev & 15 ) << 4 | cur >> 2 ); + break; + + case 3: + result.push( ( prev & 3 ) << 6 | cur ); + break; + } + + prev = cur; + } + + return result; +} + +function byteArrayToBase64 ( arr ) { + var result = [ 'data:image/jpeg;base64,' ]; + var byteNum; + var cur; + var prev; + + for ( i = 0, len = arr.length; i < len; i++ ) { + cur = arr[i]; + byteNum = i % 3; + + switch (byteNum) { + case 0: + result.push( base64Map[cur >> 2] ); + break; + + case 1: + result.push( base64Map[( prev & 3 ) << 4 | cur >> 4] ); + break; + + case 2: + result.push( base64Map[( prev & 15 ) << 2 | cur >> 6] ); + result.push( base64Map[cur & 63] ); + break; + } + + prev = cur; + } + + if ( byteNum === 0 ) { + result.push( base64Map[( prev & 3 ) << 4] ); + result.push( '==' ); + } else if ( byteNum === 1 ) { + result.push( base64Map[( prev & 15 ) << 2] ); + result.push( '=' ); + } + + return result.join( '' ); +} + +function getJpegHeaderSize ( data ) { + var result = 417; + + for ( i = 0, len = data.length; i < len; i++ ) { + if ( data[i] === 255 && data[i + 1] === 218 ) { + result = i + 2; + break; + } + } + + return result; +} \ No newline at end of file diff --git a/scripts/workers/settingsworker.js b/scripts/workers/settingsworker.js new file mode 100644 index 0000000..96648c5 --- /dev/null +++ b/scripts/workers/settingsworker.js @@ -0,0 +1,90 @@ +importScripts( '../lib/localforage.nopromises.js' ); + +var settings; +var defaultSettings; +var storageKey = 'settings'; + +self.addEventListener( 'message', receivedMessageEvent, false ); + +function receivedMessageEvent ( event ) { + if ( event && event.data ) { + if ( event.data.load ) { + load(); + } + + if ( event.data.save ) { + save( event.data.save ); + } + + if ( event.data.setStorageKey ) { + setStorageKey( event.data.setStorageKey ); + } + + if ( event.data.setDefaultSettings ) { + setDefaultSettings( event.data.setDefaultSettings ); + } + } +} + +function sendMessage ( type, data ) { + if ( typeof type === 'string' ) { + if ( typeof data === 'undefined' ) { + data = type; + } + + var message = { }; + message[type] = data; + self.postMessage( message ); + } +} + +function sendError ( err ) { + sendMessage( 'error', err ); +} + +function setStorageKey ( newKey ) { + if ( newKey ) { + storageKey = newKey; + } +} + +function setDefaultSettings ( newDefaultSettings ) { + if ( newDefaultSettings ) { + defaultSettings = newDefaultSettings; + } +} + +function load () { + localforage.getItem( storageKey, function ( err, loadedSettings ) { + if ( err ) { + sendError( 'settings.error.load' ); + console && console.log( 'localforage error', err ); + } else { + if ( ! loadedSettings && defaultSettings ) { + settings = defaultSettings; + save( defaultSettings ); + } else { + settings = loadedSettings; + sendMessage( 'update', settings ); + } + } + } ); +} + +function save ( newSettings ) { + if ( newSettings ) { + localforage.setItem( storageKey, newSettings, function ( err, savedSettings ) { + if ( err ) { + sendError( 'settings.error.save' ); + console && console.log( 'localforage error', err ); + } else { + if ( savedSettings ) { + settings = savedSettings || defaultSettings; + sendMessage( 'update', settings ); + } else { + console && console.log( 'no data was saved', savedSettings ); + } + } + } ); + } +} diff --git a/scripts/workers/storageworker.js b/scripts/workers/storageworker.js new file mode 100644 index 0000000..026c18b --- /dev/null +++ b/scripts/workers/storageworker.js @@ -0,0 +1,233 @@ +importScripts( '../lib/localforage.nopromises.js' ); +importScripts( '../lib/md5.js' ); + +var storageKey = 'items'; +var entries = { }; + +self.addEventListener( 'message', receivedMessageEvent, false ); + +function receivedMessageEvent ( event ) { + if ( event && event.data ) { + if ( event.data.setStorageKey ) { + setStorageKey( event.data.setStorageKey ); + } + + if ( event.data.add ) { + add( event.data.add ); + } + + if ( event.data.removeCompletely ) { + removeCompletely( event.data.removeCompletely ); + } + + if ( event.data.removeLocalData ) { + removeLocalData( event.data.removeLocalData ); + } + + if ( event.data.removeImgurData ) { + removeImgurData( event.data.removeImgurData ); + } + + if ( event.data.load ) { + load(); + } + + if ( event.data.save ) { + save(); + } + + if ( event.data.loadItem ) { + loadItem( event.data.loadItem ); + } + } +} + +function sendMessage ( type, data ) { + if ( typeof type === 'string' ) { + if ( typeof data === 'undefined' ) { + data = type; + } + + var message = { }; + message[type] = data; + self.postMessage( message ); + } +} + +function sendError ( err ) { + sendMessage( 'error', err ); +} + +function setStorageKey ( newKey ) { + if ( newKey ) { + storageKey = newKey; + } +} + +function add ( item ) { + if ( item ) { + var uid = createUID( item ); + + if ( + entries[uid] && + entries[uid].deleteHash === item.deleteHash && + entries[uid].publicUrl === item.publicUrl && + entries[uid].imgurID === item.imgurID + ) { + sendError( 'file.message.before' ); + } else { + item.timestamp = Date.now(); + entries[uid] = item; + + save( function () { + sendMessage( 'statusmessage', 'file.message.save' ); + } ); + } + } +} + +function removeCompletely ( uid ) { + if ( uid && entries[uid] ) { + if ( + ( + entries[uid].deleteHash || + entries[uid].publicUrl || + entries[uid].imgurID || + entries[uid].values || + entries[uid].src + ) + ) { + console && console.log( 'cant delete storage item because theres still some data left', entries[uid] ); + } else { + sendMessage( 'removeall', entries[uid] ); + delete entries[uid]; + + save( function () { + sendMessage( 'statusmessage', 'file.message.save' ); + } ); + } + } +} + +function removeLocalData ( uid ) { + if ( uid && entries[uid] ) { + if ( entries[uid].src ) { + delete entries[uid].src; + + sendMessage( 'removelocaldata', entries[uid] ); + } + + if ( entries[uid].values ) { + delete entries[uid].values; + } + + if ( ! ( entries[uid].deleteHash || entries[uid].publicUrl || entries[uid].imgurID ) ) { + removeCompletely( uid ); + } + + save(); + } +} + +function removeImgurData ( uid ) { + if ( uid && entries[uid] ) { + if ( entries[uid].deleteHash ) { + sendMessage( 'removeimgurdata', entries[uid] ); + delete entries[uid].deleteHash; + } + + if ( entries[uid].publicUrl ) { + delete entries[uid].publicUrl; + } + + if ( entries[uid].imgurID ) { + delete entries[uid].imgurID; + } + + if ( ! ( entries[uid].src || entries[uid].values ) ) { + removeCompletely( uid ); + } + + save(); + } +} + +function load ( callback ) { + localforage.getItem( storageKey, function ( err, loadedData ) { + if ( err ) { + sendError( 'file.error.load' ); + console && console.log( 'localforage error', err ); + } else { + entries = loadedData && loadedData.entries ? loadedData.entries : { }; + sendMessage( 'update', entries ); + + isFirstVisit = ( loadedData && loadedData.lastVisit ) ? false : true; + + if ( isFirstVisit ) { + sendMessage( 'firstvisit' ); + save(); + } + + if ( typeof callback === 'function' ) { + callback(); + } + } + } ); +} + +function save ( callback ) { + localforage.setItem( storageKey, { entries: entries, lastVisit: Date.now() }, function ( err, savedData ) { + if ( err ) { + sendError( 'file.error.save' ); + console && console.log( 'localforage error', err ); + } else { + if ( savedData ) { + entries = savedData.entries; + sendMessage( 'update', entries ); + sendMessage( 'save' ); + + if ( typeof callback === 'function' ) { + callback(); + } + } else { + console && console.log( 'no data was saved', savedData ); + } + } + } ); +} + +function loadItem ( uid ) { + if ( entries[uid] ) { + sendMessage( 'loaditem', { uid: uid, entries: entries[uid] } ); + } +} + +function createUID ( item ) { + var inputStr = 'N' + item.name + 'S' + item.src + 'L' + item.thumbnail.length || 0 + 'V'; + + for ( var key in item.values ) { + inputStr += key.substr( 0, 2 ); + inputStr += item.values[key]; + } + + return md5( inputStr ); +} + +function getLatestUID () { + var latestUid; + var latestTimestamp; + var timestamp; + + for ( var uid in entries ) { + timestamp = entries[uid].timestamp; + + if ( timestamp ) { + if ( ! latestUid || timestamp > latestTimestamp ) { + latestUid = uid; + latestTimestamp = timestamp; + } + } + } + + return latestUid; +} \ No newline at end of file diff --git a/serviceworker.js b/serviceworker.js new file mode 100644 index 0000000..7af4548 --- /dev/null +++ b/serviceworker.js @@ -0,0 +1,141 @@ +// most of this was taken from @adactio's serviceworker +// https://adactio.com/journal/9775 +// https://adactio.com/serviceworker.js + +var version = 'v1.0::'; +var staticCacheName = version + 'static'; +var pagesCacheName = version + 'pages'; +var imagesCacheName = version + 'images'; + +function updateStaticCache () { + return caches + .open( staticCacheName ) + .then( function ( cache ) { + // These items won't block the installation of the Service Worker + cache + .addAll( [ + 'images/icon/alert-circle.svg', + 'images/icon/camera.svg', + 'images/icon/content-save.svg', + 'images/icon/delete.svg', + 'images/icon/emoticon.svg', + 'images/icon/fullscreen-exit.svg', + 'images/icon/fullscreen.svg', + 'images/icon/information-outline.svg', + 'images/icon/open-in-app.svg', + 'images/icon/share-variant.svg', + 'images/icon/settings.svg', + 'lang/en-us.json' + ] ); + // These items must be cached for the Service Worker to complete installation + return cache + .addAll( [ + 'scripts/glitcher.js', + 'scripts/workers/glitchworker.js', + 'scripts/workers/storageworker.js', + 'scripts/workers/settingsworker.js', + 'styles/glitcher.css' + ] ); + } ); +} + +function putInCache ( cacheName, request, response ) { + caches + .open( cacheName ) + .then( function ( cache ) { + cache + .keys() + .then( function ( keys ) { + cache.put( request, response ); + } ) + } ); +} + +function clearOldCaches () { + return caches + .keys() + .then( function ( keys ) { + // Remove caches whose name is no longer valid + return Promise + .all( + keys + .filter( filterInvalidKeys ) + .map( function ( key ) { return caches.delete( key ); } ) + ); + } ); +} + +function filterInvalidKeys ( key ) { + return key.indexOf( version ) !== 0; +} + +function installed ( event ) { + event + .waitUntil( updateStaticCache().then( function () { + return self.skipWaiting(); + } ) ); +} + +function activated ( event ) { + event + .waitUntil( clearOldCaches().then( function () { + return self.clients.claim(); + } ) ); +} + +function fetched ( event ) { + var request = event.request; + // For non-GET requests, try the network, do not fall back to cache. + if ( request.method !== 'GET' ) { + event.respondWith( fetch( request ) ); + return; + } + + // For HTML requests, try the network first, fall back to the cache + if ( request.headers.get( 'Accept' ).indexOf( 'text/html' ) !== -1 ) { + event.respondWith( + fetch( request ) + .then( function ( response ) { + // NETWORK + // Stash a copy of this page in the pages cache + putInCache( pagesCacheName, request, response.clone() ); + return response; + } ) + .catch( function () { + // CACHE + return caches + .match( request ) + .then( function ( response ) { + return response; + } ); + } ) + ); + + return; + } + + // For non-HTML requests, look in the cache first, fall back to the network + event.respondWith( + caches + .match( request ) + .then( function ( response ) { + // CACHE + return response || fetch( request ) + .then( function ( response ) { + // NETWORK + // If the request is for an image, stash a copy of this image in the images cache + if ( request.headers.get( 'Accept' ).indexOf( 'image' ) !== -1 ) { + putInCache( imagesCacheName, request, response.clone() ); + } + + return response; + } ); + } ) + ); +} + +(function () { + self.addEventListener( 'fetch', fetched ); + self.addEventListener( 'install', installed ); + self.addEventListener( 'activated', activated ); +})(); diff --git a/styles/glitcher.css b/styles/glitcher.css new file mode 100644 index 0000000..315e468 --- /dev/null +++ b/styles/glitcher.css @@ -0,0 +1,14 @@ +@import 'global/reset.css'; +@import 'global/typography.css'; +@import 'global/color.css'; +@import 'modules/app.css'; +@import 'modules/buttons.css'; +@import 'modules/panzoom.css'; +@import 'modules/description.css'; +@import 'modules/controls.css'; +@import 'modules/nav.css'; +@import 'modules/dialog.css'; +@import 'modules/indicator.css'; +@import 'modules/workspace.css'; +@import 'modules/workspace-nav.css'; +@import 'modules/about.css'; \ No newline at end of file diff --git a/styles/global.css b/styles/global.css deleted file mode 100644 index fdb3ed1..0000000 --- a/styles/global.css +++ /dev/null @@ -1,130 +0,0 @@ -* -{ - margin: 0; - padding: 0; -} - -body -{ - padding: 50px; - font-family: sans-serif; - color: #666; - line-height: 18px; - font-size: 12px; -} - -a -{ - color: #06f; - text-decoration: none; -} - -a:hover -{ - text-decoration: underline; -} - -.button -{ - background-color: #eaeaea; - padding: 5px 9px; - display: inline-block; - color: #06f; - font-weight: normal; - border-radius: 2px; - cursor: pointer; - border: none; - font-family: sans-serif; - font-size: 12px; - text-decoration: none; -} - -.button:hover -{ - background-color: #06f; - color: #fff; -} - -.headline -{ - font-size: 12px; - color: #333; - margin-bottom: 10px; -} - -.content, -.missing-feature -{ - max-width: 650px; -} - -#controls -{ - float: left; - margin-top: 30px; - display: none; -} - -#controls.is-active -{ - display: block; -} - - .control-wrapper - { - float: left; - width: 100px; - margin-right: 20px; - } - - .control-label - { - display: block; - color: #666; - } - - .control-input - { - display: block; - width: 100px; - } - -#canvas -{ - clear: both; - float: left; - margin-top: 30px; - display: block; -} - -.export-wrapper -{ - clear: both; - float: left; - margin-top: 30px; -} - - .download-link - { - display: none; - } - - .download-link.is-active - { - display: inline-block; - margin-left: 15px; - } - - .download-link span - { - color: #999; - display: inline-block; - text-decoration: none; - margin-left: 4px; - } - - -.missing-feature -{ - clear: both; -} \ No newline at end of file diff --git a/styles/global/color.css b/styles/global/color.css new file mode 100644 index 0000000..0477444 --- /dev/null +++ b/styles/global/color.css @@ -0,0 +1,19 @@ +body { + color: #333; +} + +input { + color: #ccc; +} + +a { + color: #06f; +} + +.color-bg { + background-color: hsla(0, 0%, 20%, 1); +} + +.color-bg-light { + background-color: hsla(0, 0%, 30%, 1); +} \ No newline at end of file diff --git a/styles/global/reset.css b/styles/global/reset.css new file mode 100644 index 0000000..f8f2bf1 --- /dev/null +++ b/styles/global/reset.css @@ -0,0 +1,5 @@ +.clear:after { + content: ''; + display: table; + clear: both; +} \ No newline at end of file diff --git a/styles/global/typography.css b/styles/global/typography.css new file mode 100644 index 0000000..6cc8116 --- /dev/null +++ b/styles/global/typography.css @@ -0,0 +1,23 @@ +a { + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +button { + font-family: -apple-system, Roboto, 'Lucida Grande', sans-serif; + font-size: 11px; +} + +label, +time { + font-family: -apple-system, Roboto, 'Lucida Grande', sans-serif; + font-size: 11px; +} + +input { + font-family: 'Menlo', 'Lucida Grande', sans-serif; + font-size: 11px; +} \ No newline at end of file diff --git a/styles/modules/about.css b/styles/modules/about.css new file mode 100644 index 0000000..27d7383 --- /dev/null +++ b/styles/modules/about.css @@ -0,0 +1,35 @@ +.about-content { + max-width: 300px; + max-height: calc(100vh - 270px); + overflow: auto; + padding-bottom: 15px; +} + +.about-content .text { + opacity: 1; + margin-top: 0; + margin-bottom: 0; + width: 100%; +} + +.abount-content .description { + +} + +.has-touch .about-content { + max-height: calc(100vh - 290px); +} + +/*.about-content p { + font-size: 13px; + line-height: 22px; +} + +.about-content p + p { + margin-top: 10px; +}*/ + + +.about-dialog .dialog-item { + padding-bottom: 0; +} \ No newline at end of file diff --git a/styles/modules/app.css b/styles/modules/app.css new file mode 100644 index 0000000..be349f8 --- /dev/null +++ b/styles/modules/app.css @@ -0,0 +1,18 @@ +.app { + transition: opacity 0.3s ease-out; + opacity: 0; +} + +.is-loaded .app { + opacity: 1; +} + +html:not(.is-online) .is-online-only { + display: none; +} + +@media screen and (min-width: 600px) { + .app { + display: flex; + } +} \ No newline at end of file diff --git a/styles/modules/buttons.css b/styles/modules/buttons.css new file mode 100644 index 0000000..6505540 --- /dev/null +++ b/styles/modules/buttons.css @@ -0,0 +1,87 @@ +.button { + background-color: transparent; + padding: 4px 6px; + border-radius: 3px; + border: none; + color: #fff; + font-size: 11px; + display: inline-block; + cursor: pointer; + transition: all 0.2s; + outline: none; + text-decoration: none; + font-weight: 500; + text-transform: uppercase; + border: 2px solid rgba(255, 255, 255, 0.1); + height: 30px; + line-height: 22px; +} + +.has-touch .button { + border: 2px solid rgba(255, 255, 255, 0.5); + height: 45px; + line-height: 40px; + padding-top: 0; + padding-bottom: 0; + padding-left: 20px; + padding-right: 20px; +} + +.button:focus { + color: #fff; + border-color: #fff; +} + +.button:hover, +.button:active { + color: #333; + background-color: #fff; + text-decoration: none; + border-color: #fff; +} + +.button[disabled], +.button[disabled]:hover, +.button[disabled]:active, +.button[disabled]:focus { + color: rgba(255, 255, 255, 0.5); + border-color: transparent; + background-color: transparent; + cursor: default; +} + +.button + .button { + margin-left: 10px; +} + +.save-dialog.is-active { + max-height: 40px; +} + +.webcam-dialog.is-active { + max-height: 225px; +} + +.webcam-dialog.is-active { + max-height: 225px; +} + +.open-file-dialog.is-active, +.share-dialog .is-active { + max-height: 550px; +} + +.about-dialog.is-active { + max-height: 442px; +} + +/*.dialog-list .button { + border-radius: 1px; +} + +.dialog-list .button:hover, +.dialog-list .button:active, +.dialog-list .button:focus { + color: #e91e63; + background-color: #fff; +}*/ \ No newline at end of file diff --git a/styles/modules/controls.css b/styles/modules/controls.css new file mode 100644 index 0000000..24387f3 --- /dev/null +++ b/styles/modules/controls.css @@ -0,0 +1,442 @@ +.controls { + width: 100%; + max-height: 0; + transition: 0.3s all ease-out; + overflow: hidden; +} + +.controls.is-visible { + z-index: 10; +} + +.controls.is-active { + opacity: 1; + max-height: 200px; +} + + .has-touch .controls.is-active { + max-height: 300px; + } + +.controls-wrapper { + width: 100%; + background-color: #333; + padding: 10px; + color: #ccc; + display: flex; + justify-content: space-between; + align-items: flex-start; + align-content: flex-start; + flex-wrap: wrap; +} + +.control { + display: block; + position: relative; + min-width: 160px; + margin-top: 10px; + width: 100%; +} + +.has-touch .control { + height: 45px; + margin-bottom: 10px; +} + +.controls .button { + line-height: 18px; + margin-left: 10px; +} + +.control-label { + display: block; + float: left; + width: 100%; + max-width: 60px; + height: 100%; + font-size: 11px; + margin-right: 10px; + text-overflow: ellipsis; + overflow: hidden; +} + +.has-touch .control-label { + font-size: 14px; + max-width: 80px; + line-height: 45px; + text-align: right; +} + +.control-input { + display: block; + width: 100%; + height: 100%; + min-height: 10px; + max-width: calc(100% - 105px); + background-color: transparent; + margin-top: 0; + margin-bottom: 0; + float: left; +} + +.has-touch .control-input { + max-width: calc(100% - 130px); +} + +.control-value { + display: block; + float: right; + width: 35px; + height: 100%; + background-color: transparent; + border: none; + text-align: right; + float: left; +} + +.controls .random-button { + display: none; +} + +/*two columns*/ +@media screen and (min-width: 660px) { + html:not(.has-touch) .nav ~ .workspace .control { + width: calc(50% - 5px); + } + + html:not(.has-touch) .nav ~ .workspace .control { + max-width: 320px; + } +} + +@media screen and (min-width: 800px) { + .has-touch .nav ~ .workspace .control { + width: calc(50% - 5px); + } + + html:not(.has-touch) .nav ~ .workspace .control { + max-width: 320px; + } + + .has-touch .nav ~ .workspace .controls-wrapper { + min-height: 164px; + } +} + +/*four columns*/ +@media screen and (min-width: 721px) { + html:not(.has-touch) .nav:not(.is-active) ~ .workspace .controls-wrapper { + justify-content: flex-start; + } + + html:not(.has-touch) .nav:not(.is-active) ~ .workspace .control { + min-width: 160px; + max-width: 320px; + width: calc(25% - 15px); + } + + html:not(.has-touch) .nav:not(.is-active) ~ .workspace .control + .control { + margin-left: 20px; + } +} + +@media screen and (min-width: 1021px) { + html:not(.has-touch) .nav ~ .workspace .controls-wrapper { + justify-content: flex-start; + } + + html:not(.has-touch) .nav ~ .workspace .control { + min-width: 160px; + max-width: 320px; + width: calc(25% - 15px); + } + + html:not(.has-touch) .nav ~ .workspace .control + .control { + margin-left: 20px; + } +} + +/*four columns*/ +@media screen and (min-width: 815px) { + html:not(.has-touch) .nav:not(.is-active) ~ .workspace .control { + width: calc(25% - 40px); + } + + html:not(.has-touch) .nav:not(.is-active) ~ .workspace .random-button { + display: inline-block; + } +} + +@media screen and (min-width: 1215px) { + html:not(.has-touch) .nav ~ .workspace .control { + width: calc(25% - 40px); + } + + html:not(.has-touch) .nav ~ .workspace .random-button { + display: inline-block; + } +} + +@media screen and (min-width: 1200px) { + .has-touch .nav:not(.is-active) ~ .workspace .control { + width: calc(25% - 40px); + } + + .has-touch .nav:not(.is-active) ~ .workspace .random-button { + display: inline-block; + } + + .has-touch .nav:not(.is-active) ~ .workspace .controls-wrapper { + min-height: 0; + } +} + +@media screen and (min-width: 1500px) { + .has-touch .nav ~ .workspace .control { + width: calc(25% - 40px); + } + + .has-touch .nav ~ .workspace .random-button { + display: inline-block; + } + + .has-touch .nav ~ .workspace .controls-wrapper { + min-height: 0; + } +} + +input[type=range] { + -webkit-appearance: none; + width: 100%; +} + +input[type=range]:focus { + outline: none; +} + +/*input[type=range]::-webkit-slider-runnable-track { + width: 100%; + height: 4px; + cursor: pointer; + background: rgba(0, 0, 0, 0.95); + border-radius: 3px; + border: 1px solid #333333; +} + +input[type=range]::-webkit-slider-thumb { + border: 0.1px solid rgba(102, 102, 102, 0.5); + height: 10px; + width: 10px; + border-radius: 10px; + margin-top: -4px; + background: #999999; + cursor: pointer; + -webkit-appearance: none; +}*/ + +input[type='range']:not(*:root) { + overflow: hidden; + background-color: transparent; +} + +input[type=range]::-webkit-slider-runnable-track { + height: 100%; + border: none; + background-color: transparent; + position: relative; +} + +/*track background line, full width*/ +input[type=range]::-webkit-slider-runnable-track::before { + content: ''; + display: block; + position: absolute; + width: 100%; + height: 4px; + background-color: rgba(255, 255, 255, 0.2); + left: 0; + top: 50%; + transform: translateY(-50%); + transition: background-color 0.2s; +} + +input[type=range]:focus::-webkit-slider-runnable-track::before, +input[type=range]:active::-webkit-slider-runnable-track::before { + background-color: rgba(0, 0, 0, 0.5); +} + +/*slider thumb clickable area*/ +input[type=range]::-webkit-slider-thumb { + height: 20px; + width: 20px; + border-radius: 45px; + margin-top: 0; + transition: background-color 0.2s; + background-color: transparent; + position: relative; + cursor: pointer; + -webkit-appearance: none; +} + +input[type=range]:focus::-webkit-slider-thumb, +input[type=range]:active::-webkit-slider-thumb, +.has-touch input[type=range]:focus::-webkit-slider-thumb, +.has-touch input[type=range]:active::-webkit-slider-thumb { + background-color: rgba(255, 255, 255, 0.5); +} + +.has-touch input[type=range]::-webkit-slider-thumb { + height: 38px; + width: 38px; + background-color: rgba(255, 255, 255, 0.2); +} + +/*slider thumb point*/ +input[type=range]::-webkit-slider-thumb::before { + content: ''; + display: block; + position: absolute; + background-color: #fff; + width: 10px; + height: 10px; + border-radius: 14px; + z-index: 2; + top: 50%; + left: 50%; + transform: translateX(-50%) translateY(-50%); + transition: background-color 0.2s; +} + +.has-touch input[type=range]::-webkit-slider-thumb::before { + width: 14px; + height: 14px; +} + +/*slider current value track*/ +input[type=range]::-webkit-slider-thumb::after { + content: ''; + display: block; + position: absolute; + width: 100vw; + height: 3px; + top: 50%; + right: 50%; + transform: translateY(-50%); + background-color: #fff; +} + +input[type=range]::-moz-range-track { + height: 100%; + border: none; + background-color: transparent; + position: relative; + background: linear-gradient( + to bottom, + rgba(255,255,255,0) 0%, + rgba(255,255,255,0) 41.9%, + rgba(255,255,255,0.2) 42%, + rgba(255,255,255,0.2) 58%, + rgba(255,255,255,0) 58.1%, + rgba(255,255,255,0) 100% + ); +} + +.has-touch input[type=range]::-moz-range-track { + background: linear-gradient( + to bottom, + rgba(255,255,255,0) 0%, + rgba(255,255,255,0) 49.9%, + rgba(255,255,255,0.2) 50%, + rgba(255,255,255,0.2) 55%, + rgba(255,255,255,0) 55.1%, + rgba(255,255,255,0) 100% + ); +} + +input[type=range]::-moz-range-thumb { + height: 20px; + width: 20px; + border-radius: 45px; + margin-top: 3px; + transition: background-color 0.2s; + position: relative; + cursor: pointer; + appearance: none; + border: none; + background: radial-gradient( + ellipse at center, + rgba(255,255,255,1) 0%, + rgba(255,255,255,1) 30%, + rgba(255,255,255,0) 30.1%, + rgba(255,255,255,0) 100% + ); +} + +input[type=range]::-moz-range-thumb:hover, +.has-touch input[type=range]::-moz-range-thumb { + background: radial-gradient( + ellipse at center, + rgba(255,255,255,1) 0%, + rgba(255,255,255,1) 30%, + rgba(255,255,255,0.2) 30.1%, + rgba(255,255,255,0.2) 100% + ); +} + +input[type=range]:focus::-moz-range-thumb, +input[type=range]:active::-moz-range-thumb, +.has-touch input[type=range]:focus::-moz-range-thumb, +.has-touch input[type=range]:active::-moz-range-thumb { + background: radial-gradient( + ellipse at center, + rgba(255,255,255,1) 0%, + rgba(255,255,255,1) 30%, + rgba(255,255,255,0.5) 30.1%, + rgba(255,255,255,0.5) 100% + ); +} + +.has-touch input[type=range]::-moz-range-thumb { + height: 38px; + width: 38px; +} + +input[type=range]::-ms-track { + width: 100%; + height: 3px; + cursor: pointer; + background: transparent; + border: none; + color: transparent; + overflow: visible; + background-color: rgba(255, 255, 255, 0.2); +} + +input[type=range]::-ms-fill-lower { + background: #fff; + border: none; + box-shadow: none; +} + +input[type=range]::-ms-thumb { + box-shadow: none; + border: none; + height: 10px; + width: 10px; + border-radius: 14px; + border: none; + background: #fff; + cursor: pointer; +} + +.has-touch input[type=range]::-ms-thumb { + width: 15px; + height: 15px; + border-radius: 45px; + border: 10px rgba(255, 255, 255, 0.5) solid; +} + +.has-touch input[type=range]:focus::-ms-thumb, +.has-touch input[type=range]:active::-ms-thumb { + border-color: rgba(255, 255, 255, 1); +} \ No newline at end of file diff --git a/styles/modules/description.css b/styles/modules/description.css new file mode 100644 index 0000000..b7060a6 --- /dev/null +++ b/styles/modules/description.css @@ -0,0 +1,7 @@ +.is-good-enough .description .min-requirements { + display: none; +} + +.has-js .description .js-required { + display: none; +} \ No newline at end of file diff --git a/styles/modules/dialog.css b/styles/modules/dialog.css new file mode 100644 index 0000000..579d284 --- /dev/null +++ b/styles/modules/dialog.css @@ -0,0 +1,388 @@ +.dialog { + transition: all 0.5s; + max-height: 0; + overflow: hidden; + position: relative; +} + +.dialog.is-active { + max-height: calc(100vh - 220px); +} + +.has-touch .dialog.is-active { + max-height: calc(100vh - 290px); +} + +.dialog.is-visible { + display: block; +} + +.dialog-close-button { + position: absolute; + top: 5px; + right: 5px; + border: none; + cursor: pointer; + border-radius: 34px; + width: 34px; + height: 34px; + outline: none; + background-color: transparent; +} + +.dialog-close-button:hover, +.dialog-close-button:focus, +.dialog-close-button:active { + color: #f50057; +} + +.dialog-close-button .close-text { + font-size: 20px; + position: absolute; + top: 50%; + left: 50%; + transform: translateX(-50%) translateY(-50%); + text-align: center; +} + +.dialog > h1, +.dialog-title { + font-size: 17px; + font-weight: normal; + /*color: #fff;*/ + padding: 10px 20px 0 20px; +} + +.dialog-item { + display: block; + width: 100%; + padding-top: 15px; + padding-left: 20px; + padding-bottom: 15px; + padding-right: 20px; +} + +.dialog-item + .dialog-item, +.dialog-item:first-child { + padding-top: 0; +} + +.dialog-item p { + font-size: 13px; + line-height: 22px; +} + +.dialog-item p + p { + margin-top: 10px; +} + +.dialog-item .label { + display: block; + width: 100%; + font-size: 14px; + color: rgba(255, 255, 255, 0.7); + margin-bottom: 3px; + padding: 10px 0; +} + +.dialog-item input[type="text"], +.dialog-item input[type="url"], +.dialog-item input[type="email"] { + background-color: transparent; + border: none; + border-bottom: 1px #666 solid; + margin-bottom: 5px; + max-width: calc(100% - 45px); + width: 100%; + transition: all 0.2s; +} + +.dialog-item input[type="text"]:focus, +.dialog-item input[type="url"]:focus, +.dialog-item input[type="email"]:focus { + border-bottom-color: #999; + color: #fff; +} + +.dialog-item input[type="text"]:last-child, +.dialog-item input[type="url"]:last-child, +.dialog-item input[type="email"]:last-child { + max-width: 100%; +} + +.dialog-item input[type="text"] + .button, +.dialog-item input[type="url"] + .button, +.dialog-item input[type="email"] + .button { + margin-left: 5px; + float: right; +} + +.dialog-item input[type="file"] { + width: 0; + height: 0; + overflow: hidden; + position: absolute; + top: 0; + left: 0; +} + +.dialog-item video { + max-height: 200px; + max-width: 300px; + width: 100%; + background-color: #000; + overflow: hidden; + object-fit: cover; + display: block; + cursor: pointer; + opacity: 0.8; +} + +.dialog-item video:hover { + opacity: 1; +} + +.dialog-item .video-wrapper.is-taking-picture { + background-color: #fff; +} + +.dialog-item .video-wrapper.is-taking-picture video { + opacity: 0; + transition-duration: 0; +} + +.dialog-item a:not(.button) { + color: #fff; + border-bottom: 1px #999 solid; +} + +.dialog-item a:not(.button):hover { + border-bottom: 1px #ccc solid; + text-decoration: none; +} + +.dialog-list { + overflow: scroll; + margin-left: -20px; + padding-left: 20px; + padding-right: 20px; + width: calc(100% + 40px); + max-height: calc(100vh - 355px); +} + +.has-touch .dialog-list { + max-height: calc(100vh - 445px); +} + + .dialog-list-item { + position: relative; + margin-bottom: 10px; + display: block; + } + .has-touch .dialog-list-item { + margin-bottom: 30px; + } + + .dialog-list img { + transition: all 0.2s; + cursor: pointer; + display: block; + float: left; + margin-bottom: 10px; + } + + .has-touch .dialog-list img { + float: none; + } + + .dialog-list .entry-text { + position: absolute; + left: 60px; + top: 0; + line-height: 16px; + max-width: calc(100% - 60px); + } + + .has-touch .dialog-list .entry-text { + width: 100%; + } + + .dialog-list .entry-name { + font-size: 11px; + color: #fff; + display: block; + overflow: hidden; + width: 80px; + text-overflow: ellipsis; + } + + html:not(.has-touch) .dialog-list .entry-name { + white-space: nowrap; + } + + .has-touch .dialog-list .entry-name { + width: 100%; + } + + .dialog-list .entry-datetime span { + display: block; + max-width: 90px; + overflow: hidden; + text-overflow: ellipsis; + max-height: 40px + } + + .has-touch .dialog-list .entry-datetime span { + max-width: 100%; + display: inline-block; + } + + .has-touch .dialog-list .entry-datetime span + span { + margin-left: 10px; + } + + .dialog-list .entry-button-wrapper { + position: absolute; + top: 15px; + right: 0; + text-align: right; + } + + .has-touch .dialog-list .entry-button-wrapper { + position: static; + text-align: left; + margin-top: 10px; + margin-bottom: 10px; + display: inline-block; + } + + .dialog-list .entry-shared-button-wrapper { + margin-top: 10px; + clear: both; + } + + .has-touch .dialog-list .entry-shared-button-wrapper { + display: inline; + } + + .has-touch .shared-list .entry-button-wrapper { + width: 100%; + } + + html:not(.has-touch) .dialog-list .entry-shared-button-wrapper .button { + border-color: transparent; + } + + html:not(.has-touch) .dialog-list .item-delete-button { + border-color: transparent; + } + + .dialog-list .no-items { + font-size: 12px; + margin-left: 15px; + } + +.has-touch .share-dialog.is-active { + max-height: calc(100vh - 270px); + overflow: auto; +} + +/*pulse keyframe animation is inlined in html*/ + +.dialog .loader { + font-size: 14px; + overflow: hidden; + position: relative; + transition: all 0.3s; + max-height: 0; + padding-top: 0; + padding-bottom: 0; + border-width: 0; +} + +.dialog.is-loading:not(.was-loaded) .loader { + padding-left: 50px; + padding-bottom: 10px; + padding-top: 13px; + max-height: 40px; + border-width: 1; + color: #fff; +} + +.dialog .loader ~ .dialog-item { + transition: all 0.3s; + overflow: hidden; +} + +.dialog .loader + .dialog-item { + border-top: none; +} + +.dialog:not(.was-loaded) .loader ~ .dialog-item:not(.has-list) { + max-height: 0; + padding-top: 0; + padding-bottom: 0; + border-width: 0; +} + +.save-dialog .dialog-item { + display: flex; + justify-content: space-between; +} + +.save-dialog .button { + display: block; +} + +.webcam-dialog .button { + margin-top: 10px; +} + +.shared-list { + max-height: calc(100vh - 345px); + transition: max-height 0.2s; +} + +.shared-list.is-empty { + max-height: 0; + overflow: hidden; + padding-top: 0; + padding-bottom: 0; + border-width: 0; +} + +.shared-list .entry-button-wrapper { + position: static; + width: 120px; + float: right; +} + +.shared-list .item-offline-button { + margin-top: 5px; +} + +html:not(.has-touch) .shared-list .item-offline-button { + border-color: transparent; +} + +.setting { + display: flex; +} + +.setting-label { + font-size: 14px; + display: block; + width: calc(100% - 16px); + padding-right: 30px; + cursor: pointer; + line-height: 21px; + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.setting-checkbox { + margin-top: 3px; +} diff --git a/styles/modules/indicator.css b/styles/modules/indicator.css new file mode 100644 index 0000000..8fb1f34 --- /dev/null +++ b/styles/modules/indicator.css @@ -0,0 +1,75 @@ +.notifications { + position: absolute; + top: 15px; + right: 15px; + transition: all 0.3s; + width: 240px; + opacity: 0; + transform: translateZ(0); + max-height: 50vh; + overflow: hidden; +} + +.notifications.is-active { + opacity: 1; + z-index: 5; +} + +.notification { + width: 100%; + background-color: rgba(0, 0, 0, 0.8); + opacity: 0; + transition: all 0.3s ease-out; + transform: translateY(30px); + max-height: 0; + overflow: hidden; + line-height: 24px; + padding-left: 10px; + padding-right: 10px; + padding-top: 0; + padding-bottom: 0; + font-size: 12px; + padding-left: 45px; + background-repeat: no-repeat; + background-position: 10px 10px; + background-image: url(../../images/icon/information-outline.svg); + color: #fff; +} + +.notification a { + color: #fff; + text-decoration: none; + border-bottom: 1px #ccc solid; +} + +.notification-error { + background-image: url(../../images/icon/alert-circle.svg); +} + +.notification-welcome { + background-image: url(../../images/icon/emoticon.svg); +} + +.notification.is-visible { + transform: translateY(0); +} + +.notification.is-active { + margin-bottom: 10px; + opacity: 1; + padding-top: 10px; + padding-bottom: 10px; + max-height: calc(100%); +} + +.notification.is-visible:not(.is-active) { + height: 0; +} + +.notification.is-active:nth-child(3) { + opacity: 0.5; +} + +.notification.is-active:nth-child(3) ~ .notification { + opacity: 0; +} \ No newline at end of file diff --git a/styles/modules/nav.css b/styles/modules/nav.css new file mode 100644 index 0000000..41fc533 --- /dev/null +++ b/styles/modules/nav.css @@ -0,0 +1,284 @@ +.nav { + position: absolute; + width: 15%; + height: 100%; + width: 300px; + left: 0; + top: 0; + z-index: 11; + color: rgba(255, 255, 255, 0.6); + overflow: hidden; + transform: translateX(-300px); + transition: transform 300ms ease-out; + max-width: 100%; +} + +.nav.is-swiping { + transition: none; +} + +.nav.is-active { + transform: translateX(0); +} + +.nav-button { + background-color: transparent; + display: block; + color: #fff; + border: none; + line-height: 22px; + font-size: 15px; + cursor: pointer; + transition: all 0.2s; + outline: none; + width: 100%; + text-align: left; + padding-left: 50px; + padding-right: 0px; + padding-bottom: 10px; + padding-top: 10px; + position: relative; +} + +.has-touch .nav-button { + padding-top: 0; + padding-bottom: 0; + height: 48px; + line-height: 48px; +} + +.nav-button:hover, +.nav-button.is-active, +.nav-button:focus { + color: #fff; + background-color: hsla(0,0%,30%,1); +} + +.nav-button::before { + width: 18px; + height: 18px; + content: ''; + display: block; + position: absolute; + left: 20px; + top: 12px; + background-size: contain; + background-position: center; + background-repeat: no-repeat; +} + +.has-touch .nav-button::before { + top: 16px; +} + +.has-touch .nav-button::after { + top: 15px; + transform: scale(1.5); +} + +.open-button::before { + background-image: url(../../images/icon/open-in-app.svg); +} + +.save-view-button::before { + background-image: url(../../images/icon/content-save.svg); +} + +.photo-button::before { + background-image: url(../../images/icon/camera.svg); +} + +.share-toggle-button::before { + background-image: url(../../images/icon/share-variant.svg); +} + +.info-button::before { + background-image: url(../../images/icon/information-outline.svg); +} + +.settings-button::before { + background-image: url(../../images/icon/settings.svg); +} + +.nav-button::after { + content: ''; + display: block; + width: 18px; + height: 18px; + position: absolute; + right: 20px; + top: 13px; + background-image: url(../../images/icon/chevron-down.svg); + background-size: cover; + background-position: center; + background-repeat: no-repeat; + transition: all 0.3s; +} + +.nav-button.is-active::after { + transform: rotate(-180deg); +} + +.has-touch .nav-button.is-active::after { + transform: rotate(-180deg) scale(1.5); +} + +.nav-headline { + height: 50px; + line-height: 50px; + color: #fff; + font-weight: normal; + padding-left: 20px; + font-size: 15px; + text-transform: uppercase; +} + +.nav-toggle-button { + display: block; + width: 90px; + height: 30px; + position: absolute; + top: 10px; + left: 15px; + border: none; + text-indent: -5000px; + background-color: transparent; + border: none; + cursor: pointer; + outline: 0; + z-index: 11; + transition: all 0.3s ease-out; + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.nav-toggle-button.is-active { + border-color: transparent; + width: 30px; + transform: translateX(242px); +} + +.nav-toggle-button.is-swiping { + transition: none; +} + +.nav-toggle-button-text { + position: absolute; + height: 100%; + width: 50px; + text-indent: 0; + text-align: left; + left: 40px; + top: 0; + line-height: 30px; + font-size: 14px; + color: #666; + text-transform: uppercase; + overflow: hidden; + transition: all 0.3s ease-out; +} + +.nav-toggle-button.is-active .nav-toggle-button-text { + width: 0; + opacity: 0; +} + +.nav-toggle-button.is-swiping .nav-toggle-button-text { + transition: none; +} + +.nav-toggle-button .svg-wrapper { + width: 30px; + height: 100%; + position: absolute; + top: 0; + left: 0; +} + +.nav-toggle-button #svg { + width: 100%; + height: 100%; + display: block; +} + +.nav-toggle-button rect, +.nav-toggle-button #menu { + transition: all 0.4s ease-out; +} + +.nav-toggle-button #menu { + transform-origin: 12px 12px; + transform: rotateZ(0); +} + +.nav-toggle-button rect { + transform-origin: 12px 12px; +} + +.nav-toggle-button.is-swiping rect, +.nav-toggle-button.is-swiping #menu { + transition: none; +} + +.nav-toggle-button.is-active rect { + fill: #fff; +} + +.nav-toggle-button.is-active #menu { + transform: rotateZ(-90deg); +} + +.nav-toggle-button.is-active #rect-1 { + transform: rotateZ(45deg) translateX(0) translateY(5.1px); +} + +.nav-toggle-button.is-active #rect-3 { + transform: rotateZ(-45deg) translateX(0) translateY(-5.1px); +} + +.nav-toggle-button.is-active #rect-2 { + transform: scaleX(0); +} + +@media screen and (max-width: 300px) { + .nav-toggle-button.is-active { + left: calc(100% - 41px); + } +} + +@media screen and (max-width: 600px) { + body { + overflow: hidden; + } +} + +@media screen and (max-height: 600px) { + .nav { + overflow: auto; + } + + .nav .dialog.is-active { + max-height: none !important; + overflow: visible; + } + + .nav .dialog-list:not(.is-empty), + .nav .shared-list:not(.is-empty), + .nav .about-content { + max-height: none !important; + overflow: visible; + } +} + +@media screen and (min-width: 1200px) { + .nav { + transform: translateX(0); + } + + .nav-toggle-button { + display: none; + } +} diff --git a/styles/modules/panzoom.css b/styles/modules/panzoom.css new file mode 100644 index 0000000..9dea277 --- /dev/null +++ b/styles/modules/panzoom.css @@ -0,0 +1,33 @@ +.panzoom { + width: 100%; + height: 100%; + overflow: hidden; + transition: all 0.2s; +} + +.panzoom canvas { + image-rendering: -moz-crisp-edges; + image-rendering: -webkit-crisp-edges; + image-rendering: crisp-edges; + image-rendering: pixelated; + opacity: 0; +} + +.panzoom.is-visible:not(.drag-over) canvas { + opacity: 1; + transition: opacity 0.2s; +} + +.panzoom.drag-over { + background-color: #444; +} + +.panzoom.drag-over canvas { + opacity: 0; +} + +@media screen and (max-width: 800px) { + .has-touch .controls.is-active ~ .panzoom { + height: calc(100vh - 280px) + } +} \ No newline at end of file diff --git a/styles/modules/workspace-nav.css b/styles/modules/workspace-nav.css new file mode 100644 index 0000000..78e2610 --- /dev/null +++ b/styles/modules/workspace-nav.css @@ -0,0 +1,311 @@ +.workspace-nav { + z-index: 10; + width: 100%; + position: relative; +} + +.workspace-controls { + position: absolute; + top: 0; + background-color: rgba(255, 255, 255, 0.4); + padding: 10px; + transform: translateY(-100%); + width: 100%; + display: flex; + justify-content: space-between; + flex-direction: row-reverse; +} + +.workspace-controls .scale-to-original-button { + display: inline-block; +} + +input.scale-slider { + width: calc(100% - 230px); + float: right; + position: relative; + top: 6px; + height: 20px; + display: none; + margin-right: 0; + margin-left: 0; + z-index: 14; +} + + .has-touch .workspace-controls .scale-slider { + min-height: 45px; + width: calc(100% - 260px); + top: 0; + } + +.workspace-controls .button { + margin-right: 10px; + float: left; + color: #333; + border-color: rgba(0, 0, 0, 0.1); +} + + .workspace-controls .button:hover, + .workspace-controls .button:active { + border-color: rgba(0, 0, 0, 0.9); + } + + .has-touch .workspace-controls .button, + .workspace-controls .button[disabled], + .workspace-controls .button[disabled]:hover, + .workspace-controls .button[disabled]:active, + .workspace-controls .button[disabled]:focus { + border-color: rgba(0, 0, 0, 0.5); + } + +.workspace-controls .scale-label { + color: #333; + margin-left: 20px; + display: none; + height: 30px; + line-height: 30px; +} + + .has-touch .workspace-controls .scale-label { + font-size: 14px; + line-height: 45px; + text-align: right; + height: 45px; + } + +.workspace-controls .button { + float: right; + margin-right: 10px +} + +.workspace-controls .controls-toggle-button { + float: left; +} + +.fullscreen-button { + display: block; + position: absolute; + top: 10px; + right: 10px; + width: 20px; + overflow: hidden; + text-indent: -5000px; + width: 30px; + height: 30px; + background-image: url(../../images/icon/fullscreen.svg); + background-color: transparent; + background-size: cover; + background-position: center; + border: none; + cursor: pointer; + transition: all 0.3s ease-out; + opacity: 1; +} + +html:not(.has-touch) .fullscreen-button { + opacity: 0.7; +} + +html:not(.has-touch) .fullscreen-button:hover { + opacity: 1; +} + +.is-fullscreen .fullscreen-button { + background-image: url(../../images/icon/fullscreen-exit.svg); +} + +.workspace-controls input[type=range]::-webkit-slider-runnable-track::before, +.has-touch .workspace-controls input[type=range]::-webkit-slider-thumb { + background-color: rgba(0, 0, 0, 0.2); +} + +.workspace-controls input[type=range]:focus::-webkit-slider-thumb, +.workspace-controls input[type=range]:active::-webkit-slider-thumb, +.workspace-controls input[type=range]:focus::-webkit-slider-runnable-track::before, +.workspace-controls input[type=range]:active::-webkit-slider-runnable-track::before, +.has-touch .workspace-controls input[type=range]:focus::-webkit-slider-thumb, +.has-touch .workspace-controls input[type=range]:active::-webkit-slider-thumb { + background-color: rgba(0, 0, 0, 0.5); +} + +.workspace-controls input[type=range]::-webkit-slider-thumb::before, +.workspace-controls input[type=range]::-webkit-slider-thumb::after { + background-color: rgba(0, 0, 0, 0.9); +} + +.workspace-controls input[type=range]::-moz-range-track { + background: linear-gradient( + to bottom, + rgba(0, 0, 0, 0) 0%, + rgba(0, 0, 0, 0) 41.9%, + rgba(0, 0, 0, 0.2) 42%, + rgba(0, 0, 0, 0.2) 58%, + rgba(0, 0, 0, 0) 58.1%, + rgba(0, 0, 0, 0) 100% + ); +} + +.workspace-controls .has-touch input[type=range]::-moz-range-track { + background: linear-gradient( + to bottom, + rgba(0, 0, 0, 0) 0%, + rgba(0, 0, 0, 0) 49.9%, + rgba(0, 0, 0, 0.2) 50%, + rgba(0, 0, 0, 0.2) 55%, + rgba(0, 0, 0, 0) 55.1%, + rgba(0, 0, 0, 0) 100% + ); +} + +.workspace-controls input[type=range]::-moz-range-thumb { + background: radial-gradient( + ellipse at center, + rgba(0, 0, 0 ,1) 0%, + rgba(0, 0, 0 ,1) 30%, + rgba(0, 0, 0 ,0) 30.1%, + rgba(0, 0, 0 ,0) 100% + ); +} + +.workspace-controls input[type=range]::-moz-range-thumb:hover, +.has-touch .workspace-controls input[type=range]::-moz-range-thumb { + background: radial-gradient( + ellipse at center, + rgba(0, 0, 0, 1) 0%, + rgba(0, 0, 0, 1) 30%, + rgba(0, 0, 0, 0.2) 30.1%, + rgba(0, 0, 0, 0.2) 100% + ); +} + +.workspace-controls input[type=range]:focus::-moz-range-thumb, +.workspace-controls input[type=range]:active::-moz-range-thumb, +.has-touch .workspace-controls input[type=range]:focus::-moz-range-thumb, +.has-touch .workspace-controls input[type=range]:active::-moz-range-thumb { + background: radial-gradient( + ellipse at center, + rgba(0, 0, 0, 1) 0%, + rgba(0, 0, 0, 1) 30%, + rgba(0, 0, 0, 0.5) 30.1%, + rgba(0, 0, 0, 0.5) 100% + ); +} + +.workspace-controls input[type=range]::-ms-track { + background-color: rgba(0, 0, 0, 0.2); +} + +.workspace-controls input[type=range]::-ms-fill-lower, +.workspace-controls input[type=range]::-ms-thumb { + background: #000; +} + +.has-touch .workspace-controls input[type=range]::-ms-thumb { + border-color: rgba(0, 0, 0, 0.5); +} + +.has-touch .workspace-controls input[type=range]:active::-ms-thumb, +.has-touch .workspace-controls input[type=range]:focus::-ms-thumb { + border-color: rgba(0, 0, 0, 1); +} + +/*workspace ui*/ +@media screen and (min-width: 300px) { + html:not(.has-touch) .workspace-controls .scale-slider { + display: inline-block; + } +} + +@media screen and (min-width: 400px) { + html:not(.has-touch) .nav:not(.is-active) ~ .workspace .scale-label { + display: inline-block; + } + + html:not(.has-touch) .nav:not(.is-active) ~ .workspace .scale-slider { + width: calc(100% - 300px); + } + + .has-touch .nav:not(.is-active) ~ .workspace .scale-slider { + display: inline-block; + } +} + +@media screen and (min-width: 700px) { + html:not(.has-touch) .nav ~ .workspace .scale-label { + display: inline-block; + } + + html:not(.has-touch) .nav ~ .workspace .scale-slider { + width: calc(100% - 300px); + } + + .has-touch .nav ~ .workspace .scale-slider { + display: inline-block; + } +} + +@media screen and (min-width: 440px) { + .nav:not(.is-active) ~ .workspace .scale-slider { + width: calc(100% - 320px); + margin-left: 20px; + margin-right: 20px; + } + + .has-touch .nav:not(.is-active) ~ .workspace .scale-slider { + width: calc(100% - 360px); + } + + .has-touch .nav:not(.is-active) ~ .workspace .scale-label { + display: inline-block; + } +} + +@media screen and (min-width: 740px) { + .nav ~ .workspace .scale-slider { + width: calc(100% - 320px); + margin-left: 20px; + margin-right: 20px; + } + + .has-touch .nav ~ .workspace .scale-slider { + width: calc(100% - 360px); + } + + .has-touch .nav ~ .workspace .scale-label { + display: inline-block; + } +} + +@media screen and (min-width: 700px) { + .workspace-controls .controls-toggle-button { + padding-left: 20px; + position: relative; + } + + .has-touch .workspace-controls .controls-toggle-button { + text-indent: 10px; + } + + .workspace-controls .controls-toggle-button::before { + content: ''; + position: absolute; + width: 20px; + height: 20px; + background-image: url(../../images/icon/chevron-down-black.svg); + background-size: contain; + background-position: center; + background-repeat: no-repeat; + top: 50%; + left: 0; + transform: translateY(-50%) rotate(-180deg); + transition: all 0.3s ease-out; + } + + .workspace-controls .controls-toggle-button.is-active::before { + transform: translateY(-50%) rotate(0deg); + } + + .has-touch .workspace-controls .controls-toggle-button::before { + left: 5px; + } +} \ No newline at end of file diff --git a/styles/modules/workspace.css b/styles/modules/workspace.css new file mode 100644 index 0000000..bbaefd9 --- /dev/null +++ b/styles/modules/workspace.css @@ -0,0 +1,22 @@ +.workspace { + width: 100%; + height: 100%; + position: absolute; + right: 0; + top: 0; + transition: all 0.3s ease-out; + display: flex; + flex-direction: column-reverse; +} + +@media screen and (min-width: 600px) { + .nav.is-active ~ .workspace { + width: calc(100% - 300px); + } +} + +@media screen and (min-width: 1200px) { + .nav ~ .workspace { + width: calc(100% - 300px); + } +} \ No newline at end of file