Fix a lot eslint errors.

This commit is contained in:
Lars Jung
2015-11-18 23:16:58 +01:00
parent 0c6143704a
commit 39ea94daa8
88 changed files with 3872 additions and 4930 deletions

View File

@@ -7,9 +7,6 @@
es6: true es6: true
node: true node: true
globals:
modulejs: false
ecmaFeatures: ecmaFeatures:
arrowFunctions: true arrowFunctions: true
binaryLiterals: true binaryLiterals: true
@@ -68,7 +65,7 @@
max-nested-callbacks: [1, 3] max-nested-callbacks: [1, 3]
max-params: [1, 5] ### max-params: [1, 5] ###
max-statements: [1, 80] ### max-statements: [1, 80] ###
new-cap: 1 new-cap: 0
new-parens: 2 new-parens: 2
newline-after-var: 0 newline-after-var: 0
no-alert: 2 no-alert: 2

View File

@@ -14,7 +14,8 @@
* fixes preview bottom bar for small screen widths * fixes preview bottom bar for small screen widths
* lots of code cleanup and refactorings * lots of code cleanup and refactorings
* changes API * changes API
* updates build process * updates build process, now uses [ghu](https://larsjung.de/ghu/)
* switches from jshint and jscs to [eslint](http://eslint.org/)
* updates `lodash` to 3.8.0 (adds debounce and trim) * updates `lodash` to 3.8.0 (adds debounce and trim)
* updates h5bp styles to 5.1.0 * updates h5bp styles to 5.1.0
* updates `normalize.css` to 3.0.3 * updates `normalize.css` to 3.0.3
@@ -40,7 +41,7 @@
* improves drag-select * improves drag-select
* improves image preview * improves image preview
* prevents listing `_h5ai` folder and subfolders * prevents listing `_h5ai` folder and subfolders
* updates build process, now uses [mkr](http://larsjung.de/mkr/) and [fQuery](http://larsjung.de/fquery/) * updates build process, now uses [mkr](https://larsjung.de/mkr/) and [fQuery](https://larsjung.de/fquery/)
* updates `jQuery` to 2.1.3 * updates `jQuery` to 2.1.3
* updates `jQuery.qrcode` to 0.11.0 * updates `jQuery.qrcode` to 0.11.0
* updates `Lo-Dash` to 3.6.0 * updates `Lo-Dash` to 3.6.0
@@ -222,9 +223,9 @@
* changes language code `gr` to `el` * changes language code `gr` to `el`
* adds localization for filter placeholder * adds localization for filter placeholder
* adds `hu` translation by [Rodolffo](https://github.com/Rodolffo) * adds `hu` translation by [Rodolffo](https://github.com/Rodolffo)
* updates to [jQuery.qrcode](http://larsjung.de/qrcode/) 0.2 * updates to [jQuery.qrcode](https://larsjung.de/qrcode/) 0.2
* updates to [jQuery.scrollpanel](http://larsjung.de/scrollpanel/) 0.1 * updates to [jQuery.scrollpanel](https://larsjung.de/scrollpanel/) 0.1
* updates to [modulejs](http://larsjung.de/modulejs/) 0.2 * updates to [modulejs](https://larsjung.de/modulejs/) 0.2
* updates to [Moment.js](http://momentjs.com) 1.7.0 * updates to [Moment.js](http://momentjs.com) 1.7.0
* updates to [Underscore.js](http://underscorejs.org) 1.3.3 * updates to [Underscore.js](http://underscorejs.org) 1.3.3

View File

@@ -40,7 +40,7 @@ To build the frontend test suite run `npm run build-test`. This will output a
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 Lars Jung (http://larsjung.de) Copyright (c) 2015 Lars Jung (https://larsjung.de)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@@ -67,14 +67,14 @@ THE SOFTWARE.
too. Exceptions are the [Material Design icons][material-design-icons] (CC BY 4.0). too. Exceptions are the [Material Design icons][material-design-icons] (CC BY 4.0).
[web]: http://larsjung.de/h5ai/ [web]: https://larsjung.de/h5ai/
[github]: https://github.com/lrsjng/h5ai [github]: https://github.com/lrsjng/h5ai
[github-issues]: https://github.com/lrsjng/h5ai/issues [github-issues]: https://github.com/lrsjng/h5ai/issues
[release]: http://release.larsjung.de/h5ai/ [release]: https://release.larsjung.de/h5ai/
[develop]: http://release.larsjung.de/h5ai/develop/ [develop]: https://release.larsjung.de/h5ai/develop/
[git]: http://git-scm.com [git]: https://git-scm.com
[node]: https://nodejs.org [node]: https://nodejs.org
[mkr]: http://larsjung.de/mkr/ [mkr]: https://larsjung.de/mkr/
[material-design-icons]: https://github.com/google/material-design-icons [material-design-icons]: https://github.com/google/material-design-icons
[license-img]: https://img.shields.io/badge/license-MIT-a0a060.svg?style=flat-square [license-img]: https://img.shields.io/badge/license-MIT-a0a060.svg?style=flat-square

12
ghu.js
View File

@@ -2,12 +2,13 @@ import {resolve, join} from 'path';
import dateformat from 'dateformat'; import dateformat from 'dateformat';
import ghu from 'ghu'; import ghu from 'ghu';
import { import {
autoprefixer, babel, cssmin, ife, includeit, jade, jszip, autoprefixer, cssmin, ife, includeit, jade, jszip,
less, mapfn, newerThan, read, remove, run, uglify, watch, wrap, write less, mapfn, newerThan, read, remove, run, uglify, watch, wrap, write
} from 'ghu'; } from 'ghu';
const ROOT = resolve(__dirname); const ROOT = resolve(__dirname);
const SRC = join(ROOT, 'src'); const SRC = join(ROOT, 'src');
const TEST = join(ROOT, 'test');
const BUILD = join(ROOT, 'build'); const BUILD = join(ROOT, 'build');
const mapper = mapfn.p(SRC, BUILD).s('.less', '.css').s('.jade', ''); const mapper = mapfn.p(SRC, BUILD).s('.less', '.css').s('.jade', '');
@@ -54,7 +55,6 @@ ghu.task('build:scripts', runtime => {
return read(`${SRC}/_h5ai/public/js/*.js`) return read(`${SRC}/_h5ai/public/js/*.js`)
.then(newerThan(mapper, `${SRC}/_h5ai/public/js/**`)) .then(newerThan(mapper, `${SRC}/_h5ai/public/js/**`))
.then(includeit()) .then(includeit())
// .then(babel({compact: false}))
.then(ife(() => runtime.args.production, uglify())) .then(ife(() => runtime.args.production, uglify()))
.then(wrap(runtime.commentJs)) .then(wrap(runtime.commentJs))
.then(write(mapper, {overwrite: true})); .then(write(mapper, {overwrite: true}));
@@ -100,19 +100,19 @@ ghu.task('build:copy', runtime => {
ghu.task('build:tests', ['build:scripts', 'build:styles'], 'build the test suite', runtime => { ghu.task('build:tests', ['build:scripts', 'build:styles'], 'build the test suite', runtime => {
return Promise.all([ return Promise.all([
read(`${ROOT}/test/scripts.js`) read(`${TEST}/scripts.js`)
.then(newerThan(`${BUILD}/test/scripts.js`)) .then(newerThan(`${BUILD}/test/scripts.js`))
.then(includeit()) .then(includeit())
.then(write(`${BUILD}/test/scripts.js`, {overwrite: true})), .then(write(`${BUILD}/test/scripts.js`, {overwrite: true})),
read(`${ROOT}/test/styles.less`) read(`${TEST}/styles.less`)
.then(newerThan(`${BUILD}/test/styles.css`)) .then(newerThan(`${BUILD}/test/styles.css`))
.then(includeit()) .then(includeit())
.then(less()) .then(less())
.then(autoprefixer()) .then(autoprefixer())
.then(write(`${BUILD}/test/styles.css`, {overwrite: true})), .then(write(`${BUILD}/test/styles.css`, {overwrite: true})),
read(`${ROOT}/test/index.html.jade`) read(`${TEST}/index.html.jade`)
.then(newerThan(`${BUILD}/test/index.html`)) .then(newerThan(`${BUILD}/test/index.html`))
.then(jade({pkg: runtime.pkg})) .then(jade({pkg: runtime.pkg}))
.then(write(`${BUILD}/test/index.html`, {overwrite: true})), .then(write(`${BUILD}/test/index.html`, {overwrite: true})),
@@ -146,7 +146,7 @@ ghu.task('deploy', ['build'], 'deploy to a specified path with :dest=/some/path'
}); });
ghu.task('watch', runtime => { ghu.task('watch', runtime => {
return watch([SRC], () => ghu.run(runtime.sequence.filter(x => x !== 'watch'), runtime.args, true)); return watch([SRC, TEST], () => ghu.run(runtime.sequence.filter(x => x !== 'watch'), runtime.args, true));
}); });
ghu.task('release', ['force-production', 'clean', 'build'], 'create a zipball', runtime => { ghu.task('release', ['force-production', 'clean', 'build'], 'create a zipball', runtime => {

View File

@@ -1,7 +1,6 @@
{ {
"name": "h5ai", "name": "h5ai",
"version": "0.27.0", "version": "0.27.0",
"develop": true,
"description": "A modern HTTP web server index.", "description": "A modern HTTP web server index.",
"homepage": "https://larsjung.de/h5ai/", "homepage": "https://larsjung.de/h5ai/",
"bugs": "https://github.com/lrsjng/h5ai/issues", "bugs": "https://github.com/lrsjng/h5ai/issues",

43
src/.eslintrc Normal file
View File

@@ -0,0 +1,43 @@
---
env:
es6: false
node: false
browser: true
mocha: false
globals:
modulejs: false
ecmaFeatures:
arrowFunctions: false
binaryLiterals: false
blockBindings: false
classes: false
defaultParams: false
destructuring: false
forOf: false
generators: false
globalReturn: false
jsx: false
modules: false
objectLiteralComputedProperties: false
objectLiteralDuplicateProperties: false
objectLiteralShorthandMethods: false
objectLiteralShorthandProperties: false
octalLiterals: false
regexUFlag: false
regexYFlag: false
spread: false
superInFunctions: false
templateStrings: false
unicodeCodePointEscapes: false
rules:
consistent-this: 0
func-names: 0
max-params: [1, 10]
no-invalid-this: 0
no-var: 0
object-shorthand: 0
prefer-arrow-callback: 0
prefer-reflect: 0

View File

@@ -1,11 +1,11 @@
modulejs.define('boot', ['$', 'core/server'], function ($, server) { modulejs.define('boot', ['$', 'core/server'], function ($, server) {
var module = $('script[data-module]').data('module'); var module = $('script[data-module]').data('module');
var data = { var data = {
action: 'get', action: 'get',
setup: true, setup: true,
options: true, options: true,
types: true types: true
}; };
if (module === 'index') { if (module === 'index') {
data.theme = true; data.theme = true;

View File

@@ -1,13 +1,9 @@
modulejs.define('core/event', ['_'], function (_) { modulejs.define('core/event', ['_'], function (_) {
var slice = Array.prototype.slice; var slice = Array.prototype.slice;
var subscriptions = {}; var subscriptions = {};
function sub(topic, callback) { function sub(topic, callback) {
if (_.isString(topic) && _.isFunction(callback)) { if (_.isString(topic) && _.isFunction(callback)) {
if (!subscriptions[topic]) { if (!subscriptions[topic]) {
subscriptions[topic] = []; subscriptions[topic] = [];
} }
@@ -16,21 +12,16 @@ modulejs.define('core/event', ['_'], function (_) {
} }
function unsub(topic, callback) { function unsub(topic, callback) {
if (_.isString(topic) && _.isFunction(callback) && subscriptions[topic]) { if (_.isString(topic) && _.isFunction(callback) && subscriptions[topic]) {
subscriptions[topic] = _.without(subscriptions[topic], callback); subscriptions[topic] = _.without(subscriptions[topic], callback);
} }
} }
function pub(topic) { function pub(topic) {
var args = slice.call(arguments, 1); var args = slice.call(arguments, 1);
if (_.isString(topic) && subscriptions[topic]) { if (_.isString(topic) && subscriptions[topic]) {
_.each(subscriptions[topic], function (callback) { _.each(subscriptions[topic], function (callback) {
callback.apply(topic, args); callback.apply(topic, args);
}); });
} }

View File

@@ -1,41 +1,38 @@
modulejs.define('core/format', ['_'], function (_) { modulejs.define('core/format', ['_'], function (_) {
var decimalMetric = { var decimalMetric = {
t: 1000.0, t: 1000.0,
k: 1000.0, k: 1000.0,
u: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] u: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
}; };
var binaryMetric = { var binaryMetric = {
t: 1024.0, t: 1024.0,
k: 1024.0, k: 1024.0,
u: ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'] u: ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
}; };
var defaultMetric = decimalMetric; var defaultMetric = decimalMetric;
var datePatterns = [ var datePatterns = [
[/YYYY/, 'Y', 4], [/YYYY/, 'Y', 4],
[/YY/, 'Y', 2], [/YY/, 'Y', 2],
[/Y/, 'Y', 0], [/Y/, 'Y', 0],
[/MM/, 'M', 2], [/MM/, 'M', 2],
[/M/, 'M', 0], [/M/, 'M', 0],
[/DD/, 'D', 2], [/DD/, 'D', 2],
[/D/, 'D', 0], [/D/, 'D', 0],
[/HH/, 'H', 2], [/HH/, 'H', 2],
[/H/, 'H', 0], [/H/, 'H', 0],
[/mm/, 'm', 2], [/mm/, 'm', 2],
[/m/, 'm', 0], [/m/, 'm', 0],
[/ss/, 's', 2], [/ss/, 's', 2],
[/s/, 's', 0] [/s/, 's', 0]
]; ];
var defaultDateFormat = 'YYYY-MM-DD HH:mm'; var defaultDateFormat = 'YYYY-MM-DD HH:mm';
function setDefaultMetric(useBinaryMetric) { function setDefaultMetric(useBinaryMetric) {
defaultMetric = useBinaryMetric ? binaryMetric : decimalMetric; defaultMetric = useBinaryMetric ? binaryMetric : decimalMetric;
} }
function formatSize(size, metric) { function formatSize(size, metric) {
metric = metric || defaultMetric; metric = metric || defaultMetric;
if (!_.isNumber(size) || size < 0) { if (!_.isNumber(size) || size < 0) {
@@ -53,12 +50,10 @@ modulejs.define('core/format', ['_'], function (_) {
} }
function setDefaultDateFormat(dateFormat) { function setDefaultDateFormat(dateFormat) {
defaultDateFormat = dateFormat; defaultDateFormat = dateFormat;
} }
function formatNumber(number, padding) { function formatNumber(number, padding) {
var str = String(number); var str = String(number);
if (padding) { if (padding) {
str = ('000' + str).substr(-padding); str = ('000' + str).substr(-padding);
@@ -67,7 +62,6 @@ modulejs.define('core/format', ['_'], function (_) {
} }
function formatDate(millis, format) { function formatDate(millis, format) {
if (!millis || !_.isNumber(millis)) { if (!millis || !_.isNumber(millis)) {
return ''; return '';
} }
@@ -76,13 +70,13 @@ modulejs.define('core/format', ['_'], function (_) {
var date = new Date(millis); var date = new Date(millis);
var d = { var d = {
Y: date.getFullYear(), Y: date.getFullYear(),
M: date.getMonth() + 1, M: date.getMonth() + 1,
D: date.getDate(), D: date.getDate(),
H: date.getHours(), H: date.getHours(),
m: date.getMinutes(), m: date.getMinutes(),
s: date.getSeconds() s: date.getSeconds()
}; };
datePatterns.forEach(function (pattern) { datePatterns.forEach(function (pattern) {
format = format.replace(pattern[0], formatNumber(d[pattern[1]], pattern[2])); format = format.replace(pattern[0], formatNumber(d[pattern[1]], pattern[2]));

View File

@@ -1,4 +1,3 @@
modulejs.define('core/langs', ['_', 'config'], function (_, config) { modulejs.define('core/langs', ['_', 'config'], function (_, config) {
return _.extend({}, config.langs); return _.extend({}, config.langs);
}); });

View File

@@ -1,50 +1,45 @@
modulejs.define('core/location', ['_', 'core/event', 'core/modernizr', 'core/settings', 'view/notification'], function (_, event, modernizr, allsettings, notification) { modulejs.define('core/location', ['_', 'core/event', 'core/modernizr', 'core/settings', 'view/notification'], function (_, event, modernizr, allsettings, notification) {
var settings = _.extend({ var settings = _.extend({
fastBrowsing: true, fastBrowsing: true,
unmanagedInNewWindow: true unmanagedInNewWindow: true
}, allsettings.view); }, allsettings.view);
var doc = document; var doc = document;
var history = settings.fastBrowsing && modernizr.history ? window.history : null; var history = settings.fastBrowsing && modernizr.history ? window.history : null;
var reUriToPathname = /^.*:\/\/[^\/]*|[^\/]*$/g; var reUriToPathname = /^.*:\/\/[^\/]*|[^\/]*$/g;
var absHref = null; var absHref = null;
var reForceEncoding = [ var reForceEncoding = [
[/\/+/g, '/'], [/\/+/g, '/'],
[/ /g, '%20'], [/ /g, '%20'],
[/!/g, '%21'], [/!/g, '%21'],
[/#/g, '%23'], [/#/g, '%23'],
[/\$/g, '%24'], [/\$/g, '%24'],
[/&/g, '%26'], [/&/g, '%26'],
[/'/g, '%27'], [/'/g, '%27'],
[/\(/g, '%28'], [/\(/g, '%28'],
[/\)/g, '%29'], [/\)/g, '%29'],
[/\*/g, '%2A'], [/\*/g, '%2A'],
[/\+/g, '%2B'], [/\+/g, '%2B'],
[/\,/g, '%2C'], [/\,/g, '%2C'],
[/:/g, '%3A'], [/:/g, '%3A'],
[/;/g, '%3B'], [/;/g, '%3B'],
[/=/g, '%3D'], [/\=/g, '%3D'],
[/\?/g, '%3F'], [/\?/g, '%3F'],
[/@/g, '%40'], [/@/g, '%40'],
[/\[/g, '%5B'], [/\[/g, '%5B'],
[/\]/g, '%5D'] [/\]/g, '%5D']
]; ];
function forceEncoding(href) { function forceEncoding(href) {
return reForceEncoding.reduce(function (nuHref, data) {
return reForceEncoding.reduce(function (href, data) { return nuHref.replace(data[0], data[1]);
return href.replace(data[0], data[1]);
}, href); }, href);
} }
function uriToPathname(uri) { function uriToPathname(uri) {
return uri.replace(reUriToPathname, ''); return uri.replace(reUriToPathname, '');
} }
var hrefsAreDecoded = (function () { var hrefsAreDecoded = (function () {
var testpathname = '/a b'; var testpathname = '/a b';
var a = doc.createElement('a'); var a = doc.createElement('a');
@@ -53,7 +48,6 @@ modulejs.define('core/location', ['_', 'core/event', 'core/modernizr', 'core/set
}()); }());
function encodedHref(href) { function encodedHref(href) {
var a = doc.createElement('a'); var a = doc.createElement('a');
var location; var location;
@@ -68,39 +62,31 @@ modulejs.define('core/location', ['_', 'core/event', 'core/modernizr', 'core/set
} }
function getDomain() { function getDomain() {
return doc.domain; return doc.domain;
} }
function getAbsHref() { function getAbsHref() {
return absHref; return absHref;
} }
function getItem() { function getItem() {
return modulejs.require('model/item').get(absHref); return modulejs.require('model/item').get(absHref);
} }
function load(callback) { function load(callback) {
modulejs.require('core/server').request({action: 'get', items: {href: absHref, what: 1}}, function (json) { modulejs.require('core/server').request({action: 'get', items: {href: absHref, what: 1}}, function (json) {
var Item = modulejs.require('model/item'); var Item = modulejs.require('model/item');
var item = Item.get(absHref); var item = Item.get(absHref);
if (json) { if (json) {
var found = {}; var found = {};
_.each(json.items, function (jsonItem) { _.each(json.items, function (jsonItem) {
var e = Item.get(jsonItem); var e = Item.get(jsonItem);
found[e.absHref] = true; found[e.absHref] = true;
}); });
_.each(item.content, function (e) { _.each(item.content, function (e) {
if (!found[e.absHref]) { if (!found[e.absHref]) {
Item.remove(e.absHref); Item.remove(e.absHref);
} }
@@ -112,8 +98,22 @@ modulejs.define('core/location', ['_', 'core/event', 'core/modernizr', 'core/set
}); });
} }
function setLocation(newAbsHref, keepBrowserUrl) { function refresh() {
var item = getItem();
var oldItems = _.values(item.content);
event.pub('location.beforeRefresh');
load(function () {
var newItems = _.values(item.content);
var added = _.difference(newItems, oldItems);
var removed = _.difference(oldItems, newItems);
event.pub('location.refreshed', item, added, removed);
});
}
function setLocation(newAbsHref, keepBrowserUrl) {
event.pub('location.beforeChange'); event.pub('location.beforeChange');
newAbsHref = encodedHref(newAbsHref); newAbsHref = encodedHref(newAbsHref);
@@ -144,30 +144,11 @@ modulejs.define('core/location', ['_', 'core/event', 'core/modernizr', 'core/set
} }
} }
function refresh() {
var item = getItem();
var oldItems = _.values(item.content);
event.pub('location.beforeRefresh');
load(function () {
var newItems = _.values(item.content);
var added = _.difference(newItems, oldItems);
var removed = _.difference(oldItems, newItems);
event.pub('location.refreshed', item, added, removed);
});
}
function setLink($el, item) { function setLink($el, item) {
$el.attr('href', item.absHref); $el.attr('href', item.absHref);
if (history && item.isFolder() && item.isManaged) { if (history && item.isFolder() && item.isManaged) {
$el.on('click', function () { $el.on('click', function () {
setLocation(item.absHref); setLocation(item.absHref);
return false; return false;
}); });
@@ -179,7 +160,6 @@ modulejs.define('core/location', ['_', 'core/event', 'core/modernizr', 'core/set
} }
function onPopState(ev) { function onPopState(ev) {
if (ev.state && ev.state.absHref) { if (ev.state && ev.state.absHref) {
setLocation(ev.state.absHref, true); setLocation(ev.state.absHref, true);
} }

View File

@@ -1,7 +1,5 @@
modulejs.define('core/modernizr', function () { modulejs.define('core/modernizr', function () {
var hasCanvas = (function () { var hasCanvas = (function () {
var elem = document.createElement('canvas'); var elem = document.createElement('canvas');
return Boolean(elem.getContext && elem.getContext('2d')); return Boolean(elem.getContext && elem.getContext('2d'));
}()); }());
@@ -9,7 +7,6 @@ modulejs.define('core/modernizr', function () {
var hasHistory = Boolean(window.history && history.pushState); var hasHistory = Boolean(window.history && history.pushState);
var hasLocalStorage = (function () { var hasLocalStorage = (function () {
var key = '#test#'; var key = '#test#';
try { try {
localStorage.setItem(key, key); localStorage.setItem(key, key);

View File

@@ -1,5 +1,4 @@
modulejs.define('core/resource', ['_', 'config', 'core/settings'], function (_, config, settings) { modulejs.define('core/resource', ['_', 'config', 'core/settings'], function (_, config, settings) {
var imagesHref = settings.publicHref + 'images/'; var imagesHref = settings.publicHref + 'images/';
var uiHref = imagesHref + 'ui/'; var uiHref = imagesHref + 'ui/';
var themesHref = imagesHref + 'themes/'; var themesHref = imagesHref + 'themes/';
@@ -8,12 +7,10 @@ modulejs.define('core/resource', ['_', 'config', 'core/settings'], function (_,
function image(id) { function image(id) {
return uiHref + id + '.svg'; return uiHref + id + '.svg';
} }
function icon(id) { function icon(id) {
var baseId = (id || '').split('-')[0]; var baseId = (id || '').split('-')[0];
var href = config.theme[id] || config.theme[baseId]; var href = config.theme[id] || config.theme[baseId];

View File

@@ -1,7 +1,5 @@
modulejs.define('core/server', ['_', '$'], function (_, $) { modulejs.define('core/server', ['_', '$'], function (_, $) {
function request(data, callback) { function request(data, callback) {
$.ajax({ $.ajax({
url: '?', url: '?',
data: data, data: data,
@@ -9,21 +7,17 @@ modulejs.define('core/server', ['_', '$'], function (_, $) {
dataType: 'json' dataType: 'json'
}) })
.done(function (json) { .done(function (json) {
callback(json); callback(json);
}) })
.fail(function () { .fail(function () {
callback(); callback();
}); });
} }
function formRequest(data) { function formRequest(data) {
var $form = $('<form method="post" action="?" style="display:none;"/>'); var $form = $('<form method="post" action="?" style="display:none;"/>');
_.each(data, function (val, key) { _.each(data, function (val, key) {
$('<input type="hidden"/>') $('<input type="hidden"/>')
.attr('name', key) .attr('name', key)
.attr('value', val) .attr('value', val)

View File

@@ -1,5 +1,4 @@
modulejs.define('core/settings', ['_', 'config'], function (_, config) { modulejs.define('core/settings', ['_', 'config'], function (_, config) {
return _.extend({}, config.options, { return _.extend({}, config.options, {
publicHref: config.setup.PUBLIC_HREF, publicHref: config.setup.PUBLIC_HREF,
rootHref: config.setup.ROOT_HREF rootHref: config.setup.ROOT_HREF

View File

@@ -1,31 +1,26 @@
modulejs.define('core/store', ['core/modernizr'], function (modernizr) { modulejs.define('core/store', ['core/modernizr'], function (modernizr) {
var store = modernizr.localstorage ? window.localStorage : {}; var store = modernizr.localstorage ? window.localStorage : {};
var storekey = '_h5ai'; var storekey = '_h5ai';
function load() { function load() {
try { try {
return JSON.parse(store[storekey]); return JSON.parse(store[storekey]);
} catch (e) {} } catch (e) {/* skip */}
return {}; return {};
} }
function save(obj) { function save(obj) {
store[storekey] = JSON.stringify(obj); store[storekey] = JSON.stringify(obj);
} }
function put(key, value) { function put(key, value) {
var obj = load(); var obj = load();
obj[key] = value; obj[key] = value;
save(obj); save(obj);
} }
function get(key) { function get(key) {
return load()[key]; return load()[key];
} }

View File

@@ -1,26 +1,21 @@
modulejs.define('core/types', ['_', 'config'], function (_, config) { modulejs.define('core/types', ['_', 'config'], function (_, config) {
var reEndsWithSlash = /\/$/; var reEndsWithSlash = /\/$/;
var regexps = {}; var regexps = {};
function escapeRegExp(sequence) { function escapeRegExp(sequence) {
return sequence.replace(/[\-\[\]\/\{\}\(\)\+\?\.\\\^\$]/g, '\\$&'); return sequence.replace(/[\-\[\]\/\{\}\(\)\+\?\.\\\^\$]/g, '\\$&');
// return sequence.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); // return sequence.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
} }
function parse(types) { function parse(types) {
_.each(types, function (patterns, type) { _.each(types, function (patterns, type) {
var pattern = '^(' + _.map(patterns, function (p) { return '(' + escapeRegExp(p).replace(/\*/g, '.*') + ')'; }).join('|') + ')$'; var pattern = '^(' + _.map(patterns, function (p) { return '(' + escapeRegExp(p).replace(/\*/g, '.*') + ')'; }).join('|') + ')$';
regexps[type] = new RegExp(pattern, 'i'); regexps[type] = new RegExp(pattern, 'i');
}); });
} }
function getType(sequence) { function getType(sequence) {
if (reEndsWithSlash.test(sequence)) { if (reEndsWithSlash.test(sequence)) {
return 'folder'; return 'folder';
} }
@@ -30,7 +25,6 @@ modulejs.define('core/types', ['_', 'config'], function (_, config) {
var result; var result;
_.each(regexps, function (regexp, type) { _.each(regexps, function (regexp, type) {
if (regexps[type].test(name)) { if (regexps[type].test(name)) {
result = type; result = type;
return false; return false;

View File

@@ -1,8 +1,5 @@
modulejs.define('core/util', ['_'], function (_) { modulejs.define('core/util', ['_'], function (_) {
function regularCmpFn(val1, val2) { function regularCmpFn(val1, val2) {
if (val1 < val2) { if (val1 < val2) {
return -1; return -1;
} }
@@ -17,7 +14,6 @@ modulejs.define('core/util', ['_'], function (_) {
// //
// Modified to make it work with h5ai // Modified to make it work with h5ai
function naturalCmpFn(val1, val2) { function naturalCmpFn(val1, val2) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi; var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi;
var sre = /(^[ ]*|[ ]*$)/g; var sre = /(^[ ]*|[ ]*$)/g;
var dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/; var dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/;
@@ -30,7 +26,7 @@ modulejs.define('core/util', ['_'], function (_) {
var xN = x.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'); var xN = x.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0');
var yN = y.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'); var yN = y.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0');
// numeric, hex or date detection // numeric, hex or date detection
var xD = parseInt(x.match(hre), 10) || (xN.length !== 1 && x.match(dre) && Date.parse(x)); var xD = parseInt(x.match(hre), 10) || xN.length !== 1 && x.match(dre) && Date.parse(x);
var yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null; var yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
var oFxNcL; var oFxNcL;
var oFyNcL; var oFyNcL;
@@ -49,7 +45,7 @@ modulejs.define('core/util', ['_'], function (_) {
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams) // handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
return (isNaN(oFxNcL)) ? 1 : -1; return isNaN(oFxNcL) ? 1 : -1;
} else if (typeof oFxNcL !== typeof oFyNcL) { } else if (typeof oFxNcL !== typeof oFyNcL) {
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
oFxNcL += ''; oFxNcL += '';
@@ -66,12 +62,10 @@ modulejs.define('core/util', ['_'], function (_) {
} }
function escapePattern(sequence) { function escapePattern(sequence) {
return sequence.replace(/[\-\[\]{}()*+?.,\\$\^|#\s]/g, '\\$&'); return sequence.replace(/[\-\[\]{}()*+?.,\\$\^|#\s]/g, '\\$&');
} }
function parsePattern(sequence, advanced) { function parsePattern(sequence, advanced) {
if (!advanced) { if (!advanced) {
return escapePattern(sequence); return escapePattern(sequence);
} }
@@ -81,9 +75,7 @@ modulejs.define('core/util', ['_'], function (_) {
} }
sequence = _.map(_.trim(sequence).split(/\s+/), function (part) { sequence = _.map(_.trim(sequence).split(/\s+/), function (part) {
return _.map(part.split(''), function (character) { return _.map(part.split(''), function (character) {
return escapePattern(character); return escapePattern(character);
}).join('.*?'); }).join('.*?');
}).join('|'); }).join('|');

View File

@@ -1,30 +1,25 @@
modulejs.define('ext/autorefresh', ['_', '$', 'core/event', 'core/location', 'core/settings'], function (_, $, event, location, allsettings) { modulejs.define('ext/autorefresh', ['_', '$', 'core/event', 'core/location', 'core/settings'], function (_, $, event, location, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
interval: 5000 interval: 5000
}, allsettings.autorefresh); }, allsettings.autorefresh);
var timeoutId = null; var timeoutId = null;
function heartbeat() { function heartbeat() {
location.refresh(); location.refresh();
} }
function before() { function before() {
clearTimeout(timeoutId); clearTimeout(timeoutId);
} }
function after() { function after() {
clearTimeout(timeoutId); clearTimeout(timeoutId);
timeoutId = setTimeout(heartbeat, settings.interval); timeoutId = setTimeout(heartbeat, settings.interval);
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,8 +1,7 @@
modulejs.define('ext/contextmenu', ['_', '$', 'core/resource', 'core/settings'], function (_, $, resource, allsettings) { modulejs.define('ext/contextmenu', ['_', '$', 'core/resource', 'core/settings'], function (_, $, resource, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false enabled: false
}, allsettings.contextmenu); }, allsettings.contextmenu);
var templateOverlay = '<div id="cm-overlay"/>'; var templateOverlay = '<div id="cm-overlay"/>';
var templatePanel = '<div class="cm-panel"><ul/></div>'; var templatePanel = '<div class="cm-panel"><ul/></div>';
var templateSep = '<li class="cm-sep"/>'; var templateSep = '<li class="cm-sep"/>';
@@ -11,12 +10,10 @@ modulejs.define('ext/contextmenu', ['_', '$', 'core/resource', 'core/settings'],
function createOverlay(callback) { function createOverlay(callback) {
var $overlay = $(templateOverlay); var $overlay = $(templateOverlay);
$overlay $overlay
.on('click contextmenu', function (ev) { .on('click contextmenu', function (ev) {
ev.stopPropagation(); ev.stopPropagation();
ev.preventDefault(); ev.preventDefault();
@@ -32,20 +29,16 @@ modulejs.define('ext/contextmenu', ['_', '$', 'core/resource', 'core/settings'],
} }
function createPanel(menu) { function createPanel(menu) {
var $panel = $(templatePanel); var $panel = $(templatePanel);
var $ul = $panel.find('ul'); var $ul = $panel.find('ul');
var $li; var $li;
_.each(menu, function (entry) { _.each(menu, function (entry) {
if (entry.type === '-') { if (entry.type === '-') {
$(templateSep).appendTo($ul); $(templateSep).appendTo($ul);
} else if (entry.type === 'l') { } else if (entry.type === 'l') {
$(templateLabel).appendTo($ul) $(templateLabel).appendTo($ul)
.find('.cm-text').text(entry.text); .find('.cm-text').text(entry.text);
} else if (entry.type === 'e') { } else if (entry.type === 'e') {
$li = $(templateEntry).appendTo($ul); $li = $(templateEntry).appendTo($ul);
$li.data('cm-id', entry.id); $li.data('cm-id', entry.id);
@@ -62,7 +55,6 @@ modulejs.define('ext/contextmenu', ['_', '$', 'core/resource', 'core/settings'],
} }
function positionPanel($overlay, $panel, x, y) { function positionPanel($overlay, $panel, x, y) {
var margin = 4; var margin = 4;
$panel.css({ $panel.css({
@@ -123,7 +115,6 @@ modulejs.define('ext/contextmenu', ['_', '$', 'core/resource', 'core/settings'],
} }
function showMenuAt(x, y, menu, callback) { function showMenuAt(x, y, menu, callback) {
var $overlay = createOverlay(callback); var $overlay = createOverlay(callback);
var $panel = createPanel(menu); var $panel = createPanel(menu);
$overlay.append($panel).appendTo('body'); $overlay.append($panel).appendTo('body');
@@ -131,20 +122,17 @@ modulejs.define('ext/contextmenu', ['_', '$', 'core/resource', 'core/settings'],
} }
function init() { function init() {
// settings.enabled = true; // settings.enabled = true;
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
$(document).on('contextmenu', function (ev) { $(document).on('contextmenu', function (ev) {
ev.stopPropagation(); ev.stopPropagation();
ev.preventDefault(); ev.preventDefault();
$(ev.target).trigger($.Event('h5ai-contextmenu', { $(ev.target).trigger($.Event('h5ai-contextmenu', {
originalEvent: ev, originalEvent: ev,
showMenu: function (menu, callback) { showMenu: function (menu, callback) {
showMenuAt(ev.pageX, ev.pageY, menu, callback); showMenuAt(ev.pageX, ev.pageY, menu, callback);
} }
})); }));

View File

@@ -1,8 +1,7 @@
modulejs.define('ext/crumb', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/settings', 'view/topbar'], function (_, $, event, location, resource, allsettings, topbar) { modulejs.define('ext/crumb', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/settings', 'view/topbar'], function (_, $, event, location, resource, allsettings, topbar) {
var settings = _.extend({ var settings = _.extend({
enabled: false enabled: false
}, allsettings.crumb); }, allsettings.crumb);
var crumbTemplate = var crumbTemplate =
'<a class="crumb">' + '<a class="crumb">' +
'<img class="sep" src="' + resource.image('crumb') + '" alt=">"/>' + '<img class="sep" src="' + resource.image('crumb') + '" alt=">"/>' +
@@ -13,7 +12,6 @@ modulejs.define('ext/crumb', ['_', '$', 'core/event', 'core/location', 'core/res
function createHtml(item) { function createHtml(item) {
var $html = $(crumbTemplate).data('item', item); var $html = $(crumbTemplate).data('item', item);
item.$crumb = $html; item.$crumb = $html;
location.setLink($html, item); location.setLink($html, item);
@@ -32,7 +30,6 @@ modulejs.define('ext/crumb', ['_', '$', 'core/event', 'core/location', 'core/res
} }
function onLocationChanged(item) { function onLocationChanged(item) {
var $crumb = item.$crumb; var $crumb = item.$crumb;
if ($crumb && $crumb.parent()[0] === $crumbbar[0]) { if ($crumb && $crumb.parent()[0] === $crumbbar[0]) {
@@ -40,14 +37,13 @@ modulejs.define('ext/crumb', ['_', '$', 'core/event', 'core/location', 'core/res
$crumb.addClass('active'); $crumb.addClass('active');
} else { } else {
$crumbbar.empty(); $crumbbar.empty();
_.each(item.getCrumb(), function (item) { _.each(item.getCrumb(), function (crumbItem) {
$crumbbar.append(createHtml(item)); $crumbbar.append(createHtml(crumbItem));
}); });
} }
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,17 +1,14 @@
modulejs.define('ext/custom', ['_', '$', 'marked', 'core/event', 'core/server', 'core/settings'], function (_, $, marked, event, server, allsettings) { modulejs.define('ext/custom', ['_', '$', 'marked', 'core/event', 'core/server', 'core/settings'], function (_, $, marked, event, server, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false enabled: false
}, allsettings.custom); }, allsettings.custom);
var $header; var $header;
var $footer; var $footer;
var duration = 200; var duration = 200;
function onLocationChanged(item) { function onLocationChanged(item) {
server.request({action: 'get', custom: item.absHref}, function (response) { server.request({action: 'get', custom: item.absHref}, function (response) {
var custom = response && response.custom; var custom = response && response.custom;
var hasHeader; var hasHeader;
var hasFooter; var hasFooter;
@@ -50,7 +47,6 @@ modulejs.define('ext/custom', ['_', '$', 'marked', 'core/event', 'core/server',
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,11 +1,10 @@
modulejs.define('ext/download', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/server', 'core/settings'], function (_, $, event, location, resource, server, allsettings) { modulejs.define('ext/download', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/server', 'core/settings'], function (_, $, event, location, resource, server, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
type: 'php-tar', type: 'php-tar',
packageName: 'package', packageName: 'package',
alwaysVisible: false alwaysVisible: false
}, allsettings.download); }, allsettings.download);
var template = var template =
'<div id="download" class="tool">' + '<div id="download" class="tool">' +
'<img src="' + resource.image('download') + '" alt="download"/>' + '<img src="' + resource.image('download') + '" alt="download"/>' +
@@ -15,7 +14,6 @@ modulejs.define('ext/download', ['_', '$', 'core/event', 'core/location', 'core/
function onSelection(items) { function onSelection(items) {
selectedItems = items.slice(0); selectedItems = items.slice(0);
if (selectedItems.length) { if (selectedItems.length) {
$download.show(); $download.show();
@@ -25,10 +23,9 @@ modulejs.define('ext/download', ['_', '$', 'core/event', 'core/location', 'core/
} }
function onClick() { function onClick() {
var type = settings.type; var type = settings.type;
var name = settings.packageName; var name = settings.packageName;
var extension = (type === 'shell-zip') ? 'zip' : 'tar'; var extension = type === 'shell-zip' ? 'zip' : 'tar';
if (!name) { if (!name) {
if (selectedItems.length === 1) { if (selectedItems.length === 1) {
@@ -39,14 +36,13 @@ modulejs.define('ext/download', ['_', '$', 'core/event', 'core/location', 'core/
} }
var query = { var query = {
action: 'download', action: 'download',
as: name + '.' + extension, as: name + '.' + extension,
type: type, type: type,
baseHref: location.getAbsHref() baseHref: location.getAbsHref()
}; };
_.each(selectedItems, function (item, idx) { _.each(selectedItems, function (item, idx) {
query['hrefs[' + idx + ']'] = item.absHref; query['hrefs[' + idx + ']'] = item.absHref;
}); });
@@ -54,7 +50,6 @@ modulejs.define('ext/download', ['_', '$', 'core/event', 'core/location', 'core/
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,10 +1,9 @@
modulejs.define('ext/filter', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/settings', 'core/util', 'view/view'], function (_, $, event, location, resource, allsettings, util, view) { modulejs.define('ext/filter', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/settings', 'core/util', 'view/view'], function (_, $, event, location, resource, allsettings, util, view) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
advanced: false, advanced: false,
debounceTime: 100 debounceTime: 100
}, allsettings.filter); }, allsettings.filter);
var template = var template =
'<div id="filter" class="tool">' + '<div id="filter" class="tool">' +
'<img src="' + resource.image('filter') + '" alt="filter"/>' + '<img src="' + resource.image('filter') + '" alt="filter"/>' +
@@ -17,7 +16,6 @@ modulejs.define('ext/filter', ['_', '$', 'core/event', 'core/location', 'core/re
function filter(pattern) { function filter(pattern) {
pattern = pattern || ''; pattern = pattern || '';
if (pattern === prevPattern) { if (pattern === prevPattern) {
return; return;
@@ -35,7 +33,6 @@ modulejs.define('ext/filter', ['_', '$', 'core/event', 'core/location', 'core/re
var matchedItems = []; var matchedItems = [];
_.each(location.getItem().content, function (item) { _.each(location.getItem().content, function (item) {
if (re.test(item.label)) { if (re.test(item.label)) {
matchedItems.push(item); matchedItems.push(item);
} }
@@ -47,7 +44,6 @@ modulejs.define('ext/filter', ['_', '$', 'core/event', 'core/location', 'core/re
} }
function update() { function update() {
if (inputIsVisible) { if (inputIsVisible) {
$filter.addClass('active'); $filter.addClass('active');
$input.focus(); $input.focus();
@@ -59,20 +55,17 @@ modulejs.define('ext/filter', ['_', '$', 'core/event', 'core/location', 'core/re
} }
function toggle() { function toggle() {
inputIsVisible = !inputIsVisible; inputIsVisible = !inputIsVisible;
update(); update();
} }
function reset() { function reset() {
inputIsVisible = false; inputIsVisible = false;
$input.val(''); $input.val('');
update(); update();
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,49 +1,37 @@
modulejs.define('ext/google-analytics-ua', ['_', 'core/event', 'core/settings'], function (_, event, allsettings) { modulejs.define('ext/google-analytics-ua', ['_', 'core/event', 'core/settings'], function (_, event, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
id: 'UA-000000-0' id: 'UA-000000-0'
}, allsettings['google-analytics-ua']); }, allsettings['google-analytics-ua']);
var win = window;
var doc = document;
var scriptLiteral = 'script';
var id = 'h5ai-ga';
function snippet() {
/* eslint-disable */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
/* eslint-enable */
}
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
var el; snippet();
var firstScriptElement;
win.GoogleAnalyticsObject = id; var WIN = window;
win[id] = win[id] || function () { var GA = 'ga';
(win[id].q = win[id].q || []).push(arguments); WIN[GA]('create', settings.id, 'auto');
};
win[id].l = 1 * new Date();
el = doc.createElement(scriptLiteral);
el.async = true;
el.src = '//www.google-analytics.com/analytics.js';
firstScriptElement = doc.getElementsByTagName(scriptLiteral)[0];
firstScriptElement.parentNode.insertBefore(el, firstScriptElement);
win[id]('create', settings.id, 'auto');
event.sub('location.changed', function (item) { event.sub('location.changed', function (item) {
var loc = WIN.location;
var loc = win.location; WIN[GA]('send', 'pageview', {
win[id]('send', 'pageview', {
location: loc.protocol + '//' + loc.host + item.absHref, location: loc.protocol + '//' + loc.host + item.absHref,
title: _.pluck(item.getCrumb(), 'label').join(' > ') title: _.pluck(item.getCrumb(), 'label').join(' > ')
}); });
}); });
} }
init(); init();
}); });

View File

@@ -1,11 +1,10 @@
modulejs.define('ext/info', ['_', '$', 'core/event', 'core/format', 'core/modernizr', 'core/resource', 'core/settings', 'core/store'], function (_, $, event, format, modernizr, resource, allsettings, store) { modulejs.define('ext/info', ['_', '$', 'core/event', 'core/format', 'core/modernizr', 'core/resource', 'core/settings', 'core/store'], function (_, $, event, format, modernizr, resource, allsettings, store) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
show: false, show: false,
qrcode: true, qrcode: true,
qrColor: '#999' qrColor: '#999'
}, allsettings.info); }, allsettings.info);
var template = var template =
'<div id="info">' + '<div id="info">' +
'<div class="icon"><img/></div>' + '<div class="icon"><img/></div>' +
@@ -40,7 +39,6 @@ modulejs.define('ext/info', ['_', '$', 'core/event', 'core/format', 'core/modern
function updateSettings() { function updateSettings() {
if (store.get(storekey)) { if (store.get(storekey)) {
$('#view-info').addClass('active'); $('#view-info').addClass('active');
$('#info').show(); $('#info').show();
@@ -51,7 +49,6 @@ modulejs.define('ext/info', ['_', '$', 'core/event', 'core/format', 'core/modern
} }
function update(item) { function update(item) {
var src = item.thumbRational || item.icon; var src = item.thumbRational || item.icon;
var isThumb = Boolean(item.thumbRational); var isThumb = Boolean(item.thumbRational);
@@ -101,23 +98,19 @@ modulejs.define('ext/info', ['_', '$', 'core/event', 'core/format', 'core/modern
} }
function onMouseenter(item) { function onMouseenter(item) {
update(item); update(item);
} }
function onMouseleave() { function onMouseleave() {
update(currentFolder); update(currentFolder);
} }
function onLocationChanged(item) { function onLocationChanged(item) {
currentFolder = item; currentFolder = item;
update(currentFolder); update(currentFolder);
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
@@ -140,14 +133,13 @@ modulejs.define('ext/info', ['_', '$', 'core/event', 'core/format', 'core/modern
.appendTo('#sidebar') .appendTo('#sidebar')
.find('#view-info') .find('#view-info')
.on('click', function (ev) { .on('click', function (ev) {
store.put(storekey, !store.get(storekey)); store.put(storekey, !store.get(storekey));
updateSettings(); updateSettings();
ev.preventDefault(); ev.preventDefault();
}); });
// ensure stored value is boolean, otherwise set default // ensure stored value is boolean, otherwise set default
if (typeof (store.get(storekey)) !== 'boolean') { if (typeof store.get(storekey) !== 'boolean') {
store.put(storekey, settings.show); store.put(storekey, settings.show);
} }
updateSettings(); updateSettings();

View File

@@ -1,44 +1,43 @@
modulejs.define('ext/l10n', ['_', '$', 'core/event', 'core/format', 'core/langs', 'core/server', 'core/settings', 'core/store'], function (_, $, event, format, langs, server, allsettings, store) { modulejs.define('ext/l10n', ['_', '$', 'core/event', 'core/format', 'core/langs', 'core/server', 'core/settings', 'core/store'],
function (_, $, event, format, langs, server, allsettings, store) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
lang: 'en', lang: 'en',
useBrowserLang: true useBrowserLang: true
}, allsettings.l10n); }, allsettings.l10n);
var defaultTranslations = { var defaultTranslations = {
isoCode: 'en', isoCode: 'en',
lang: 'english', lang: 'english',
dateFormat: 'YYYY-MM-DD HH:mm', dateFormat: 'YYYY-MM-DD HH:mm',
details: 'details', details: 'details',
download: 'download', download: 'download',
empty: 'empty', empty: 'empty',
files: 'files', files: 'files',
filter: 'filter', filter: 'filter',
folders: 'folders', folders: 'folders',
grid: 'grid', grid: 'grid',
icons: 'icons', icons: 'icons',
language: 'Language', language: 'Language',
lastModified: 'Last modified', lastModified: 'Last modified',
name: 'Name', name: 'Name',
noMatch: 'no match', noMatch: 'no match',
parentDirectory: 'Parent Directory', parentDirectory: 'Parent Directory',
search: 'search', search: 'search',
size: 'Size', size: 'Size',
tree: 'Tree', tree: 'Tree',
view: 'View' view: 'View'
}; };
var blockTemplate = '<div class="block"><h1 class="l10n-language">Language</h1><div class="select"><select id="langs"/></div></div>'; var blockTemplate = '<div class="block"><h1 class="l10n-language">Language</h1><div class="select"><select id="langs"/></div></div>';
var optionTemplate = '<option/>'; var optionTemplate = '<option/>';
var storekey = 'ext/l10n'; var storekey = 'ext/l10n';
var loaded = { var loaded = {
en: _.extend({}, defaultTranslations) en: _.extend({}, defaultTranslations)
}; };
var currentLang = loaded.en; var currentLang = loaded.en;
function update(lang) { function update(lang) {
if (lang) { if (lang) {
currentLang = lang; currentLang = lang;
} }
@@ -55,7 +54,6 @@ modulejs.define('ext/l10n', ['_', '$', 'core/event', 'core/format', 'core/langs'
format.setDefaultDateFormat(currentLang.dateFormat); format.setDefaultDateFormat(currentLang.dateFormat);
$('#items .item .date').each(function () { $('#items .item .date').each(function () {
var $this = $(this); var $this = $(this);
$this.text(format.formatDate($this.data('time'))); $this.text(format.formatDate($this.data('time')));
@@ -63,14 +61,10 @@ modulejs.define('ext/l10n', ['_', '$', 'core/event', 'core/format', 'core/langs'
} }
function loadLanguage(isoCode, callback) { function loadLanguage(isoCode, callback) {
if (loaded[isoCode]) { if (loaded[isoCode]) {
callback(loaded[isoCode]); callback(loaded[isoCode]);
} else { } else {
server.request({action: 'get', l10n: [isoCode]}, function (response) { server.request({action: 'get', l10n: [isoCode]}, function (response) {
var json = response.l10n && response.l10n[isoCode] ? response.l10n[isoCode] : {}; var json = response.l10n && response.l10n[isoCode] ? response.l10n[isoCode] : {};
loaded[isoCode] = _.extend({}, defaultTranslations, json, {isoCode: isoCode}); loaded[isoCode] = _.extend({}, defaultTranslations, json, {isoCode: isoCode});
callback(loaded[isoCode]); callback(loaded[isoCode]);
@@ -78,46 +72,44 @@ modulejs.define('ext/l10n', ['_', '$', 'core/event', 'core/format', 'core/langs'
} }
} }
function localize(langs, isoCode, useBrowserLang) { function localize(languages, isoCode, useBrowserLang) {
var storedIsoCode = store.get(storekey); var storedIsoCode = store.get(storekey);
if (langs[storedIsoCode]) { if (languages[storedIsoCode]) {
isoCode = storedIsoCode; isoCode = storedIsoCode;
} else if (useBrowserLang) { } else if (useBrowserLang) {
var browserLang = navigator.language || navigator.browserLanguage; var browserLang = navigator.language || navigator.browserLanguage;
if (browserLang) { if (browserLang) {
if (langs[browserLang]) { if (languages[browserLang]) {
isoCode = browserLang; isoCode = browserLang;
} else if (browserLang.length > 2 && langs[browserLang.substr(0, 2)]) { } else if (browserLang.length > 2 && languages[browserLang.substr(0, 2)]) {
isoCode = browserLang.substr(0, 2); isoCode = browserLang.substr(0, 2);
} }
} }
} }
if (!langs[isoCode]) { if (!languages[isoCode]) {
isoCode = 'en'; isoCode = 'en';
} }
loadLanguage(isoCode, update); loadLanguage(isoCode, update);
} }
function initLangSelector(langs) { function initLangSelector(languages) {
var isoCodes = _.keys(languages).sort();
var isoCodes = _.keys(langs).sort();
var $block = $(blockTemplate); var $block = $(blockTemplate);
var $select = $block.find('select') var $select = $block.find('select')
.on('change', function (event) { .on('change', function (ev) {
var isoCode = event.target.value; var isoCode = ev.target.value;
store.put(storekey, isoCode); store.put(storekey, isoCode);
localize(langs, isoCode, false); localize(languages, isoCode, false);
}); });
$.each(isoCodes, function (idx, isoCode) { $.each(isoCodes, function (idx, isoCode) {
$(optionTemplate) $(optionTemplate)
.attr('value', isoCode) .attr('value', isoCode)
.addClass(isoCode) .addClass(isoCode)
.text(isoCode + ' - ' + (_.isString(langs[isoCode]) ? langs[isoCode] : langs[isoCode].lang)) .text(isoCode + ' - ' + (_.isString(languages[isoCode]) ? languages[isoCode] : languages[isoCode].lang))
.appendTo($select); .appendTo($select);
}); });
@@ -125,13 +117,11 @@ modulejs.define('ext/l10n', ['_', '$', 'core/event', 'core/format', 'core/langs'
} }
function init() { function init() {
if (settings.enabled) { if (settings.enabled) {
initLangSelector(langs); initLangSelector(langs);
} }
event.sub('view.changed', function () { event.sub('view.changed', function () {
localize(langs, settings.lang, settings.useBrowserLang); localize(langs, settings.lang, settings.useBrowserLang);
}); });
} }

View File

@@ -1,13 +1,11 @@
modulejs.define('ext/peer5', ['_', '$', 'core/settings'], function (_, $, allsettings) { modulejs.define('ext/peer5', ['_', '$', 'core/settings'], function (_, $, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
id: 'z142i5n5qypq4cxr' id: 'z142i5n5qypq4cxr'
}, allsettings.peer5); }, allsettings.peer5);
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
@@ -23,9 +21,7 @@ modulejs.define('ext/peer5', ['_', '$', 'core/settings'], function (_, $, allset
// attach to file items, once the DOM is ready // attach to file items, once the DOM is ready
$(function () { $(function () {
$('body').on('click', '.item.file > a', function (ev) { $('body').on('click', '.item.file > a', function (ev) {
if (window.peer5) { if (window.peer5) {
ev.preventDefault(); ev.preventDefault();
var url = ev.currentTarget.href; var url = ev.currentTarget.href;

View File

@@ -1,25 +1,23 @@
modulejs.define('ext/piwik-analytics', ['_', '$', 'core/settings'], function (_, $, allsettings) { modulejs.define('ext/piwik-analytics', ['_', '$', 'core/settings'], function (_, $, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
baseURL: 'not-set', baseURL: 'not-set',
idSite: 0 idSite: 0
}, allsettings['piwik-analytics']); }, allsettings['piwik-analytics']);
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
// reference: http://piwik.org/docs/javascript-tracking/ // reference: http://piwik.org/docs/javascript-tracking/
var pkBaseURL = ((document.location.protocol === 'https:') ? 'https://' : 'http://') + settings.baseURL + '/'; var pkBaseURL = (document.location.protocol === 'https:' ? 'https://' : 'http://') + settings.baseURL + '/';
$('<script/>').attr('src', pkBaseURL + 'piwik.js').appendTo('body'); $('<script/>').attr('src', pkBaseURL + 'piwik.js').appendTo('body');
$(window).load(function () { $(window).load(function () {
/*global Piwik */ /* global Piwik */
var piwikTracker = Piwik.getTracker(pkBaseURL + 'piwik.php', settings.idSite); var piwikTracker = Piwik.getTracker(pkBaseURL + 'piwik.php', settings.idSite);
piwikTracker.trackPageView(); piwikTracker.trackPageView();

View File

@@ -1,37 +1,30 @@
modulejs.define('ext/preview-audio', ['_', '$', 'core/event', 'core/format', 'core/settings', 'ext/preview'], function (_, $, event, format, allsettings, preview) { modulejs.define('ext/preview-audio', ['_', '$', 'core/event', 'core/format', 'core/settings', 'ext/preview'], function (_, $, event, format, allsettings, preview) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
types: [] types: []
}, allsettings['preview-aud']); }, allsettings['preview-aud']);
function preloadAudio(src, callback) { function preloadAudio(src, callback) {
var $audio = $('<audio/>') var $audio = $('<audio/>')
.one('loadedmetadata', function () { .one('loadedmetadata', function () {
callback($audio);
callback($audio); // setTimeout(function () { callback($img); }, 1000); // for testing
// setTimeout(function () { callback($img); }, 1000); // for testing })
}) .attr('autoplay', 'autoplay')
.attr('autoplay', 'autoplay') .attr('controls', 'controls')
.attr('controls', 'controls') .attr('src', src);
.attr('src', src);
} }
function onEnter(items, idx) { function onEnter(items, idx) {
var currentItems = items; var currentItems = items;
var currentIdx = idx; var currentIdx = idx;
var currentItem = items[idx]; var currentItem = items[idx];
function onAdjustSize() { function onAdjustSize() {
var $content = $('#pv-content'); var $content = $('#pv-content');
var $audio = $('#pv-aud-audio'); var $audio = $('#pv-aud-audio');
if ($audio.length) { if ($audio.length) {
$audio.css({ $audio.css({
left: String(($content.width() - $audio.width()) * 0.5) + 'px', left: String(($content.width() - $audio.width()) * 0.5) + 'px',
top: String(($content.height() - $audio.height()) * 0.5) + 'px' top: String(($content.height() - $audio.height()) * 0.5) + 'px'
@@ -45,7 +38,6 @@ modulejs.define('ext/preview-audio', ['_', '$', 'core/event', 'core/format', 'co
} }
function onIdxChange(rel) { function onIdxChange(rel) {
currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length; currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length;
currentItem = currentItems[currentIdx]; currentItem = currentItems[currentIdx];
@@ -54,24 +46,29 @@ modulejs.define('ext/preview-audio', ['_', '$', 'core/event', 'core/format', 'co
if ($('#pv-aud-audio').length) { if ($('#pv-aud-audio').length) {
$('#pv-aud-audio')[0].pause(); $('#pv-aud-audio')[0].pause();
} }
preloadAudio(currentItem.absHref, function ($preloadedAudio) {
function updateMeta() {
onAdjustSize();
preview.setIndex(currentIdx + 1, currentItems.length);
preview.setRawLink(currentItem.absHref);
}
function swap(nuContent) {
$('#pv-content').empty().append(nuContent.attr('id', 'pv-vid-audio')).fadeIn(200);
// small timeout, so nuContent is visible and therefore its width is available
setTimeout(updateMeta, 10);
}
function onReady($preloadedContent) {
clearTimeout(spinnerTimeout); clearTimeout(spinnerTimeout);
preview.showSpinner(false); preview.showSpinner(false);
$('#pv-content').fadeOut(100, function () { $('#pv-content').fadeOut(100, function () {
swap($preloadedContent);
$('#pv-content').empty().append($preloadedAudio.attr('id', 'pv-aud-audio')).fadeIn(200);
// small timeout, so $preloadedAudio is visible and therefore $preloadedAudio.width is available
setTimeout(function () {
onAdjustSize();
preview.setIndex(currentIdx + 1, currentItems.length);
preview.setRawLink(currentItem.absHref);
}, 10);
}); });
}); }
preloadAudio(currentItem.absHref, onReady);
} }
onIdxChange(0); onIdxChange(0);
@@ -81,30 +78,25 @@ modulejs.define('ext/preview-audio', ['_', '$', 'core/event', 'core/format', 'co
} }
function initItem(item) { function initItem(item) {
if (item.$view && _.indexOf(settings.types, item.type) >= 0) { if (item.$view && _.indexOf(settings.types, item.type) >= 0) {
item.$view.find('a').on('click', function (event) { item.$view.find('a').on('click', function (ev) {
ev.preventDefault();
event.preventDefault(); var matchedItems = _.compact(_.map($('#items .item'), function (matchedItem) {
matchedItem = $(matchedItem).data('item');
var matchedEntries = _.compact(_.map($('#items .item'), function (item) { return _.indexOf(settings.types, matchedItem.type) >= 0 ? matchedItem : null;
item = $(item).data('item');
return _.indexOf(settings.types, item.type) >= 0 ? item : null;
})); }));
onEnter(matchedEntries, _.indexOf(matchedEntries, item)); onEnter(matchedItems, _.indexOf(matchedItems, item));
}); });
} }
} }
function onViewChanged(added) { function onViewChanged(added) {
_.each(added, initItem); _.each(added, initItem);
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
@@ -112,6 +104,5 @@ modulejs.define('ext/preview-audio', ['_', '$', 'core/event', 'core/format', 'co
event.sub('view.changed', onViewChanged); event.sub('view.changed', onViewChanged);
} }
init(); init();
}); });

View File

@@ -1,10 +1,9 @@
modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core/settings', 'ext/preview'], function (_, $, event, server, allsettings, preview) { modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core/settings', 'ext/preview'], function (_, $, event, server, allsettings, preview) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
size: null, size: null,
types: [] types: []
}, allsettings['preview-img']); }, allsettings['preview-img']);
var spinnerThreshold = 200; var spinnerThreshold = 200;
var spinnerTimeoutId; var spinnerTimeoutId;
var currentItems; var currentItems;
@@ -13,7 +12,6 @@ modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core
function requestSample(href, callback) { function requestSample(href, callback) {
if (!settings.size) { if (!settings.size) {
callback(href); callback(href);
return; return;
@@ -28,18 +26,14 @@ modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core
height: 0 height: 0
}] }]
}, function (json) { }, function (json) {
callback(json && json.thumbs && json.thumbs[0] ? json.thumbs[0] : null); callback(json && json.thumbs && json.thumbs[0] ? json.thumbs[0] : null);
}); });
} }
function preloadImage(item, callback) { function preloadImage(item, callback) {
requestSample(item.absHref, function (src) { requestSample(item.absHref, function (src) {
$('<img/>') $('<img/>')
.one('load', function (ev) { .one('load', function (ev) {
callback(item, ev.target); callback(item, ev.target);
// for testing // for testing
@@ -50,7 +44,6 @@ modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core
} }
function onAdjustSize() { function onAdjustSize() {
var $content = $('#pv-content'); var $content = $('#pv-content');
var $img = $('#pv-img-image'); var $img = $('#pv-img-image');
@@ -72,7 +65,6 @@ modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core
} }
function onIdxChange(rel) { function onIdxChange(rel) {
currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length; currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length;
currentItem = currentItems[currentIdx]; currentItem = currentItems[currentIdx];
@@ -86,13 +78,11 @@ modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core
} else { } else {
clearTimeout(spinnerTimeoutId); clearTimeout(spinnerTimeoutId);
spinnerTimeoutId = setTimeout(function () { spinnerTimeoutId = setTimeout(function () {
preview.showSpinner(true, currentItem.thumbSquare); preview.showSpinner(true, currentItem.thumbSquare);
}, spinnerThreshold); }, spinnerThreshold);
} }
preloadImage(currentItem, function (item, preloadedImage) { preloadImage(currentItem, function (item, preloadedImage) {
if (item !== currentItem) { if (item !== currentItem) {
return; return;
} }
@@ -108,7 +98,6 @@ modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core
} }
function onEnter(items, idx) { function onEnter(items, idx) {
currentItems = items; currentItems = items;
currentIdx = idx; currentIdx = idx;
preview.setOnIndexChange(onIdxChange); preview.setOnIndexChange(onIdxChange);
@@ -118,30 +107,25 @@ modulejs.define('ext/preview-img', ['_', '$', 'core/event', 'core/server', 'core
} }
function initItem(item) { function initItem(item) {
if (item.$view && _.indexOf(settings.types, item.type) >= 0) { if (item.$view && _.indexOf(settings.types, item.type) >= 0) {
item.$view.find('a').on('click', function (ev) { item.$view.find('a').on('click', function (ev) {
ev.preventDefault(); ev.preventDefault();
var matchedEntries = _.compact(_.map($('#items .item'), function (item) { var matchedItems = _.compact(_.map($('#items .item'), function (matchedItem) {
matchedItem = $(matchedItem).data('item');
item = $(item).data('item'); return _.indexOf(settings.types, matchedItem.type) >= 0 ? matchedItem : null;
return _.indexOf(settings.types, item.type) >= 0 ? item : null;
})); }));
onEnter(matchedEntries, _.indexOf(matchedEntries, item)); onEnter(matchedItems, _.indexOf(matchedItems, item));
}); });
} }
} }
function onViewChanged(added) { function onViewChanged(added) {
_.each(added, initItem); _.each(added, initItem);
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,9 +1,8 @@
modulejs.define('ext/preview-txt', ['_', '$', 'marked', 'prism', 'core/event', 'core/settings', 'ext/preview'], function (_, $, marked, prism, event, allsettings, preview) { modulejs.define('ext/preview-txt', ['_', '$', 'marked', 'prism', 'core/event', 'core/settings', 'ext/preview'], function (_, $, marked, prism, event, allsettings, preview) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
types: {} types: {}
}, allsettings['preview-txt']); }, allsettings['preview-txt']);
var tplText = '<pre id="pv-txt-text" class="highlighted"/>'; var tplText = '<pre id="pv-txt-text" class="highlighted"/>';
var tplMarkdown = '<div id="pv-txt-text" class="markdown"/>'; var tplMarkdown = '<div id="pv-txt-text" class="markdown"/>';
var spinnerThreshold = 200; var spinnerThreshold = 200;
@@ -14,26 +13,22 @@ modulejs.define('ext/preview-txt', ['_', '$', 'marked', 'prism', 'core/event', '
function preloadText(item, callback) { function preloadText(item, callback) {
$.ajax({ $.ajax({
url: item.absHref, url: item.absHref,
dataType: 'text' dataType: 'text'
}) })
.done(function (content) { .done(function (content) {
callback(item, content);
callback(item, content); // for testing
// setTimeout(function () { callback(item, content); }, 1000);
// for testing })
// setTimeout(function () { callback(item, content); }, 1000); .fail(function (jqXHR, textStatus) {
}) callback(item, '[ajax error] ' + textStatus);
.fail(function (jqXHR, textStatus) { });
callback(item, '[ajax error] ' + textStatus);
});
} }
function onAdjustSize() { function onAdjustSize() {
var $content = $('#pv-content'); var $content = $('#pv-content');
var $text = $('#pv-txt-text'); var $text = $('#pv-txt-text');
@@ -43,7 +38,6 @@ modulejs.define('ext/preview-txt', ['_', '$', 'marked', 'prism', 'core/event', '
} }
function onIdxChange(rel) { function onIdxChange(rel) {
currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length; currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length;
currentItem = currentItems[currentIdx]; currentItem = currentItems[currentIdx];
@@ -60,13 +54,11 @@ modulejs.define('ext/preview-txt', ['_', '$', 'marked', 'prism', 'core/event', '
} else { } else {
clearTimeout(spinnerTimeoutId); clearTimeout(spinnerTimeoutId);
spinnerTimeoutId = setTimeout(function () { spinnerTimeoutId = setTimeout(function () {
preview.showSpinner(true, currentItem.icon); preview.showSpinner(true, currentItem.icon);
}, spinnerThreshold); }, spinnerThreshold);
} }
preloadText(currentItem, function (item, textContent) { preloadText(currentItem, function (item, textContent) {
if (item !== currentItem) { if (item !== currentItem) {
return; return;
} }
@@ -104,7 +96,6 @@ modulejs.define('ext/preview-txt', ['_', '$', 'marked', 'prism', 'core/event', '
} }
function onEnter(items, idx) { function onEnter(items, idx) {
currentItems = items; currentItems = items;
currentIdx = idx; currentIdx = idx;
currentItem = items[idx]; currentItem = items[idx];
@@ -115,30 +106,25 @@ modulejs.define('ext/preview-txt', ['_', '$', 'marked', 'prism', 'core/event', '
} }
function initItem(item) { function initItem(item) {
if (item.$view && _.indexOf(_.keys(settings.types), item.type) >= 0) { if (item.$view && _.indexOf(_.keys(settings.types), item.type) >= 0) {
item.$view.find('a').on('click', function (event) { item.$view.find('a').on('click', function (ev) {
ev.preventDefault();
event.preventDefault(); var matchedItems = _.compact(_.map($('#items .item'), function (matchedItem) {
matchedItem = $(matchedItem).data('item');
var matchedEntries = _.compact(_.map($('#items .item'), function (item) { return _.indexOf(_.keys(settings.types), matchedItem.type) >= 0 ? matchedItem : null;
item = $(item).data('item');
return _.indexOf(_.keys(settings.types), item.type) >= 0 ? item : null;
})); }));
onEnter(matchedEntries, _.indexOf(matchedEntries, item)); onEnter(matchedItems, _.indexOf(matchedItems, item));
}); });
} }
} }
function onViewChanged(added) { function onViewChanged(added) {
_.each(added, initItem); _.each(added, initItem);
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,37 +1,30 @@
modulejs.define('ext/preview-vid', ['_', '$', 'core/event', 'core/settings', 'ext/preview'], function (_, $, event, allsettings, preview) { modulejs.define('ext/preview-vid', ['_', '$', 'core/event', 'core/settings', 'ext/preview'], function (_, $, event, allsettings, preview) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
types: [] types: []
}, allsettings['preview-vid']); }, allsettings['preview-vid']);
function preloadVideo(src, callback) { function preloadVideo(src, callback) {
var $video = $('<video/>') var $video = $('<video/>')
.one('loadedmetadata', function () { .one('loadedmetadata', function () {
callback($video);
callback($video); // setTimeout(function () { callback($video); }, 1000); // for testing
// setTimeout(function () { callback($video); }, 1000); // for testing })
}) .attr('autoplay', 'autoplay')
.attr('autoplay', 'autoplay') .attr('controls', 'controls')
.attr('controls', 'controls') .attr('src', src);
.attr('src', src);
} }
function onEnter(items, idx) { function onEnter(items, idx) {
var currentItems = items; var currentItems = items;
var currentIdx = idx; var currentIdx = idx;
var currentItem = items[idx]; var currentItem = items[idx];
function onAdjustSize() { function onAdjustSize() {
var $content = $('#pv-content'); var $content = $('#pv-content');
var $vid = $('#pv-vid-video'); var $vid = $('#pv-vid-video');
if ($vid.length) { if ($vid.length) {
$vid.css({ $vid.css({
left: String(($content.width() - $vid.width()) * 0.5) + 'px', left: String(($content.width() - $vid.width()) * 0.5) + 'px',
top: String(($content.height() - $vid.height()) * 0.5) + 'px' top: String(($content.height() - $vid.height()) * 0.5) + 'px'
@@ -46,7 +39,6 @@ modulejs.define('ext/preview-vid', ['_', '$', 'core/event', 'core/settings', 'ex
} }
function onIdxChange(rel) { function onIdxChange(rel) {
currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length; currentIdx = (currentIdx + rel + currentItems.length) % currentItems.length;
currentItem = currentItems[currentIdx]; currentItem = currentItems[currentIdx];
@@ -55,24 +47,29 @@ modulejs.define('ext/preview-vid', ['_', '$', 'core/event', 'core/settings', 'ex
if ($('#pv-vid-video').length) { if ($('#pv-vid-video').length) {
$('#pv-vid-video')[0].pause(); $('#pv-vid-video')[0].pause();
} }
preloadVideo(currentItem.absHref, function ($preloadedVideo) {
function updateMeta() {
onAdjustSize();
preview.setIndex(currentIdx + 1, currentItems.length);
preview.setRawLink(currentItem.absHref);
}
function swap(nuContent) {
$('#pv-content').empty().append(nuContent.attr('id', 'pv-vid-video')).fadeIn(200);
// small timeout, so nuContent is visible and therefore its width is available
setTimeout(updateMeta, 10);
}
function onReady($preloadedContent) {
clearTimeout(spinnerTimeout); clearTimeout(spinnerTimeout);
preview.showSpinner(false); preview.showSpinner(false);
$('#pv-content').fadeOut(100, function () { $('#pv-content').fadeOut(100, function () {
swap($preloadedContent);
$('#pv-content').empty().append($preloadedVideo.attr('id', 'pv-vid-video')).fadeIn(200);
// small timeout, so $preloadedVideo is visible and therefore $preloadedVideo.width is available
setTimeout(function () {
onAdjustSize();
preview.setIndex(currentIdx + 1, currentItems.length);
preview.setRawLink(currentItem.absHref);
}, 10);
}); });
}); }
preloadVideo(currentItem.absHref, onReady);
} }
onIdxChange(0); onIdxChange(0);
@@ -82,30 +79,25 @@ modulejs.define('ext/preview-vid', ['_', '$', 'core/event', 'core/settings', 'ex
} }
function initItem(item) { function initItem(item) {
if (item.$view && _.indexOf(settings.types, item.type) >= 0) { if (item.$view && _.indexOf(settings.types, item.type) >= 0) {
item.$view.find('a').on('click', function (event) { item.$view.find('a').on('click', function (ev) {
ev.preventDefault();
event.preventDefault(); var matchedItems = _.compact(_.map($('#items .item'), function (matchedItem) {
matchedItem = $(matchedItem).data('item');
var matchedEntries = _.compact(_.map($('#items .item'), function (item) { return _.indexOf(settings.types, matchedItem.type) >= 0 ? matchedItem : null;
item = $(item).data('item');
return _.indexOf(settings.types, item.type) >= 0 ? item : null;
})); }));
onEnter(matchedEntries, _.indexOf(matchedEntries, item)); onEnter(matchedItems, _.indexOf(matchedItems, item));
}); });
} }
} }
function onViewChanged(added) { function onViewChanged(added) {
_.each(added, initItem); _.each(added, initItem);
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
@@ -113,6 +105,5 @@ modulejs.define('ext/preview-vid', ['_', '$', 'core/event', 'core/settings', 'ex
event.sub('view.changed', onViewChanged); event.sub('view.changed', onViewChanged);
} }
init(); init();
}); });

View File

@@ -1,8 +1,7 @@
modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'core/store'], function (_, $, resource, allsettings, store) { modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'core/store'], function (_, $, resource, allsettings, store) {
var settings = _.extend({ var settings = _.extend({
enabled: true enabled: true
}, allsettings.preview); }, allsettings.preview);
var $window = $(window); var $window = $(window);
var tplOverlay = var tplOverlay =
'<div id="pv-overlay">' + '<div id="pv-overlay">' +
@@ -30,7 +29,6 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
function adjustSize() { function adjustSize() {
var winWidth = $window.width(); var winWidth = $window.width();
var winHeight = $window.height(); var winHeight = $window.height();
var $container = $('#pv-content'); var $container = $('#pv-content');
@@ -63,53 +61,40 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
} }
} }
function onEnter() { function setLabels(labels) {
$('#pv-buttons .bar-left').remove();
setLabels([]); _.each(labels, function (label) {
$('#pv-content').empty(); $('<li/>')
$('#pv-overlay').stop(true, true).fadeIn(200); .addClass('bar-left bar-label')
$window.on('keydown', onKeydown); .text(label)
adjustSize(); .appendTo('#pv-buttons');
}
function onExit() {
$window.off('keydown', onKeydown);
$('#pv-overlay').stop(true, true).fadeOut(200, function () {
$('#pv-content').empty();
setLabels([]);
}); });
} }
function onNext() { function onNext() {
if (_.isFunction(onIndexChange)) { if (_.isFunction(onIndexChange)) {
onIndexChange(1); onIndexChange(1);
} }
} }
function onPrevious() { function onPrevious() {
if (_.isFunction(onIndexChange)) { if (_.isFunction(onIndexChange)) {
onIndexChange(-1); onIndexChange(-1);
} }
} }
function userAlive() { function userAlive() {
clearTimeout(userAliveTimeoutId); clearTimeout(userAliveTimeoutId);
$('#pv-overlay .hof').stop(true, true).fadeIn(200); $('#pv-overlay .hof').stop(true, true).fadeIn(200);
if (isFullscreen) { if (isFullscreen) {
userAliveTimeoutId = setTimeout(function () { userAliveTimeoutId = setTimeout(function () {
$('#pv-overlay .hof').stop(true, true).fadeOut(2000); $('#pv-overlay .hof').stop(true, true).fadeOut(2000);
}, 2000); }, 2000);
} }
} }
function onFullscreen() { function onFullscreen() {
isFullscreen = !isFullscreen; isFullscreen = !isFullscreen;
store.put(storekey, isFullscreen); store.put(storekey, isFullscreen);
@@ -118,7 +103,6 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
} }
function onKeydown(ev) { function onKeydown(ev) {
var key = ev.which; var key = ev.which;
if (key === 27) { // esc if (key === 27) { // esc
@@ -140,8 +124,23 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
} }
} }
function setIndex(idx, total) { function onEnter() {
setLabels([]);
$('#pv-content').empty();
$('#pv-overlay').stop(true, true).fadeIn(200);
$window.on('keydown', onKeydown);
adjustSize();
}
function onExit() {
$window.off('keydown', onKeydown);
$('#pv-overlay').stop(true, true).fadeOut(200, function () {
$('#pv-content').empty();
setLabels([]);
});
}
function setIndex(idx, total) {
if (_.isNumber(idx)) { if (_.isNumber(idx)) {
$('#pv-bar-idx').text(String(idx) + (_.isNumber(total) ? '/' + String(total) : '')).show(); $('#pv-bar-idx').text(String(idx) + (_.isNumber(total) ? '/' + String(total) : '')).show();
} else { } else {
@@ -150,7 +149,6 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
} }
function setRawLink(href) { function setRawLink(href) {
if (href) { if (href) {
$('#pv-bar-raw').show().find('a').attr('href', href); $('#pv-bar-raw').show().find('a').attr('href', href);
} else { } else {
@@ -158,30 +156,15 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
} }
} }
function setLabels(labels) {
$('#pv-buttons .bar-left').remove();
_.each(labels, function (label) {
$('<li/>')
.addClass('bar-left bar-label')
.text(label)
.appendTo('#pv-buttons');
});
}
function setOnIndexChange(fn) { function setOnIndexChange(fn) {
onIndexChange = fn; onIndexChange = fn;
} }
function setOnAdjustSize(fn) { function setOnAdjustSize(fn) {
onAdjustSize = fn; onAdjustSize = fn;
} }
function showSpinner(show, src, millis) { function showSpinner(show, src, millis) {
if (!_.isNumber(millis)) { if (!_.isNumber(millis)) {
millis = 300; millis = 300;
} }
@@ -204,12 +187,10 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
} }
function isSpinnerVisible() { function isSpinnerVisible() {
return spinnerVisible; return spinnerVisible;
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
@@ -226,7 +207,6 @@ modulejs.define('ext/preview', ['_', '$', 'core/resource', 'core/settings', 'cor
.on('keydown', onKeydown) .on('keydown', onKeydown)
.on('mousemove mousedown', userAlive) .on('mousemove mousedown', userAlive)
.on('click mousedown mousemove keydown keypress', function (ev) { .on('click mousedown mousemove keydown keypress', function (ev) {
if (ev.type === 'click' && (ev.target.id === 'pv-overlay' || ev.target.id === 'pv-content')) { if (ev.type === 'click' && (ev.target.id === 'pv-overlay' || ev.target.id === 'pv-content')) {
onExit(); onExit();
} }

View File

@@ -1,10 +1,9 @@
modulejs.define('ext/search', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/server', 'core/settings', 'core/util', 'model/item', 'view/view'], function (_, $, event, location, resource, server, allsettings, util, Item, view) { modulejs.define('ext/search', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/server', 'core/settings', 'core/util', 'model/item', 'view/view'], function (_, $, event, location, resource, server, allsettings, util, Item, view) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
advanced: false, advanced: false,
debounceTime: 300 debounceTime: 300
}, allsettings.search); }, allsettings.search);
var template = var template =
'<div id="search" class="tool">' + '<div id="search" class="tool">' +
'<img src="' + resource.image('search') + '" alt="search"/>' + '<img src="' + resource.image('search') + '" alt="search"/>' +
@@ -17,7 +16,6 @@ modulejs.define('ext/search', ['_', '$', 'core/event', 'core/location', 'core/re
function search(pattern) { function search(pattern) {
pattern = pattern || ''; pattern = pattern || '';
if (pattern === prevPattern) { if (pattern === prevPattern) {
return; return;
@@ -38,18 +36,15 @@ modulejs.define('ext/search', ['_', '$', 'core/event', 'core/location', 'core/re
pattern: pattern pattern: pattern
} }
}, function (response) { }, function (response) {
$search.removeClass('pending'); $search.removeClass('pending');
view.setHint('noMatch'); view.setHint('noMatch');
view.setItems(_.map(response.search, function (item) { view.setItems(_.map(response.search, function (item) {
return Item.get(item); return Item.get(item);
})); }));
}); });
} }
function update() { function update() {
if (inputIsVisible) { if (inputIsVisible) {
$search.addClass('active'); $search.addClass('active');
$input.focus(); $input.focus();
@@ -61,20 +56,17 @@ modulejs.define('ext/search', ['_', '$', 'core/event', 'core/location', 'core/re
} }
function toggle() { function toggle() {
inputIsVisible = !inputIsVisible; inputIsVisible = !inputIsVisible;
update(); update();
} }
function reset() { function reset() {
inputIsVisible = false; inputIsVisible = false;
$input.val(''); $input.val('');
update(); update();
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,10 +1,9 @@
modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/settings'], function (_, $, event, resource, allsettings) { modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/settings'], function (_, $, event, resource, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
clickndrag: false, clickndrag: false,
checkboxes: false checkboxes: false
}, allsettings.select); }, allsettings.select);
var template = '<span class="selector"><img src="' + resource.image('selected') + '" alt="selected"/></span>'; var template = '<span class="selector"><img src="' + resource.image('selected') + '" alt="selected"/></span>';
var x = 0; var x = 0;
var y = 0; var y = 0;
@@ -21,30 +20,26 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
function publish() { function publish() {
var items = _.map($('#items .item.selected'), function (itemElement) { var items = _.map($('#items .item.selected'), function (itemElement) {
return $(itemElement).data('item'); return $(itemElement).data('item');
}); });
event.pub('selection', items); event.pub('selection', items);
} }
function elementRect($element) { function elementRect($element) {
if (!$element.is(':visible')) { if (!$element.is(':visible')) {
return null; return null;
} }
var offset = $element.offset(); var offset = $element.offset();
var l = offset.left; var elL = offset.left;
var t = offset.top; var elT = offset.top;
var w = $element.outerWidth(); var elW = $element.outerWidth();
var h = $element.outerHeight(); var elH = $element.outerHeight();
return {l: l, t: t, w: w, h: h, r: l + w, b: t + h}; return {l: elL, t: elT, w: elW, h: elH, r: elL + elW, b: elT + elH};
} }
function doOverlap(rect1, rect2) { function doOverlap(rect1, rect2) {
if (!rect1 || !rect2) { if (!rect1 || !rect2) {
return false; return false;
} }
@@ -56,11 +51,10 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
var width = right - left; var width = right - left;
var height = bottom - top; var height = bottom - top;
return (width >= 0 && height >= 0); return width >= 0 && height >= 0;
} }
function selectionUpdate(ev) { function selectionUpdate(ev) {
l = Math.min(x, ev.pageX); l = Math.min(x, ev.pageX);
t = Math.min(y, ev.pageY); t = Math.min(y, ev.pageY);
w = Math.abs(x - ev.pageX); w = Math.abs(x - ev.pageX);
@@ -86,7 +80,6 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
var selRect = elementRect($selectionRect); var selRect = elementRect($selectionRect);
$('#items .item').removeClass('selecting').each(function () { $('#items .item').removeClass('selecting').each(function () {
var $item = $(this); var $item = $(this);
var inter = doOverlap(selRect, elementRect($item.find('a'))); var inter = doOverlap(selRect, elementRect($item.find('a')));
@@ -97,7 +90,6 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
} }
function selectionEnd(ev) { function selectionEnd(ev) {
$document.off('mousemove', selectionUpdate); $document.off('mousemove', selectionUpdate);
if (!isDragSelect) { if (!isDragSelect) {
@@ -112,23 +104,20 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
$html.removeClass('drag-select'); $html.removeClass('drag-select');
$selectionRect $selectionRect
.stop(true, true) .stop(true, true)
.animate( .animate({
{ left: l + w * 0.5 * shrink,
left: l + w * 0.5 * shrink, top: t + h * 0.5 * shrink,
top: t + h * 0.5 * shrink, width: w * (1 - shrink),
width: w * (1 - shrink), height: h * (1 - shrink),
height: h * (1 - shrink), opacity: 0
opacity: 0 },
}, 300,
300, function () {
function () { $selectionRect.hide();
$selectionRect.hide(); });
}
);
} }
function selectionStart(ev) { function selectionStart(ev) {
// only on left button and don't block scrollbar // only on left button and don't block scrollbar
if (ev.button !== 0 || ev.offsetX >= $('#content').width() - 14) { if (ev.button !== 0 || ev.offsetX >= $('#content').width() - 14) {
return; return;
@@ -145,7 +134,6 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
} }
function onSelectorClick(ev) { function onSelectorClick(ev) {
ev.stopImmediatePropagation(); ev.stopImmediatePropagation();
ev.preventDefault(); ev.preventDefault();
@@ -154,7 +142,6 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
} }
function addCheckbox(item) { function addCheckbox(item) {
if (item.$view && !item.isCurrentParentFolder()) { if (item.$view && !item.isCurrentParentFolder()) {
$(template) $(template)
.on('click', onSelectorClick) .on('click', onSelectorClick)
@@ -163,13 +150,11 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
} }
function onViewChanged(added, removed) { function onViewChanged(added, removed) {
if (settings.checkboxes) { if (settings.checkboxes) {
_.each(added, addCheckbox); _.each(added, addCheckbox);
} }
_.each(removed, function (item) { _.each(removed, function (item) {
if (item.$view) { if (item.$view) {
item.$view.removeClass('selected'); item.$view.removeClass('selected');
} }
@@ -179,8 +164,7 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
} }
function init() { function init() {
if (!settings.enabled || !settings.clickndrag && !settings.checkboxes) {
if (!settings.enabled || (!settings.clickndrag && !settings.checkboxes)) {
return; return;
} }
@@ -192,12 +176,10 @@ modulejs.define('ext/select', ['_', '$', 'core/event', 'core/resource', 'core/se
$('#content') $('#content')
.on('mousedown', selectionStart) .on('mousedown', selectionStart)
.on('drag dragstart', function (ev) { .on('drag dragstart', function (ev) {
ev.stopImmediatePropagation(); ev.stopImmediatePropagation();
ev.preventDefault(); ev.preventDefault();
}) })
.on('click', function () { .on('click', function () {
$('#items .item').removeClass('selected'); $('#items .item').removeClass('selected');
publish(); publish();
}); });

View File

@@ -1,19 +1,17 @@
modulejs.define('ext/sort', ['_', '$', 'core/event', 'core/resource', 'core/settings', 'core/store', 'core/util'], function (_, $, event, resource, allsettings, store, util) { modulejs.define('ext/sort', ['_', '$', 'core/event', 'core/resource', 'core/settings', 'core/store', 'core/util'], function (_, $, event, resource, allsettings, store, util) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
column: 0, column: 0,
reverse: false, reverse: false,
ignorecase: true, ignorecase: true,
natural: false, natural: false,
folders: 0 folders: 0
}, allsettings.sort); }, allsettings.sort);
var storekey = 'ext/sort'; var storekey = 'ext/sort';
var template = '<img src="' + resource.image('sort') + '" class="sort" alt="sort order" />'; var template = '<img src="' + resource.image('sort') + '" class="sort" alt="sort order" />';
function getType(item) { function getType(item) {
var $item = $(item); var $item = $(item);
if ($item.hasClass('folder-parent')) { if ($item.hasClass('folder-parent')) {
@@ -31,37 +29,32 @@ modulejs.define('ext/sort', ['_', '$', 'core/event', 'core/resource', 'core/sett
} }
function getName(item) { function getName(item) {
return $(item).find('.label').text(); return $(item).find('.label').text();
} }
function getTime(item) { function getTime(item) {
return $(item).find('.date').data('time'); return $(item).find('.date').data('time');
} }
function getSize(item) { function getSize(item) {
return $(item).find('.size').data('bytes'); return $(item).find('.size').data('bytes');
} }
var columnGetters = { var columnGetters = {
0: getName, 0: getName,
1: getTime, 1: getTime,
2: getSize 2: getSize
}; };
var columnClasses = { var columnClasses = {
0: 'label', 0: 'label',
1: 'date', 1: 'date',
2: 'size' 2: 'size'
}; };
function cmpFn(getValue, reverse, ignorecase, natural) { function cmpFn(getValue, reverse, ignorecase, natural) {
return function (item1, item2) { return function (item1, item2) {
var res; var res;
var val1; var val1;
var val2; var val2;
@@ -90,7 +83,6 @@ modulejs.define('ext/sort', ['_', '$', 'core/event', 'core/resource', 'core/sett
} }
function sortItems(column, reverse) { function sortItems(column, reverse) {
var $headers = $('#items li.header a'); var $headers = $('#items li.header a');
var $header = $('#items li.header a.' + columnClasses[column]); var $header = $('#items li.header a.' + columnClasses[column]);
var fn = cmpFn(columnGetters[column], reverse, settings.ignorecase, column === 0 && settings.natural); var fn = cmpFn(columnGetters[column], reverse, settings.ignorecase, column === 0 && settings.natural);
@@ -111,7 +103,6 @@ modulejs.define('ext/sort', ['_', '$', 'core/event', 'core/resource', 'core/sett
} }
function onContentChanged() { function onContentChanged() {
var order = store.get(storekey); var order = store.get(storekey);
var column = order && order.column || settings.column; var column = order && order.column || settings.column;
var reverse = order && order.reverse || settings.reverse; var reverse = order && order.reverse || settings.reverse;
@@ -120,7 +111,6 @@ modulejs.define('ext/sort', ['_', '$', 'core/event', 'core/resource', 'core/sett
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,19 +1,17 @@
modulejs.define('ext/thumbnails', ['_', 'core/event', 'core/server', 'core/settings'], function (_, event, server, allsettings) { modulejs.define('ext/thumbnails', ['_', 'core/event', 'core/server', 'core/settings'], function (_, event, server, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
img: ['img-bmp', 'img-gif', 'img-ico', 'img-jpg', 'img-png'], img: ['img-bmp', 'img-gif', 'img-ico', 'img-jpg', 'img-png'],
mov: ['vid-avi', 'vid-flv', 'vid-mkv', 'vid-mov', 'vid-mp4', 'vid-mpg', 'vid-webm'], mov: ['vid-avi', 'vid-flv', 'vid-mkv', 'vid-mov', 'vid-mp4', 'vid-mpg', 'vid-webm'],
doc: ['x-pdf', 'x-ps'], doc: ['x-pdf', 'x-ps'],
delay: 1, delay: 1,
size: 100, size: 100,
exif: false exif: false
}, allsettings.thumbnails); }, allsettings.thumbnails);
var landscapeRatio = 4 / 3; var landscapeRatio = 4 / 3;
function queueItem(queue, item) { function queueItem(queue, item) {
var type = null; var type = null;
if (_.contains(settings.img, item.type)) { if (_.contains(settings.img, item.type)) {
@@ -34,7 +32,6 @@ modulejs.define('ext/thumbnails', ['_', 'core/event', 'core/server', 'core/setti
href: item.absHref, href: item.absHref,
ratio: 1, ratio: 1,
callback: function (src) { callback: function (src) {
if (src && item.$view) { if (src && item.$view) {
item.thumbSquare = src; item.thumbSquare = src;
item.$view.find('.icon.square img').addClass('thumb').attr('src', src); item.$view.find('.icon.square img').addClass('thumb').attr('src', src);
@@ -51,7 +48,6 @@ modulejs.define('ext/thumbnails', ['_', 'core/event', 'core/server', 'core/setti
href: item.absHref, href: item.absHref,
ratio: landscapeRatio, ratio: landscapeRatio,
callback: function (src) { callback: function (src) {
if (src && item.$view) { if (src && item.$view) {
item.thumbRational = src; item.thumbRational = src;
item.$view.find('.icon.landscape img').addClass('thumb').attr('src', src); item.$view.find('.icon.landscape img').addClass('thumb').attr('src', src);
@@ -62,9 +58,7 @@ modulejs.define('ext/thumbnails', ['_', 'core/event', 'core/server', 'core/setti
} }
function requestQueue(queue) { function requestQueue(queue) {
var thumbs = _.map(queue, function (req) { var thumbs = _.map(queue, function (req) {
return { return {
type: req.type, type: req.type,
href: req.href, href: req.href,
@@ -77,20 +71,16 @@ modulejs.define('ext/thumbnails', ['_', 'core/event', 'core/server', 'core/setti
action: 'get', action: 'get',
thumbs: thumbs thumbs: thumbs
}, function (json) { }, function (json) {
_.each(queue, function (req, idx) { _.each(queue, function (req, idx) {
req.callback(json && json.thumbs ? json.thumbs[idx] : null); req.callback(json && json.thumbs ? json.thumbs[idx] : null);
}); });
}); });
} }
function handleItems(items) { function handleItems(items) {
var queue = []; var queue = [];
_.each(items, function (item) { _.each(items, function (item) {
queueItem(queue, item); queueItem(queue, item);
}); });
@@ -100,15 +90,12 @@ modulejs.define('ext/thumbnails', ['_', 'core/event', 'core/server', 'core/setti
} }
function onViewChanged(added) { function onViewChanged(added) {
setTimeout(function () { setTimeout(function () {
handleItems(added); handleItems(added);
}, settings.delay); }, settings.delay);
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,11 +1,9 @@
modulejs.define('ext/title', ['_', 'core/event', 'core/settings'], function (_, event, allsettings) { modulejs.define('ext/title', ['_', 'core/event', 'core/settings'], function (_, event, allsettings) {
var settings = _.extend({ var settings = _.extend({
enabled: false enabled: false
}, allsettings.title); }, allsettings.title);
function onLocationChanged(item) { function onLocationChanged(item) {
var labels = _.pluck(item.getCrumb(), 'label'); var labels = _.pluck(item.getCrumb(), 'label');
var title = labels.join(' > '); var title = labels.join(' > ');
@@ -17,7 +15,6 @@ modulejs.define('ext/title', ['_', 'core/event', 'core/settings'], function (_,
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }

View File

@@ -1,12 +1,11 @@
modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/settings', 'core/store', 'core/util'], function (_, $, event, location, resource, allsettings, store, util) { modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/resource', 'core/settings', 'core/store', 'core/util'], function (_, $, event, location, resource, allsettings, store, util) {
var settings = _.extend({ var settings = _.extend({
enabled: false, enabled: false,
show: true, show: true,
maxSubfolders: 50, maxSubfolders: 50,
naturalSort: false, naturalSort: false,
ignorecase: true ignorecase: true
}, allsettings.tree); }, allsettings.tree);
var template = var template =
'<div class="item">' + '<div class="item">' +
'<span class="indicator none">' + '<span class="indicator none">' +
@@ -28,7 +27,6 @@ modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/reso
function cmpFn(item1, item2) { function cmpFn(item1, item2) {
var val1 = item1.label; var val1 = item1.label;
var val2 = item2.label; var val2 = item2.label;
@@ -41,7 +39,6 @@ modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/reso
} }
function update(item) { function update(item) {
var $html = $(template); var $html = $(template);
var $indicator = $html.find('.indicator'); var $indicator = $html.find('.indicator');
var $a = $html.find('a'); var $a = $html.find('a');
@@ -57,15 +54,13 @@ modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/reso
$label.text(item.label); $label.text(item.label);
if (item.isFolder()) { if (item.isFolder()) {
var subfolders = item.getSubfolders(); var subfolders = item.getSubfolders();
// indicator // indicator
if ((item.isManaged && !item.isContentFetched) || subfolders.length) { if (item.isManaged && !item.isContentFetched || subfolders.length) {
$indicator.removeClass('none'); $indicator.removeClass('none');
if ((item.isManaged && !item.isContentFetched)) { if (item.isManaged && !item.isContentFetched) {
$indicator.addClass('unknown'); $indicator.addClass('unknown');
} else if (item.isContentVisible) { } else if (item.isContentVisible) {
$indicator.addClass('open'); $indicator.addClass('open');
@@ -114,52 +109,41 @@ modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/reso
} }
function createOnIndicatorClick() { function createOnIndicatorClick() {
function slide(item, $indicator, $content, down) { function slide(item, $indicator, $content, down) {
item.isContentVisible = down; item.isContentVisible = down;
$indicator.removeClass('open close').addClass(down ? 'open' : 'close'); $indicator.removeClass('open close').addClass(down ? 'open' : 'close');
$content[down ? 'slideDown' : 'slideUp'](); $content[down ? 'slideDown' : 'slideUp']();
} }
return function () { return function () {
var $indicator = $(this); var $indicator = $(this);
var $item = $indicator.closest('.item'); var $item = $indicator.closest('.item');
var item = $item.data('item'); var item = $item.data('item');
var $content = $item.find('> ul.content'); var $content = $item.find('> ul.content');
if ($indicator.hasClass('unknown')) { if ($indicator.hasClass('unknown')) {
item.fetchContent(function () {
item.fetchContent(function (item) {
item.isContentVisible = false; item.isContentVisible = false;
var $item = update(item); $item = update(item);
var $indicator = $item.find('> .indicator'); $indicator = $item.find('> .indicator');
var $content = $item.find('> ul.content'); $content = $item.find('> ul.content');
if (!$indicator.hasClass('none')) { if (!$indicator.hasClass('none')) {
slide(item, $indicator, $content, true); slide(item, $indicator, $content, true);
} }
}); });
} else if ($indicator.hasClass('open')) { } else if ($indicator.hasClass('open')) {
slide(item, $indicator, $content, false); slide(item, $indicator, $content, false);
} else if ($indicator.hasClass('close')) { } else if ($indicator.hasClass('close')) {
slide(item, $indicator, $content, true); slide(item, $indicator, $content, true);
} }
}; };
} }
function fetchTree(item, callback) { function fetchTree(item, callback) {
item.isContentVisible = true; item.isContentVisible = true;
item.fetchContent(function (item) { item.fetchContent(function () {
if (item.parent) { if (item.parent) {
fetchTree(item.parent, callback); fetchTree(item.parent, callback);
} else { } else {
@@ -169,7 +153,6 @@ modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/reso
} }
function updateSettings() { function updateSettings() {
if (store.get(storekey)) { if (store.get(storekey)) {
$('#view-tree').addClass('active'); $('#view-tree').addClass('active');
$('#tree').show(); $('#tree').show();
@@ -180,16 +163,13 @@ modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/reso
} }
function onLocationChanged(item) { function onLocationChanged(item) {
fetchTree(item, function (root) { fetchTree(item, function (root) {
$('#tree').append(update(root)); $('#tree').append(update(root));
updateSettings(); updateSettings();
}); });
} }
function init() { function init() {
if (!settings.enabled) { if (!settings.enabled) {
return; return;
} }
@@ -202,14 +182,13 @@ modulejs.define('ext/tree', ['_', '$', 'core/event', 'core/location', 'core/reso
.appendTo('#sidebar') .appendTo('#sidebar')
.find('#view-tree') .find('#view-tree')
.on('click', function (ev) { .on('click', function (ev) {
store.put(storekey, !store.get(storekey)); store.put(storekey, !store.get(storekey));
updateSettings(); updateSettings();
ev.preventDefault(); ev.preventDefault();
}); });
// ensure stored value is boolean, otherwise set default // ensure stored value is boolean, otherwise set default
if (typeof (store.get(storekey)) !== 'boolean') { if (typeof store.get(storekey) !== 'boolean') {
store.put(storekey, settings.show); store.put(storekey, settings.show);
} }
updateSettings(); updateSettings();

View File

@@ -1,9 +1,7 @@
modulejs.define('main/index', ['_', 'core/location'], function (_, location) { modulejs.define('main/index', ['_', 'core/location'], function (_, location) {
modulejs.require('view/viewmode'); modulejs.require('view/viewmode');
_.each(modulejs.state(), function (state, id) { _.each(modulejs.state(), function (state, id) {
if (id.indexOf('ext/') === 0) { if (id.indexOf('ext/') === 0) {
modulejs.require(id); modulejs.require(id);
} }

View File

@@ -1,5 +1,4 @@
modulejs.define('main/info', ['$', 'config', 'core/resource', 'core/server'], function ($, config, resource, server) { modulejs.define('main/info', ['$', 'config', 'core/resource', 'core/server'], function ($, config, resource, server) {
var tplTests = var tplTests =
'<ul id="tests">'; '<ul id="tests">';
var tplTest = var tplTest =
@@ -33,17 +32,15 @@ modulejs.define('main/info', ['$', 'config', 'core/resource', 'core/server'], fu
function addTest(label, info, passed, result) { function addTest(label, info, passed, result) {
var $test = $(tplTest).appendTo('#tests'); var $test = $(tplTest).appendTo('#tests');
$test.find('.label').text(label); $test.find('.label').text(label);
$test.find('.result') $test.find('.result')
.addClass(passed ? 'passed' : 'failed') .addClass(passed ? 'passed' : 'failed')
.text(result ? result : (passed ? 'yes' : 'no')); .text(result ? result : passed ? 'yes' : 'no');
$test.find('.info').html(info); $test.find('.info').html(info);
} }
function addTests() { function addTests() {
if (!setup.AS_ADMIN) { if (!setup.AS_ADMIN) {
return; return;
} }
@@ -52,7 +49,7 @@ modulejs.define('main/info', ['$', 'config', 'core/resource', 'core/server'], fu
addTest( addTest(
'h5ai version', 'Only green if this is an official h5ai release', 'h5ai version', 'Only green if this is an official h5ai release',
/^\d+\.\d+\.\d+$/.test(setup.VERSION), setup.VERSION (/^\d+\.\d+\.\d+$/).test(setup.VERSION), setup.VERSION
); );
addTest( addTest(
@@ -127,12 +124,10 @@ modulejs.define('main/info', ['$', 'config', 'core/resource', 'core/server'], fu
} }
function reload() { function reload() {
window.location.reload(); window.location.reload();
} }
function onLogin() { function onLogin() {
server.request({ server.request({
action: 'login', action: 'login',
pass: $('#pass').val() pass: $('#pass').val()
@@ -140,26 +135,22 @@ modulejs.define('main/info', ['$', 'config', 'core/resource', 'core/server'], fu
} }
function onLogout() { function onLogout() {
server.request({ server.request({
action: 'logout' action: 'logout'
}, reload); }, reload);
} }
function onKeydown(event) { function onKeydown(event) {
if (event.which === 13) { if (event.which === 13) {
onLogin(); onLogin();
} }
} }
function addSupport() { function addSupport() {
$(tplSupport).appendTo('#content'); $(tplSupport).appendTo('#content');
} }
function addLogin() { function addLogin() {
$(tplLogin).appendTo('#content'); $(tplLogin).appendTo('#content');
if (setup.AS_ADMIN) { if (setup.AS_ADMIN) {
@@ -177,7 +168,6 @@ modulejs.define('main/info', ['$', 'config', 'core/resource', 'core/server'], fu
} }
function init() { function init() {
addSupport(); addSupport();
addLogin(); addLogin();
addTests(); addTests();

View File

@@ -1,12 +1,10 @@
modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server', 'core/settings', 'core/types'], function (_, event, location, server, settings, types) { modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server', 'core/settings', 'core/types'], function (_, event, location, server, settings, types) {
var reEndsWithSlash = /\/$/; var reEndsWithSlash = /\/$/;
var reSplitPath = /^(.*\/)([^\/]+\/?)$/; var reSplitPath = /^(.*\/)([^\/]+\/?)$/;
var cache = {}; var cache = {};
function startsWith(sequence, part) { function startsWith(sequence, part) {
if (!sequence || !sequence.indexOf) { if (!sequence || !sequence.indexOf) {
return false; return false;
} }
@@ -15,16 +13,14 @@ modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server'
} }
function createLabel(sequence) { function createLabel(sequence) {
sequence = sequence.replace(reEndsWithSlash, ''); sequence = sequence.replace(reEndsWithSlash, '');
try { try {
sequence = decodeURIComponent(sequence); sequence = decodeURIComponent(sequence);
} catch (e) {} } catch (e) {/* skip */}
return sequence; return sequence;
} }
function splitPath(sequence) { function splitPath(sequence) {
if (sequence === '/') { if (sequence === '/') {
return { return {
parent: null, parent: null,
@@ -35,9 +31,9 @@ modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server'
var match = reSplitPath.exec(sequence); var match = reSplitPath.exec(sequence);
if (match) { if (match) {
var split = { var split = {
parent: match[1], parent: match[1],
name: match[2] name: match[2]
}; };
if (split.parent && !startsWith(split.parent, settings.rootHref)) { if (split.parent && !startsWith(split.parent, settings.rootHref)) {
split.parent = null; split.parent = null;
@@ -47,7 +43,6 @@ modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server'
} }
function getItem(options) { function getItem(options) {
if (_.isString(options)) { if (_.isString(options)) {
options = {href: options}; options = {href: options};
} else if (!options || !_.isString(options.href)) { } else if (!options || !_.isString(options.href)) {
@@ -60,70 +55,64 @@ modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server'
return null; return null;
} }
var self = cache[href] || new Item(href); var item = cache[href] || new Item(href);
if (_.isNumber(options.time)) { if (_.isNumber(options.time)) {
self.time = options.time; item.time = options.time;
} }
if (_.isNumber(options.size)) { if (_.isNumber(options.size)) {
self.size = options.size; item.size = options.size;
} }
if (options.managed) { if (options.managed) {
self.isManaged = true; item.isManaged = true;
} }
if (options.fetched) { if (options.fetched) {
self.isContentFetched = true; item.isContentFetched = true;
} }
return self; return item;
} }
function removeItem(absHref) { function removeItem(absHref) {
absHref = location.forceEncoding(absHref); absHref = location.forceEncoding(absHref);
var self = cache[absHref]; var item = cache[absHref];
if (self) { if (item) {
delete cache[absHref]; delete cache[absHref];
if (self.parent) { if (item.parent) {
delete self.parent.content[self.absHref]; delete item.parent.content[item.absHref];
} }
_.each(self.content, function (item) { _.each(item.content, function (child) {
removeItem(child.absHref);
removeItem(item.absHref);
}); });
} }
} }
function fetchContent(absHref, callback) { function fetchContent(absHref, callback) {
var item = getItem(absHref);
var self = getItem(absHref);
if (!_.isFunction(callback)) { if (!_.isFunction(callback)) {
callback = function () {}; callback = function () {};
} }
if (self.isContentFetched) { if (item.isContentFetched) {
callback(self); callback(item);
} else { } else {
server.request({action: 'get', items: {href: self.absHref, what: 1}}, function (response) { server.request({action: 'get', items: {href: item.absHref, what: 1}}, function (response) {
if (response.items) { if (response.items) {
_.each(response.items, function (jsonItem) { _.each(response.items, function (jsonItem) {
getItem(jsonItem); getItem(jsonItem);
}); });
} }
callback(self); callback(item);
}); });
} }
} }
function Item(absHref) { function Item(absHref) {
var split = splitPath(absHref); var split = splitPath(absHref);
cache[absHref] = this; cache[absHref] = this;
@@ -149,49 +138,40 @@ modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server'
_.extend(Item.prototype, { _.extend(Item.prototype, {
isFolder: function () { isFolder: function () {
return reEndsWithSlash.test(this.absHref); return reEndsWithSlash.test(this.absHref);
}, },
isCurrentFolder: function () { isCurrentFolder: function () {
return this.absHref === location.getAbsHref(); return this.absHref === location.getAbsHref();
}, },
isInCurrentFolder: function () { isInCurrentFolder: function () {
return Boolean(this.parent) && this.parent.isCurrentFolder(); return Boolean(this.parent) && this.parent.isCurrentFolder();
}, },
isCurrentParentFolder: function () { isCurrentParentFolder: function () {
var item = getItem(location.getAbsHref()); var item = getItem(location.getAbsHref());
return Boolean(item) && this === item.parent; return Boolean(item) && this === item.parent;
}, },
isDomain: function () { isDomain: function () {
return this.absHref === '/'; return this.absHref === '/';
}, },
isRoot: function () { isRoot: function () {
return this.absHref === settings.rootHref; return this.absHref === settings.rootHref;
}, },
isEmpty: function () { isEmpty: function () {
return _.keys(this.content).length === 0; return _.keys(this.content).length === 0;
}, },
fetchContent: function (callback) { fetchContent: function (callback) {
return fetchContent(this.absHref, callback); return fetchContent(this.absHref, callback);
}, },
getCrumb: function () { getCrumb: function () {
var item = this; // eslint-disable-line consistent-this
var item = this;
var crumb = [item]; var crumb = [item];
while (item.parent) { while (item.parent) {
@@ -203,23 +183,18 @@ modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server'
}, },
getSubfolders: function () { getSubfolders: function () {
return _.sortBy(_.filter(this.content, function (item) { return _.sortBy(_.filter(this.content, function (item) {
return item.isFolder(); return item.isFolder();
}), function (item) { }), function (item) {
return item.label.toLowerCase(); return item.label.toLowerCase();
}); });
}, },
getStats: function () { getStats: function () {
var folders = 0; var folders = 0;
var files = 0; var files = 0;
_.each(this.content, function (item) { _.each(this.content, function (item) {
if (item.isFolder()) { if (item.isFolder()) {
folders += 1; folders += 1;
} else { } else {
@@ -228,7 +203,7 @@ modulejs.define('model/item', ['_', 'core/event', 'core/location', 'core/server'
}); });
var depth = 0; var depth = 0;
var item = this; var item = this; // eslint-disable-line consistent-this
while (item.parent) { while (item.parent) {
depth += 1; depth += 1;

View File

@@ -1,5 +1,4 @@
modulejs.define('view/content', ['$', 'view/mainrow'], function ($, mainrow) { modulejs.define('view/content', ['$', 'view/mainrow'], function ($, mainrow) {
var $el = $('<div id="content"/>').appendTo(mainrow.$el); var $el = $('<div id="content"/>').appendTo(mainrow.$el);
return { return {

View File

@@ -1,5 +1,4 @@
modulejs.define('view/mainrow', ['$', 'view/root'], function ($, root) { modulejs.define('view/mainrow', ['$', 'view/root'], function ($, root) {
var $el = $('<div id="mainrow"/>').appendTo(root.$el); var $el = $('<div id="mainrow"/>').appendTo(root.$el);
return { return {

View File

@@ -1,9 +1,7 @@
modulejs.define('view/notification', ['$', 'view/root'], function ($, root) { modulejs.define('view/notification', ['$', 'view/root'], function ($, root) {
var $el = $('<div id="notification"/>').hide().appendTo(root.$el); var $el = $('<div id="notification"/>').hide().appendTo(root.$el);
function set(content) { function set(content) {
if (content) { if (content) {
$el.stop(true, true).html(content).fadeIn(400); $el.stop(true, true).html(content).fadeIn(400);
} else { } else {

View File

@@ -1,5 +1,4 @@
modulejs.define('view/root', ['$'], function ($) { modulejs.define('view/root', ['$'], function ($) {
var $el = $('body').attr('id', 'root'); var $el = $('body').attr('id', 'root');
$('#fallback, #fallback-hints').remove(); $('#fallback, #fallback-hints').remove();

View File

@@ -1,5 +1,4 @@
modulejs.define('view/sidebar', ['$', 'core/resource', 'core/store', 'view/mainrow', 'view/topbar'], function ($, resource, store, mainrow, topbar) { modulejs.define('view/sidebar', ['$', 'core/resource', 'core/store', 'view/mainrow', 'view/topbar'], function ($, resource, store, mainrow, topbar) {
var storekey = 'sidebarIsVisible'; var storekey = 'sidebarIsVisible';
var tplSidebar = '<div id="sidebar"/>'; var tplSidebar = '<div id="sidebar"/>';
var tplToggle = var tplToggle =
@@ -12,7 +11,6 @@ modulejs.define('view/sidebar', ['$', 'core/resource', 'core/store', 'view/mainr
function update(toggle) { function update(toggle) {
var isVisible = store.get(storekey); var isVisible = store.get(storekey);
if (toggle) { if (toggle) {

View File

@@ -1,5 +1,4 @@
modulejs.define('view/topbar', ['$', 'view/root'], function ($, root) { modulejs.define('view/topbar', ['$', 'view/root'], function ($, root) {
var tplTopbar = var tplTopbar =
'<div id="topbar">' + '<div id="topbar">' +
'<div id="toolbar"/>' + '<div id="toolbar"/>' +

View File

@@ -1,15 +1,14 @@
modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/location', 'core/resource', 'core/settings', 'core/store', 'view/content'], function (_, $, event, format, location, resource, allsettings, store, content) { modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/location', 'core/resource', 'core/settings', 'core/store', 'view/content'], function (_, $, event, format, location, resource, allsettings, store, content) {
var modes = ['details', 'grid', 'icons']; var modes = ['details', 'grid', 'icons'];
var sizes = [20, 40, 60, 80, 100, 150, 200, 250, 300, 350, 400]; var sizes = [20, 40, 60, 80, 100, 150, 200, 250, 300, 350, 400];
var settings = _.extend({ var settings = _.extend({
binaryPrefix: false, binaryPrefix: false,
hideFolders: false, hideFolders: false,
hideParentFolder: false, hideParentFolder: false,
modes: modes, modes: modes,
setParentFolderLabels: false, setParentFolderLabels: false,
sizes: sizes sizes: sizes
}, allsettings.view); }, allsettings.view);
var sortedSizes = settings.sizes.sort(function (a, b) { return a - b; }); var sortedSizes = settings.sizes.sort(function (a, b) { return a - b; });
var checkedModes = _.intersection(settings.modes, modes); var checkedModes = _.intersection(settings.modes, modes);
var storekey = 'view'; var storekey = 'view';
@@ -41,46 +40,42 @@ modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/locat
function cropSize(size, min, max) { function cropSize(size, min, max) {
return Math.min(max, Math.max(min, size)); return Math.min(max, Math.max(min, size));
} }
function createStyles(size) { function createStyles(size) {
var dsize = cropSize(size, 20, 80); var dsize = cropSize(size, 20, 80);
var gsize = cropSize(size, 40, 160); var gsize = cropSize(size, 40, 160);
var isize = cropSize(size, 80, 1000); var isize = cropSize(size, 80, 1000);
var ilsize = Math.round(isize * 4 / 3); var ilsize = Math.round(isize * 4 / 3);
var rules = [ var rules = [
'#view.view-details.view-size-' + size + ' .item .label { line-height: ' + (dsize + 14) + 'px !important; }', '#view.view-details.view-size-' + size + ' .item .label { line-height: ' + (dsize + 14) + 'px !important; }',
'#view.view-details.view-size-' + size + ' .item .date { line-height: ' + (dsize + 14) + 'px !important; }', '#view.view-details.view-size-' + size + ' .item .date { line-height: ' + (dsize + 14) + 'px !important; }',
'#view.view-details.view-size-' + size + ' .item .size { line-height: ' + (dsize + 14) + 'px !important; }', '#view.view-details.view-size-' + size + ' .item .size { line-height: ' + (dsize + 14) + 'px !important; }',
'#view.view-details.view-size-' + size + ' .square { width: ' + dsize + 'px !important; height: ' + dsize + 'px !important; }', '#view.view-details.view-size-' + size + ' .square { width: ' + dsize + 'px !important; height: ' + dsize + 'px !important; }',
'#view.view-details.view-size-' + size + ' .square img { width: ' + dsize + 'px !important; height: ' + dsize + 'px !important; }', '#view.view-details.view-size-' + size + ' .square img { width: ' + dsize + 'px !important; height: ' + dsize + 'px !important; }',
'#view.view-details.view-size-' + size + ' .label { margin: 0 246px 0 ' + (dsize + 32) + 'px !important; }', '#view.view-details.view-size-' + size + ' .label { margin: 0 246px 0 ' + (dsize + 32) + 'px !important; }',
'#view.view-grid.view-size-' + size + ' .item .label { line-height: ' + gsize + 'px !important; }', '#view.view-grid.view-size-' + size + ' .item .label { line-height: ' + gsize + 'px !important; }',
'#view.view-grid.view-size-' + size + ' .square { width: ' + gsize + 'px !important; height: ' + gsize + 'px !important; }', '#view.view-grid.view-size-' + size + ' .square { width: ' + gsize + 'px !important; height: ' + gsize + 'px !important; }',
'#view.view-grid.view-size-' + size + ' .square img { width: ' + gsize + 'px !important; height: ' + gsize + 'px !important; }', '#view.view-grid.view-size-' + size + ' .square img { width: ' + gsize + 'px !important; height: ' + gsize + 'px !important; }',
'#view.view-icons.view-size-' + size + ' .item { width: ' + ilsize + 'px !important; }', '#view.view-icons.view-size-' + size + ' .item { width: ' + ilsize + 'px !important; }',
'#view.view-icons.view-size-' + size + ' .landscape { width: ' + ilsize + 'px !important; height: ' + isize + 'px !important; }', '#view.view-icons.view-size-' + size + ' .landscape { width: ' + ilsize + 'px !important; height: ' + isize + 'px !important; }',
'#view.view-icons.view-size-' + size + ' .landscape img { width: ' + isize + 'px !important; height: ' + isize + 'px !important; }', '#view.view-icons.view-size-' + size + ' .landscape img { width: ' + isize + 'px !important; height: ' + isize + 'px !important; }',
'#view.view-icons.view-size-' + size + ' .landscape .thumb { width: ' + ilsize + 'px !important; }' '#view.view-icons.view-size-' + size + ' .landscape .thumb { width: ' + ilsize + 'px !important; }'
]; ];
return rules.join('\n'); return rules.join('\n');
} }
function addCssStyles() { function addCssStyles() {
var styles = _.map(sortedSizes, function (size) { return createStyles(size); }); var styles = _.map(sortedSizes, function (size) { return createStyles(size); });
styles.push('#view .icon img { max-width: ' + settings.maxIconSize + 'px; max-height: ' + settings.maxIconSize + 'px; }'); styles.push('#view .icon img { max-width: ' + settings.maxIconSize + 'px; max-height: ' + settings.maxIconSize + 'px; }');
$('<style/>').text(styles.join('\n')).appendTo('head'); $('<style/>').text(styles.join('\n')).appendTo('head');
} }
function set(mode, size) { function set(mode, size) {
var stored = store.get(storekey); var stored = store.get(storekey);
mode = mode || stored && stored.mode; mode = mode || stored && stored.mode;
@@ -109,37 +104,30 @@ modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/locat
} }
function getModes() { function getModes() {
return checkedModes; return checkedModes;
} }
function getSizes() { function getSizes() {
return sortedSizes; return sortedSizes;
} }
function getMode() { function getMode() {
return store.get(storekey).mode; return store.get(storekey).mode;
} }
function setMode(mode) { function setMode(mode) {
set(mode, null); set(mode, null);
} }
function getSize() { function getSize() {
return store.get(storekey).size; return store.get(storekey).size;
} }
function setSize(size) { function setSize(size) {
set(null, size); set(null, size);
} }
function createHtml(item) { function createHtml(item) {
var $html = $(tplItem); var $html = $(tplItem);
var $a = $html.find('a'); var $a = $html.find('a');
var $iconImg = $html.find('.icon img'); var $iconImg = $html.find('.icon img');
@@ -178,56 +166,16 @@ modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/locat
} }
function onMouseenter() { function onMouseenter() {
var item = $(this).closest('.item').data('item'); var item = $(this).closest('.item').data('item');
event.pub('item.mouseenter', item); event.pub('item.mouseenter', item);
} }
function onMouseleave() { function onMouseleave() {
var item = $(this).closest('.item').data('item'); var item = $(this).closest('.item').data('item');
event.pub('item.mouseleave', item); event.pub('item.mouseleave', item);
} }
function setItems(items) {
var removed = _.map($items.find('.item'), function (item) {
return $(item).data('item');
});
$items.find('.item').remove();
_.each(items, function (e) {
$items.append(createHtml(e));
});
content.$el.scrollLeft(0).scrollTop(0);
checkHint();
event.pub('view.changed', items, removed);
}
function changeItems(add, remove) {
_.each(add, function (item) {
createHtml(item).hide().appendTo($items).fadeIn(400);
});
_.each(remove, function (item) {
item.$view.fadeOut(400, function () {
item.$view.remove();
});
});
checkHint();
event.pub('view.changed', add, remove);
}
function checkHint() { function checkHint() {
var hasNoItems = $items.find('.item').not('.folder-parent').length === 0; var hasNoItems = $items.find('.item').not('.folder-parent').length === 0;
if (hasNoItems) { if (hasNoItems) {
@@ -237,14 +185,43 @@ modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/locat
} }
} }
function setHint(l10nKey) { function setItems(items) {
var removed = _.map($items.find('.item'), function (item) {
return $(item).data('item');
});
$items.find('.item').remove();
_.each(items, function (e) {
$items.append(createHtml(e));
});
content.$el.scrollLeft(0).scrollTop(0);
checkHint();
event.pub('view.changed', items, removed);
}
function changeItems(add, remove) {
_.each(add, function (item) {
createHtml(item).hide().appendTo($items).fadeIn(400);
});
_.each(remove, function (item) {
item.$view.fadeOut(400, function () {
item.$view.remove();
});
});
checkHint();
event.pub('view.changed', add, remove);
}
function setHint(l10nKey) {
$hint.removeClass().addClass('l10n-' + l10nKey); $hint.removeClass().addClass('l10n-' + l10nKey);
checkHint(); checkHint();
} }
function onLocationChanged(item) { function onLocationChanged(item) {
if (!item) { if (!item) {
item = location.getItem(); item = location.getItem();
} }
@@ -255,10 +232,9 @@ modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/locat
items.push(item.parent); items.push(item.parent);
} }
_.each(item.content, function (item) { _.each(item.content, function (child) {
if (!(child.isFolder() && settings.hideFolders)) {
if (!(item.isFolder() && settings.hideFolders)) { items.push(child);
items.push(item);
} }
}); });
@@ -267,13 +243,11 @@ modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/locat
} }
function onLocationRefreshed(item, added, removed) { function onLocationRefreshed(item, added, removed) {
var add = []; var add = [];
_.each(added, function (item) { _.each(added, function (child) {
if (!(child.isFolder() && settings.hideFolders)) {
if (!(item.isFolder() && settings.hideFolders)) { add.push(child);
add.push(item);
} }
}); });
@@ -282,7 +256,6 @@ modulejs.define('view/view', ['_', '$', 'core/event', 'core/format', 'core/locat
} }
function init() { function init() {
addCssStyles(); addCssStyles();
set(); set();

View File

@@ -1,8 +1,7 @@
modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core/settings', 'view/sidebar', 'view/topbar', 'view/view'], function (_, $, event, resource, allsettings, sidebar, topbar, view) { modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core/settings', 'view/sidebar', 'view/topbar', 'view/view'], function (_, $, event, resource, allsettings, sidebar, topbar, view) {
var settings = _.extend({ var settings = _.extend({
modeToggle: false modeToggle: false
}, allsettings.view); }, allsettings.view);
var tplSettings = var tplSettings =
'<div id="viewmode-settings" class="block"><h1 class="l10n-view">View</h1></div>'; '<div id="viewmode-settings" class="block"><h1 class="l10n-view">View</h1></div>';
var tplMode = var tplMode =
@@ -20,7 +19,6 @@ modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core
function onChanged(mode, size) { function onChanged(mode, size) {
$('#viewmode-settings .mode').removeClass('active'); $('#viewmode-settings .mode').removeClass('active');
$('#viewmode-' + mode).addClass('active'); $('#viewmode-' + mode).addClass('active');
$('#viewmode-size').val(_.indexOf(sizes, size)); $('#viewmode-size').val(_.indexOf(sizes, size));
@@ -32,7 +30,6 @@ modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core
} }
function addSettings() { function addSettings() {
if (modes.length < 2 && sizes.length < 2) { if (modes.length < 2 && sizes.length < 2) {
return; return;
} }
@@ -43,7 +40,6 @@ modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core
_.each(modes, function (mode) { _.each(modes, function (mode) {
$(tplMode.replace(/\[MODE\]/g, mode)) $(tplMode.replace(/\[MODE\]/g, mode))
.on('click', function () { .on('click', function () {
view.setMode(mode); view.setMode(mode);
}) })
.appendTo($viewBlock); .appendTo($viewBlock);
@@ -55,7 +51,6 @@ modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core
$(tplSize) $(tplSize)
.prop('max', max).attr('max', max) .prop('max', max).attr('max', max)
.on('input change', function (ev) { .on('input change', function (ev) {
view.setSize(sizes[ev.target.valueAsNumber]); view.setSize(sizes[ev.target.valueAsNumber]);
}) })
.appendTo($viewBlock); .appendTo($viewBlock);
@@ -65,7 +60,6 @@ modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core
} }
function onToggle() { function onToggle() {
var mode = view.getMode(); var mode = view.getMode();
var nextIdx = (modes.indexOf(mode) + 1) % modes.length; var nextIdx = (modes.indexOf(mode) + 1) % modes.length;
var nextMode = modes[nextIdx]; var nextMode = modes[nextIdx];
@@ -74,7 +68,6 @@ modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core
} }
function addToggle() { function addToggle() {
if (settings.modeToggle && modes.length > 1) { if (settings.modeToggle && modes.length > 1) {
$(tplToggle) $(tplToggle)
.on('click', onToggle) .on('click', onToggle)
@@ -83,7 +76,6 @@ modulejs.define('view/viewmode', ['_', '$', 'core/event', 'core/resource', 'core
} }
function init() { function init() {
modes = view.getModes(); modes = view.getModes();
sizes = view.getSizes(); sizes = view.getSizes();

View File

@@ -17,7 +17,7 @@
// @include 'vendor/prism-*.js' // @include 'vendor/prism-*.js'
(function () { (function () {
'use strict'; 'use strict'; // eslint-disable-line strict
var win = window; var win = window;
modulejs.define('_', function () { return win._; }); modulejs.define('_', function () { return win._; });

51
test/.eslintrc Normal file
View File

@@ -0,0 +1,51 @@
---
env:
es6: false
node: false
browser: true
mocha: true
globals:
modulejs: false
jQuery: false
$: false
_: false
util: false
assert: false
uniq: false
sinon: false
ecmaFeatures:
arrowFunctions: false
binaryLiterals: false
blockBindings: false
classes: false
defaultParams: false
destructuring: false
forOf: false
generators: false
globalReturn: false
jsx: false
modules: false
objectLiteralComputedProperties: false
objectLiteralDuplicateProperties: false
objectLiteralShorthandMethods: false
objectLiteralShorthandProperties: false
octalLiterals: false
regexUFlag: false
regexYFlag: false
spread: false
superInFunctions: false
templateStrings: false
unicodeCodePointEscapes: false
rules:
consistent-this: 0
func-names: 0
max-nested-callbacks: [1, 5]
max-params: [1, 10]
no-invalid-this: 0
no-var: 0
object-shorthand: 0
prefer-arrow-callback: 0
prefer-reflect: 0

View File

@@ -1,14 +1,14 @@
doctype html doctype html
html html
head head
meta( charset="utf-8" ) meta(charset="utf-8")
meta( http-equiv="x-ua-compatible", content="ie=edge" ) meta(http-equiv="x-ua-compatible", content="ie=edge")
title h5ai test suite - v#{pkg.version} title h5ai test suite - v#{pkg.version}
meta( name="viewport", content="width=device-width, initial-scale=1" ) meta(name="viewport", content="width=device-width, initial-scale=1")
link( rel="stylesheet", href="h5ai-styles.css" ) link(rel="stylesheet", href="h5ai-styles.css")
link( rel="stylesheet", href="styles.css" ) link(rel="stylesheet", href="styles.css")
script( src="h5ai-scripts.js" ) script(src="h5ai-scripts.js")
script( src="scripts.js" ) script(src="scripts.js")
body body
div#mocha div#mocha

View File

@@ -1,19 +1,21 @@
// @include "vendor/*.js" // @include "vendor/*.js"
// @include "util/*.js"
$(function () { (function () {
'use strict'; 'use strict'; // eslint-disable-line strict
// @include "util/*.js"
}());
jQuery(function () {
'use strict'; // eslint-disable-line strict
util.mockConfigModule(); util.mockConfigModule();
util.clearModulejs(); util.clearModulejs();
util.setupMocha(); util.setupMocha();
describe('all tests', function () { describe('all tests', function () {
// @include "tests/premisses.js" // @include "tests/premisses.js"
describe('unit tests', function () { describe('unit tests', function () {
// @include "tests/unit/modulejs.js" // @include "tests/unit/modulejs.js"
// @include "tests/unit/libs.js" // @include "tests/unit/libs.js"
// @include "tests/unit/boot.js" // @include "tests/unit/boot.js"
@@ -23,7 +25,6 @@ $(function () {
}); });
describe('integration tests', function () { describe('integration tests', function () {
// @include "tests/integration/*.js" // @include "tests/integration/*.js"
// @-include "tests/integration/*/*.js" // @-include "tests/integration/*/*.js"
}); });

View File

@@ -1,129 +1,106 @@
(function () { (function () {
'use strict'; describe('view', function () {
before(function () {
describe('view', function () { this.configBackup = modulejs._private.definitions.config;
this.storeKey = '_h5ai';
before(function () { this.xConfig = {
setup: {
this.configBackup = modulejs._private.definitions.config; PUBLIC_HREF: uniq.path('-PUBLIC/'),
this.storeKey = '_h5ai'; ROOT_HREF: uniq.path('-ROOT/')
this.xConfig = { }
setup: { };
PUBLIC_HREF: uniq.path('-PUBLIC/'),
ROOT_HREF: uniq.path('-ROOT/')
}
};
});
after(function () {
modulejs._private.definitions.config = this.configBackup;
util.clearModulejs();
util.restoreHtml();
});
beforeEach(function () {
delete modulejs._private.definitions.config;
modulejs.define('config', this.xConfig);
util.clearModulejs();
util.restoreHtml();
$('<div id="fallback"/>').appendTo('body');
$('<div id="fallback-hints"/>').appendTo('body');
});
describe('requiring \'view/viewmode\' sets up basic HTML', function () {
it('runs without errors', function () {
modulejs.require('view/viewmode');
}); });
it('adds id root to body', function () { after(function () {
modulejs._private.definitions.config = this.configBackup;
modulejs.require('view/viewmode'); util.clearModulejs();
assert.strictEqual($('body').attr('id'), 'root'); util.restoreHtml();
}); });
it('removes HTML #fallback', function () { beforeEach(function () {
delete modulejs._private.definitions.config;
modulejs.require('view/viewmode'); modulejs.define('config', this.xConfig);
assert.lengthOf($('#fallback'), 0); util.clearModulejs();
util.restoreHtml();
$('<div id="fallback"/>').appendTo('body');
$('<div id="fallback-hints"/>').appendTo('body');
}); });
it('removes HTML #fallback-hints', function () { describe('requiring \'view/viewmode\' sets up basic HTML', function () {
it('runs without errors', function () {
modulejs.require('view/viewmode');
});
modulejs.require('view/viewmode'); it('adds id root to body', function () {
assert.lengthOf($('#fallback-hints'), 0); modulejs.require('view/viewmode');
}); assert.strictEqual($('body').attr('id'), 'root');
});
it('adds HTML #mainrow to #root', function () { it('removes HTML #fallback', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#fallback'), 0);
});
modulejs.require('view/viewmode'); it('removes HTML #fallback-hints', function () {
assert.lengthOf($('#root > #mainrow'), 1); modulejs.require('view/viewmode');
}); assert.lengthOf($('#fallback-hints'), 0);
});
it('adds HTML #content to #mainrow', function () { it('adds HTML #mainrow to #root', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#root > #mainrow'), 1);
});
modulejs.require('view/viewmode'); it('adds HTML #content to #mainrow', function () {
assert.lengthOf($('#mainrow > #content'), 1); modulejs.require('view/viewmode');
}); assert.lengthOf($('#mainrow > #content'), 1);
});
it('adds HTML #view to #content', function () { it('adds HTML #view to #content', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#content > #view'), 1);
});
modulejs.require('view/viewmode'); it('adds HTML #items to #view', function () {
assert.lengthOf($('#content > #view'), 1); modulejs.require('view/viewmode');
}); assert.lengthOf($('#view > #items'), 1);
});
it('adds HTML #items to #view', function () { it('adds HTML #topbar to #root', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#root > #topbar'), 1);
});
modulejs.require('view/viewmode'); it('adds HTML #toolbar to #topbar', function () {
assert.lengthOf($('#view > #items'), 1); modulejs.require('view/viewmode');
}); assert.lengthOf($('#topbar > #toolbar'), 1);
});
it('adds HTML #topbar to #root', function () { it('adds HTML #flowbar to #topbar', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#topbar > #flowbar'), 1);
});
modulejs.require('view/viewmode'); it('adds HTML #backlink to #topbar', function () {
assert.lengthOf($('#root > #topbar'), 1); modulejs.require('view/viewmode');
}); assert.lengthOf($('#topbar > #backlink'), 1);
});
it('adds HTML #toolbar to #topbar', function () { it('adds HTML #sidebar-toggle to #toolbar', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#toolbar > #sidebar-toggle'), 1);
});
modulejs.require('view/viewmode'); it('adds HTML #viewmode-settings to #sidebar', function () {
assert.lengthOf($('#topbar > #toolbar'), 1); modulejs.require('view/viewmode');
}); assert.lengthOf($('#sidebar > #viewmode-settings'), 1);
});
it('adds HTML #flowbar to #topbar', function () { it('adds style to head', function () {
var styleTagCount = $('head > style').length;
modulejs.require('view/viewmode'); modulejs.require('view/viewmode');
assert.lengthOf($('#topbar > #flowbar'), 1); assert.lengthOf($('head > style'), styleTagCount + 1);
}); });
it('adds HTML #backlink to #topbar', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#topbar > #backlink'), 1);
});
it('adds HTML #sidebar-toggle to #toolbar', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#toolbar > #sidebar-toggle'), 1);
});
it('adds HTML #viewmode-settings to #sidebar', function () {
modulejs.require('view/viewmode');
assert.lengthOf($('#sidebar > #viewmode-settings'), 1);
});
it('adds style to head', function () {
var styleTagCount = $('head > style').length;
modulejs.require('view/viewmode');
assert.lengthOf($('head > style'), styleTagCount + 1);
}); });
}); });
});
}()); }());

View File

@@ -1,81 +1,69 @@
(function () { (function () {
'use strict'; describe('premisses', function () {
it('window is global object', function () {
assert.isObject(window);
assert.strictEqual(window, window.window);
});
describe('premisses', function () { it('document is global object', function () {
assert.isObject(document);
assert.strictEqual(document, window.document);
});
it('window is global object', function () { it('jQuery and $ are global functions', function () {
assert.isFunction(jQuery);
assert.strictEqual(jQuery, window.jQuery);
assert.strictEqual(jQuery.fn.jquery, '2.1.3');
assert.isObject(window); assert.strictEqual($, jQuery);
assert.strictEqual(window, window.window); assert.strictEqual($, window.$);
});
it('_ is global function', function () {
assert.isFunction(_);
assert.strictEqual(_, window._);
assert.strictEqual(_.VERSION, '3.9.3');
});
it('util is global object', function () {
assert.isPlainObject(util);
assert.strictEqual(util, window.util);
});
it('uniq is global object', function () {
assert.isPlainObject(uniq);
assert.strictEqual(uniq, window.uniq);
});
it('assert.isPlainObject() works', function () {
assert.isFunction(assert.isPlainObject);
assert.isPlainObject({});
assert.isPlainObject({a: 1});
assert.isPlainObject(Object());
assert.isPlainObject(new Object()); // eslint-disable-line no-new-object
assert.throws(function () { assert.isPlainObject(); });
assert.throws(function () { assert.isPlainObject(1); });
assert.throws(function () { assert.isPlainObject('a'); });
assert.throws(function () { assert.isPlainObject(new Date()); });
assert.throws(function () { assert.isPlainObject(/a/); });
assert.throws(function () { assert.isPlainObject(function () {}); });
assert.throws(function () { assert.isPlainObject(new function A() {}); });
});
it('assert.lengthOfKeys() works', function () {
assert.isFunction(assert.lengthOfKeys);
assert.lengthOfKeys({}, 0);
assert.lengthOfKeys({a: true}, 1);
assert.lengthOfKeys({a: true, b: 0, c: undefined}, 3);
assert.throws(function () { assert.lengthOfKeys(); });
assert.throws(function () { assert.lengthOfKeys(1); });
assert.throws(function () { assert.lengthOfKeys('a'); });
assert.throws(function () { assert.lengthOfKeys({}); });
assert.throws(function () { assert.lengthOfKeys({}, 1); });
});
}); });
it('document is global object', function () {
assert.isObject(document);
assert.strictEqual(document, window.document);
});
it('jQuery and $ are global functions', function () {
assert.isFunction(jQuery);
assert.strictEqual(jQuery, window.jQuery);
assert.strictEqual(jQuery.fn.jquery, '2.1.3');
assert.strictEqual($, jQuery);
assert.strictEqual($, window.$);
});
it('_ is global function', function () {
assert.isFunction(_);
assert.strictEqual(_, window._);
assert.strictEqual(_.VERSION, '3.9.3');
});
it('util is global object', function () {
assert.isPlainObject(util);
assert.strictEqual(util, window.util);
});
it('uniq is global object', function () {
assert.isPlainObject(uniq);
assert.strictEqual(uniq, window.uniq);
});
it('assert.isPlainObject() works', function () {
assert.isFunction(assert.isPlainObject);
assert.isPlainObject({});
assert.isPlainObject({a: 1});
assert.isPlainObject(Object());
assert.isPlainObject(new Object());
assert.throws(function () { assert.isPlainObject(); });
assert.throws(function () { assert.isPlainObject(1); });
assert.throws(function () { assert.isPlainObject('a'); });
assert.throws(function () { assert.isPlainObject(new Date()); });
assert.throws(function () { assert.isPlainObject(/a/); });
assert.throws(function () { assert.isPlainObject(function () {}); });
assert.throws(function () { assert.isPlainObject(new function A() {}); });
});
it('assert.lengthOfKeys() works', function () {
assert.isFunction(assert.lengthOfKeys);
assert.lengthOfKeys({}, 0);
assert.lengthOfKeys({a: true}, 1);
assert.lengthOfKeys({a: true, b: 0, c: undefined}, 3);
assert.throws(function () { assert.lengthOfKeys(); });
assert.throws(function () { assert.lengthOfKeys(1); });
assert.throws(function () { assert.lengthOfKeys('a'); });
assert.throws(function () { assert.lengthOfKeys({}); });
assert.throws(function () { assert.lengthOfKeys({}, 1); });
});
});
}()); }());

View File

@@ -1,105 +1,86 @@
(function () { (function () {
'use strict'; var ID = 'boot';
var DEPS = ['$', 'core/server'];
var ID = 'boot'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$', 'core/server']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xConfig = uniq.obj();
this.xDefine = sinon.stub(modulejs, 'define');
this.xRequire = sinon.stub(modulejs, 'require');
this.xServer = {
request: sinon.stub().callsArgWith(1, this.xConfig)
};
before(function () { this.applyFn = function () {
this.xDefine.reset();
this.xRequire.reset();
this.xServer.request.reset();
this.definition = modulejs._private.definitions[ID]; return this.definition.fn($, this.xServer);
};
this.xConfig = uniq.obj();
this.xDefine = sinon.stub(modulejs, 'define');
this.xRequire = sinon.stub(modulejs, 'require');
this.xServer = {
request: sinon.stub().callsArgWith(1, this.xConfig)
};
this.applyFn = function () {
this.xDefine.reset();
this.xRequire.reset();
this.xServer.request.reset();
return this.definition.fn($, this.xServer);
};
});
after(function () {
this.xDefine.restore();
this.xRequire.restore();
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
this.xDefine.restore();
assert.strictEqual(this.definition.id, ID); this.xRequire.restore();
util.restoreHtml();
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS);
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
assert.notProperty(modulejs._private.instances, ID); it('no data-module', function () {
}); this.applyFn();
assert.isFalse(this.xServer.request.called);
assert.isFalse(this.xDefine.called);
assert.isFalse(this.xRequire.called);
});
it('inits without errors', function () { it('data-module=\'test\'', function () {
$('<script/>').attr('data-module', 'test').appendTo('head');
this.applyFn();
assert.isFalse(this.xServer.request.called);
assert.isFalse(this.xDefine.called);
assert.isFalse(this.xRequire.called);
});
this.applyFn(); it('data-module=\'info\'', function () {
}); var expectedData = {
});
describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
it('no data-module', function () {
this.applyFn();
assert.isFalse(this.xServer.request.called);
assert.isFalse(this.xDefine.called);
assert.isFalse(this.xRequire.called);
});
it('data-module=\'test\'', function () {
$('<script/>').attr('data-module', 'test').appendTo('head');
this.applyFn();
assert.isFalse(this.xServer.request.called);
assert.isFalse(this.xDefine.called);
assert.isFalse(this.xRequire.called);
});
it('data-module=\'info\'', function () {
var expectedData = {
action: 'get', action: 'get',
setup: true, setup: true,
options: true, options: true,
@@ -107,25 +88,24 @@ describe('module \'' + ID + '\'', function () {
refresh: true refresh: true
}; };
$('<script/>').attr('data-module', 'info').appendTo('head'); $('<script/>').attr('data-module', 'info').appendTo('head');
this.applyFn(); this.applyFn();
assert.isTrue(this.xServer.request.calledOnce); assert.isTrue(this.xServer.request.calledOnce);
assert.isPlainObject(this.xServer.request.lastCall.args[0]); assert.isPlainObject(this.xServer.request.lastCall.args[0]);
assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData); assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData);
assert.isFunction(this.xServer.request.lastCall.args[1]); assert.isFunction(this.xServer.request.lastCall.args[1]);
assert.isTrue(this.xDefine.calledOnce); assert.isTrue(this.xDefine.calledOnce);
assert.deepEqual(this.xDefine.lastCall.args, ['config', this.xConfig]); assert.deepEqual(this.xDefine.lastCall.args, ['config', this.xConfig]);
assert.isTrue(this.xRequire.calledOnce); assert.isTrue(this.xRequire.calledOnce);
assert.deepEqual(this.xRequire.lastCall.args, ['main/info']); assert.deepEqual(this.xRequire.lastCall.args, ['main/info']);
}); });
it('data-module=\'index\'', function () { it('data-module=\'index\'', function () {
var expectedData = {
var expectedData = {
action: 'get', action: 'get',
setup: true, setup: true,
options: true, options: true,
@@ -134,22 +114,21 @@ describe('module \'' + ID + '\'', function () {
langs: true langs: true
}; };
$('<script/>').attr('data-module', 'index').appendTo('head'); $('<script/>').attr('data-module', 'index').appendTo('head');
this.applyFn(); this.applyFn();
assert.isTrue(this.xServer.request.calledOnce); assert.isTrue(this.xServer.request.calledOnce);
assert.isPlainObject(this.xServer.request.lastCall.args[0]); assert.isPlainObject(this.xServer.request.lastCall.args[0]);
assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData); assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData);
assert.isFunction(this.xServer.request.lastCall.args[1]); assert.isFunction(this.xServer.request.lastCall.args[1]);
assert.isTrue(this.xDefine.calledOnce); assert.isTrue(this.xDefine.calledOnce);
assert.deepEqual(this.xDefine.lastCall.args, ['config', this.xConfig]); assert.deepEqual(this.xDefine.lastCall.args, ['config', this.xConfig]);
assert.isTrue(this.xRequire.calledOnce); assert.isTrue(this.xRequire.calledOnce);
assert.deepEqual(this.xRequire.lastCall.args, ['main/index']); assert.deepEqual(this.xRequire.lastCall.args, ['main/index']);
});
}); });
}); });
});
}()); }());

View File

@@ -1,61 +1,47 @@
(function () { (function () {
'use strict'; var ID = 'config';
var DEPS = [];
var ID = 'config'; describe('module \'' + ID + '\'', function () {
var DEPS = []; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.applyFn = function () {
return this.definition.fn($);
before(function () { };
this.definition = modulejs._private.definitions[ID];
this.applyFn = function () {
return this.definition.fn($);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
}); assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () { it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
assert.deepEqual(this.definition.deps, DEPS); it('args for each request', function () {
}); assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('args for each request', function () { it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('inits without errors', function () {
}); this.applyFn();
});
it('has no instance', function () { it('is only dummy definition', function () {
var instance = this.applyFn();
assert.notProperty(modulejs._private.instances, ID); assert.isPlainObject(instance);
}); assert.lengthOfKeys(instance, 1);
assert.isTrue(uniq.isId(instance._uniq_id));
it('inits without errors', function () { });
this.applyFn();
});
it('is only dummy definition', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
assert.isTrue(uniq.isId(instance._uniq_id));
}); });
}); });
});
}()); }());

View File

@@ -1,127 +1,104 @@
(function () { (function () {
'use strict'; var ID = 'core/event';
var DEPS = ['_'];
var ID = 'core/event'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.applyFn = function () {
return this.definition.fn(_);
before(function () { };
this.definition = modulejs._private.definitions[ID];
this.applyFn = function () {
return this.definition.fn(_);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with 3 properties', function () {
assert.deepEqual(this.definition.deps, DEPS); var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 3);
});
}); });
it('args for each request', function () { describe('.sub()', function () {
it('is function', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); var instance = this.applyFn();
assert.isFunction(instance.sub);
});
}); });
it('has no instance', function () { describe('.unsub()', function () {
it('is function', function () {
assert.notProperty(modulejs._private.instances, ID); var instance = this.applyFn();
assert.isFunction(instance.unsub);
});
}); });
it('inits without errors', function () { describe('.pub()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.pub);
});
});
this.applyFn(); describe('works', function () {
it('works', function () {
var topic = 'topic';
var arg1 = 'arg1';
var arg2 = 'arg2';
var arg3 = 'arg3';
var subSpy = sinon.spy();
var instance = this.applyFn();
instance.sub(topic, subSpy);
instance.pub(topic, arg1, arg2, arg3);
assert.isTrue(subSpy.calledOnce);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
instance.pub(topic, arg1, arg2);
assert.isTrue(subSpy.calledTwice);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
assert.deepEqual(subSpy.secondCall.args, [arg1, arg2]);
instance.unsub(topic, subSpy);
assert.isTrue(subSpy.calledTwice);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
assert.deepEqual(subSpy.secondCall.args, [arg1, arg2]);
instance.pub(topic, arg1);
assert.isTrue(subSpy.calledTwice);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
assert.deepEqual(subSpy.secondCall.args, [arg1, arg2]);
});
}); });
}); });
describe('application', function () {
it('returns plain object with 3 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 3);
});
});
describe('.sub()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.sub);
});
});
describe('.unsub()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.unsub);
});
});
describe('.pub()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.pub);
});
});
describe('works', function () {
it('works', function () {
var topic = 'topic';
var arg1 = 'arg1';
var arg2 = 'arg2';
var arg3 = 'arg3';
var subSpy = sinon.spy();
var instance = this.applyFn();
instance.sub(topic, subSpy);
instance.pub(topic, arg1, arg2, arg3);
assert.isTrue(subSpy.calledOnce);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
instance.pub(topic, arg1, arg2);
assert.isTrue(subSpy.calledTwice);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
assert.deepEqual(subSpy.secondCall.args, [arg1, arg2]);
instance.unsub(topic, subSpy);
assert.isTrue(subSpy.calledTwice);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
assert.deepEqual(subSpy.secondCall.args, [arg1, arg2]);
instance.pub(topic, arg1);
assert.isTrue(subSpy.calledTwice);
assert.deepEqual(subSpy.firstCall.args, [arg1, arg2, arg3]);
assert.deepEqual(subSpy.secondCall.args, [arg1, arg2]);
});
});
});
}()); }());

View File

@@ -1,221 +1,188 @@
(function () { (function () {
'use strict'; var ID = 'core/format';
var DEPS = ['_'];
var ID = 'core/format'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.applyFn = function () {
return this.definition.fn(_);
before(function () { };
this.definition = modulejs._private.definitions[ID];
this.applyFn = function () {
return this.definition.fn(_);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
}); assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () { it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
assert.deepEqual(this.definition.deps, DEPS); it('args for each request', function () {
}); assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('args for each request', function () { it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('inits without errors', function () {
}); this.applyFn();
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns plain object with 4 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 4);
});
});
describe('.setDefaultMetric()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setDefaultMetric);
});
});
describe('.formatSize()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.formatSize);
});
it('defaults to decimal metric', function () {
var instance = this.applyFn();
assert.strictEqual(instance.formatSize(1024), '1 KB');
instance.setDefaultMetric(true);
assert.strictEqual(instance.formatSize(1024), '1 KiB');
instance.setDefaultMetric(false);
assert.strictEqual(instance.formatSize(1024), '1 KB');
});
describe('decimal metric', function () {
_.each([
[0, '0 B'],
[10, '10 B'],
[999, '999 B'],
[1000, '1 KB'],
[1001, '1 KB'],
[1499, '1 KB'],
[1500, '2 KB'],
[999999, '1000 KB'],
[1000000, '1.0 MB'],
[1000001, '1.0 MB'],
[1230000, '1.2 MB'],
[1250000, '1.3 MB'],
[999999999, '1000.0 MB'],
[1000000000, '1.0 GB'],
[1250000000, '1.3 GB'],
[999999999999, '1000.0 GB'],
[1000000000000, '1.0 TB'],
[1250000000000, '1.3 TB']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
instance.setDefaultMetric(false);
assert.strictEqual(instance.formatSize(arg), exp);
});
}); });
}); });
describe('binary metric', function () { describe('application', function () {
it('returns plain object with 4 properties', function () {
_.each([
[0, '0 B'],
[10, '10 B'],
[999, '999 B'],
[1000, '1000 B'],
[1001, '1001 B'],
[1024, '1 KiB'],
[1499, '1 KiB'],
[1500, '1 KiB'],
[999999, '977 KiB'],
[1000000, '977 KiB'],
[1000001, '977 KiB'],
[1230000, '1.2 MiB'],
[1250000, '1.2 MiB'],
[999999999, '953.7 MiB'],
[1000000000, '953.7 MiB'],
[1250000000, '1.2 GiB'],
[999999999999, '931.3 GiB'],
[1000000000000, '931.3 GiB'],
[1250000000000, '1.1 TiB']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
instance.setDefaultMetric(true);
assert.strictEqual(instance.formatSize(arg), exp);
});
});
});
});
describe('.setDefaultDateFormat()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setDefaultDateFormat);
});
});
describe('.formatDate()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.formatDate);
});
it('default format', function () {
var instance = this.applyFn();
assert.strictEqual(instance.formatDate(0), '');
assert.strictEqual(instance.formatDate(1000), '1970-01-01 01:00');
assert.strictEqual(instance.formatDate(-1000), '1970-01-01 00:59');
assert.strictEqual(instance.formatDate(1400000000000), '2014-05-13 18:53');
instance.setDefaultDateFormat('YYYY-MM-DD HH:mm:ss');
assert.strictEqual(instance.formatDate(0), '');
assert.strictEqual(instance.formatDate(1000), '1970-01-01 01:00:01');
assert.strictEqual(instance.formatDate(-1000), '1970-01-01 00:59:59');
assert.strictEqual(instance.formatDate(1400000000000), '2014-05-13 18:53:20');
instance.setDefaultDateFormat('H YY s');
assert.strictEqual(instance.formatDate(0), '');
assert.strictEqual(instance.formatDate(1000), '1 70 1');
assert.strictEqual(instance.formatDate(-1000), '0 70 59');
assert.strictEqual(instance.formatDate(1400000000000), '18 14 20');
});
_.each([
[0, 'YYYY-MM-DD HH:mm:ss', ''],
[1000, 'YYYY-MM-DD HH:mm:ss', '1970-01-01 01:00:01'],
[-1000, 'YYYY-MM-DD HH:mm:ss', '1970-01-01 00:59:59'],
[1400000000000, 'YYYY-MM-DD HH:mm:ss', '2014-05-13 18:53:20'],
[1400000000000, 'XYYYYXMMXDDXHHXmmXssX', 'X2014X05X13X18X53X20X'],
[1400000000000, 'YYYY YY Y MM M DD D HH H mm m ss s', '2014 14 2014 05 5 13 13 18 18 53 53 20 20']
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn(); var instance = this.applyFn();
assert.strictEqual(instance.formatDate(arg1, arg2), exp); assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 4);
});
});
describe('.setDefaultMetric()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setDefaultMetric);
});
});
describe('.formatSize()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.formatSize);
});
it('defaults to decimal metric', function () {
var instance = this.applyFn();
assert.strictEqual(instance.formatSize(1024), '1 KB');
instance.setDefaultMetric(true);
assert.strictEqual(instance.formatSize(1024), '1 KiB');
instance.setDefaultMetric(false);
assert.strictEqual(instance.formatSize(1024), '1 KB');
});
describe('decimal metric', function () {
_.each([
[0, '0 B'],
[10, '10 B'],
[999, '999 B'],
[1000, '1 KB'],
[1001, '1 KB'],
[1499, '1 KB'],
[1500, '2 KB'],
[999999, '1000 KB'],
[1000000, '1.0 MB'],
[1000001, '1.0 MB'],
[1230000, '1.2 MB'],
[1250000, '1.3 MB'],
[999999999, '1000.0 MB'],
[1000000000, '1.0 GB'],
[1250000000, '1.3 GB'],
[999999999999, '1000.0 GB'],
[1000000000000, '1.0 TB'],
[1250000000000, '1.3 TB']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
instance.setDefaultMetric(false);
assert.strictEqual(instance.formatSize(arg), exp);
});
});
});
describe('binary metric', function () {
_.each([
[0, '0 B'],
[10, '10 B'],
[999, '999 B'],
[1000, '1000 B'],
[1001, '1001 B'],
[1024, '1 KiB'],
[1499, '1 KiB'],
[1500, '1 KiB'],
[999999, '977 KiB'],
[1000000, '977 KiB'],
[1000001, '977 KiB'],
[1230000, '1.2 MiB'],
[1250000, '1.2 MiB'],
[999999999, '953.7 MiB'],
[1000000000, '953.7 MiB'],
[1250000000, '1.2 GiB'],
[999999999999, '931.3 GiB'],
[1000000000000, '931.3 GiB'],
[1250000000000, '1.1 TiB']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
instance.setDefaultMetric(true);
assert.strictEqual(instance.formatSize(arg), exp);
});
});
});
});
describe('.setDefaultDateFormat()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setDefaultDateFormat);
});
});
describe('.formatDate()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.formatDate);
});
it('default format', function () {
var instance = this.applyFn();
assert.strictEqual(instance.formatDate(0), '');
assert.strictEqual(instance.formatDate(1000), '1970-01-01 01:00');
assert.strictEqual(instance.formatDate(-1000), '1970-01-01 00:59');
assert.strictEqual(instance.formatDate(1400000000000), '2014-05-13 18:53');
instance.setDefaultDateFormat('YYYY-MM-DD HH:mm:ss');
assert.strictEqual(instance.formatDate(0), '');
assert.strictEqual(instance.formatDate(1000), '1970-01-01 01:00:01');
assert.strictEqual(instance.formatDate(-1000), '1970-01-01 00:59:59');
assert.strictEqual(instance.formatDate(1400000000000), '2014-05-13 18:53:20');
instance.setDefaultDateFormat('H YY s');
assert.strictEqual(instance.formatDate(0), '');
assert.strictEqual(instance.formatDate(1000), '1 70 1');
assert.strictEqual(instance.formatDate(-1000), '0 70 59');
assert.strictEqual(instance.formatDate(1400000000000), '18 14 20');
});
_.each([
[0, 'YYYY-MM-DD HH:mm:ss', ''],
[1000, 'YYYY-MM-DD HH:mm:ss', '1970-01-01 01:00:01'],
[-1000, 'YYYY-MM-DD HH:mm:ss', '1970-01-01 00:59:59'],
[1400000000000, 'YYYY-MM-DD HH:mm:ss', '2014-05-13 18:53:20'],
[1400000000000, 'XYYYYXMMXDDXHHXmmXssX', 'X2014X05X13X18X53X20X'],
[1400000000000, 'YYYY YY Y MM M DD D HH H mm m ss s', '2014 14 2014 05 5 13 13 18 18 53 53 20 20']
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.formatDate(arg1, arg2), exp);
});
}); });
}); });
}); });
});
}()); }());

View File

@@ -1,64 +1,49 @@
(function () { (function () {
'use strict'; var ID = 'core/langs';
var DEPS = ['_', 'config'];
var ID = 'core/langs'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'config']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xConfig = {langs: uniq.obj()};
this.applyFn = function () {
before(function () { return this.definition.fn(_, this.xConfig);
};
this.definition = modulejs._private.definitions[ID];
this.xConfig = {langs: uniq.obj()};
this.applyFn = function () {
return this.definition.fn(_, this.xConfig);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with right content', function () {
assert.deepEqual(this.definition.deps, DEPS); var instance = this.applyFn();
}); assert.isPlainObject(instance);
assert.deepEqual(instance, this.xConfig.langs);
it('args for each request', function () { });
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
}); });
}); });
describe('application', function () {
it('returns plain object with right content', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.deepEqual(instance, this.xConfig.langs);
});
});
});
}()); }());

View File

@@ -1,309 +1,266 @@
(function () { (function () {
'use strict'; var ID = 'core/location';
var DEPS = ['_', 'core/event', 'core/modernizr', 'core/settings', 'view/notification'];
var ID = 'core/location'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'core/event', 'core/modernizr', 'core/settings', 'view/notification']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xModernizr = {
history: true
};
this.xSettings = {view: {
fastBrowsing: true,
unmanagedInNewWindow: true
}};
this.xEvent = {
pub: sinon.stub(),
sub: sinon.stub()
};
this.xNotification = {
set: sinon.stub()
};
this.applyFn = function () {
this.xEvent.pub.reset();
this.xEvent.sub.reset();
this.xNotification.set.reset();
before(function () { return this.definition.fn(_, this.xEvent, this.xModernizr, this.xSettings, this.xNotification);
};
this.definition = modulejs._private.definitions[ID];
this.xModernizr = {
history: true
};
this.xSettings = {view: {
fastBrowsing: true,
unmanagedInNewWindow: true
}};
this.xEvent = {
pub: sinon.stub(),
sub: sinon.stub()
};
this.xNotification = {
set: sinon.stub()
};
this.applyFn = function () {
this.xEvent.pub.reset();
this.xEvent.sub.reset();
this.xNotification.set.reset();
return this.definition.fn(_, this.xEvent, this.xModernizr, this.xSettings, this.xNotification);
};
});
after(function () {
window.onpopstate = null;
});
beforeEach(function () {
window.onpopstate = null;
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
window.onpopstate = null;
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
window.onpopstate = null;
assert.deepEqual(this.definition.deps, DEPS);
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns plain object with 7 properties', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns plain object with 7 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 7);
});
it('sets window.onpopstate function when history and fastBrowsing', function () {
this.xModernizr.history = true;
this.xSettings.view.fastBrowsing = true;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isFunction(window.onpopstate);
});
it('sets window.onpopstate to null when not history and fastBrowsing', function () {
this.xModernizr.history = false;
this.xSettings.view.fastBrowsing = true;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isNull(window.onpopstate);
});
it('sets window.onpopstate to null when history and not fastBrowsing', function () {
this.xModernizr.history = true;
this.xSettings.view.fastBrowsing = false;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isNull(window.onpopstate);
});
it('sets window.onpopstate to null when not history and not fastBrowsing', function () {
this.xModernizr.history = false;
this.xSettings.view.fastBrowsing = false;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isNull(window.onpopstate);
});
});
describe('.forceEncoding()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.forceEncoding);
});
_.each([
['', ''],
['//', '/'],
['////', '/'],
['//a///b////c//', '/a/b/c/'],
['a b', 'a%20b'],
['ab ', 'ab%20'],
[' ab', '%20ab'],
['a!b', 'a%21b'],
['a#b', 'a%23b'],
['a$b', 'a%24b'],
['a&b', 'a%26b'],
['a\'b', 'a%27b'],
['a(b', 'a%28b'],
['a)b', 'a%29b'],
['a*b', 'a%2Ab'],
['a+b', 'a%2Bb'],
['a,b', 'a%2Cb'],
['a:b', 'a%3Ab'],
['a;b', 'a%3Bb'],
['a=b', 'a%3Db'],
['a?b', 'a%3Fb'],
['a@b', 'a%40b'],
['a[b', 'a%5Bb'],
['a]b', 'a%5Db']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn(); var instance = this.applyFn();
assert.strictEqual(instance.forceEncoding(arg), exp); assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 7);
});
it('sets window.onpopstate function when history and fastBrowsing', function () {
this.xModernizr.history = true;
this.xSettings.view.fastBrowsing = true;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isFunction(window.onpopstate);
});
it('sets window.onpopstate to null when not history and fastBrowsing', function () {
this.xModernizr.history = false;
this.xSettings.view.fastBrowsing = true;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isNull(window.onpopstate);
});
it('sets window.onpopstate to null when history and not fastBrowsing', function () {
this.xModernizr.history = true;
this.xSettings.view.fastBrowsing = false;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isNull(window.onpopstate);
});
it('sets window.onpopstate to null when not history and not fastBrowsing', function () {
this.xModernizr.history = false;
this.xSettings.view.fastBrowsing = false;
assert.isNull(window.onpopstate);
this.applyFn();
assert.isNull(window.onpopstate);
});
});
describe('.forceEncoding()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.forceEncoding);
});
_.each([
['', ''],
['//', '/'],
['////', '/'],
['//a///b////c//', '/a/b/c/'],
['a b', 'a%20b'],
['ab ', 'ab%20'],
[' ab', '%20ab'],
['a!b', 'a%21b'],
['a#b', 'a%23b'],
['a$b', 'a%24b'],
['a&b', 'a%26b'],
['a\'b', 'a%27b'],
['a(b', 'a%28b'],
['a)b', 'a%29b'],
['a*b', 'a%2Ab'],
['a+b', 'a%2Bb'],
['a,b', 'a%2Cb'],
['a:b', 'a%3Ab'],
['a;b', 'a%3Bb'],
['a=b', 'a%3Db'],
['a?b', 'a%3Fb'],
['a@b', 'a%40b'],
['a[b', 'a%5Bb'],
['a]b', 'a%5Db']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.forceEncoding(arg), exp);
});
});
});
describe('.getDomain()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getDomain);
});
it('returns document.domain', function () {
var instance = this.applyFn();
assert.strictEqual(instance.getDomain(), window.document.domain);
});
});
describe('.getAbsHref()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getAbsHref);
});
it('returns null before .setLocation()', function () {
var instance = this.applyFn();
assert.isNull(instance.getAbsHref());
});
});
describe('.getItem()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getItem);
});
});
describe('.setLocation()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setLocation);
});
});
describe('.refresh()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.refresh);
});
});
describe('.setLink()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setLink);
});
it('sets href correct', function () {
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: false,
isFolder: sinon.stub().returns(false)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.strictEqual($el.attr('href'), item.absHref);
});
it('sets target=\'_blank\' for unmanaged folders', function () {
this.xSettings.view.unmanagedInNewWindow = true;
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: false,
isFolder: sinon.stub().returns(true)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.strictEqual($el.attr('target'), '_blank');
});
it('does not set target=\'_blank\' for managed folders', function () {
this.xSettings.view.unmanagedInNewWindow = true;
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: true,
isFolder: sinon.stub().returns(true)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.isUndefined($el.attr('target'));
});
it('does not set target=\'_blank\' for unmanaged folders if disabled', function () {
this.xSettings.view.unmanagedInNewWindow = false;
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: true,
isFolder: sinon.stub().returns(true)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.isUndefined($el.attr('target'));
}); });
}); });
}); });
describe('.getDomain()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getDomain);
});
it('returns document.domain', function () {
var instance = this.applyFn();
assert.strictEqual(instance.getDomain(), window.document.domain);
});
});
describe('.getAbsHref()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getAbsHref);
});
it('returns null before .setLocation()', function () {
var instance = this.applyFn();
assert.isNull(instance.getAbsHref());
});
});
describe('.getItem()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getItem);
});
});
describe('.setLocation()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setLocation);
});
});
describe('.refresh()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.refresh);
});
});
describe('.setLink()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.setLink);
});
it('sets href correct', function () {
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: false,
isFolder: sinon.stub().returns(false)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.strictEqual($el.attr('href'), item.absHref);
});
it('sets target=\'_blank\' for unmanaged folders', function () {
this.xSettings.view.unmanagedInNewWindow = true;
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: false,
isFolder: sinon.stub().returns(true)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.strictEqual($el.attr('target'), '_blank');
});
it('does not set target=\'_blank\' for managed folders', function () {
this.xSettings.view.unmanagedInNewWindow = true;
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: true,
isFolder: sinon.stub().returns(true)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.isUndefined($el.attr('target'));
});
it('does not set target=\'_blank\' for unmanaged folders if disabled', function () {
this.xSettings.view.unmanagedInNewWindow = false;
var $el = $('<a/>');
var item = {
absHref: uniq.id(),
isManaged: true,
isFolder: sinon.stub().returns(true)
};
var setLink = this.applyFn().setLink;
setLink($el, item);
assert.isUndefined($el.attr('target'));
});
});
});
}()); }());

View File

@@ -1,90 +1,69 @@
(function () { (function () {
'use strict'; var ID = 'core/modernizr';
var DEPS = [];
var ID = 'core/modernizr'; describe('module \'' + ID + '\'', function () {
var DEPS = []; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.applyFn = function () {
return this.definition.fn();
before(function () { };
this.definition = modulejs._private.definitions[ID];
this.applyFn = function () {
return this.definition.fn();
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with 3 properties', function () {
assert.deepEqual(this.definition.deps, DEPS); var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOf(_.keys(instance), 3);
});
}); });
it('args for each request', function () { describe('.canvas', function () {
it('is boolean', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); var instance = this.applyFn();
assert.isBoolean(instance.canvas);
});
}); });
it('has no instance', function () { describe('.history', function () {
it('is boolean', function () {
assert.notProperty(modulejs._private.instances, ID); var instance = this.applyFn();
assert.isBoolean(instance.history);
});
}); });
it('inits without errors', function () { describe('.localstorage', function () {
it('is boolean', function () {
this.applyFn(); var instance = this.applyFn();
assert.isBoolean(instance.localstorage);
});
}); });
}); });
describe('application', function () {
it('returns plain object with 3 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOf(_.keys(instance), 3);
});
});
describe('.canvas', function () {
it('is boolean', function () {
var instance = this.applyFn();
assert.isBoolean(instance.canvas);
});
});
describe('.history', function () {
it('is boolean', function () {
var instance = this.applyFn();
assert.isBoolean(instance.history);
});
});
describe('.localstorage', function () {
it('is boolean', function () {
var instance = this.applyFn();
assert.isBoolean(instance.localstorage);
});
});
});
}()); }());

View File

@@ -1,113 +1,92 @@
(function () { (function () {
'use strict'; var ID = 'core/resource';
var DEPS = ['_', 'config', 'core/settings'];
var ID = 'core/resource'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'config', 'core/settings']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xConfig = {
theme: {
before(function () { a: 'myTheme/a.svg',
b: 'myTheme/b.jpg'
this.definition = modulejs._private.definitions[ID]; }
};
this.xConfig = { this.xSettings = {publicHref: uniq.path('/publicHref/')};
theme: { this.applyFn = function () {
a: 'myTheme/a.svg', return this.definition.fn(_, this.xConfig, this.xSettings);
b: 'myTheme/b.jpg' };
}
};
this.xSettings = {publicHref: uniq.path('/publicHref/')};
this.applyFn = function () {
return this.definition.fn(_, this.xConfig, this.xSettings);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with 2 properties', function () {
assert.deepEqual(this.definition.deps, DEPS); var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
}); });
it('args for each request', function () { describe('.image()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.image);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('works', function () {
var instance = this.applyFn();
var ui = this.xSettings.publicHref + 'images/ui/';
assert.strictEqual(instance.image(), ui + 'undefined.svg');
assert.strictEqual(instance.image(1), ui + '1.svg');
assert.strictEqual(instance.image(''), ui + '.svg');
assert.strictEqual(instance.image('a'), ui + 'a.svg');
});
}); });
it('has no instance', function () { describe('.icon()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.icon);
});
assert.notProperty(modulejs._private.instances, ID); it('works', function () {
}); var instance = this.applyFn();
var themes = this.xSettings.publicHref + 'images/themes/';
it('inits without errors', function () { assert.strictEqual(instance.icon(''), themes + 'default/file.svg');
assert.strictEqual(instance.icon('a'), themes + 'myTheme/a.svg');
this.applyFn(); assert.strictEqual(instance.icon('a-sub'), themes + 'myTheme/a.svg');
assert.strictEqual(instance.icon('b'), themes + 'myTheme/b.jpg');
assert.strictEqual(instance.icon('x'), themes + 'default/x.svg');
assert.strictEqual(instance.icon('y'), themes + 'default/file.svg');
assert.strictEqual(instance.icon('y-sub'), themes + 'default/file.svg');
});
}); });
}); });
describe('application', function () {
it('returns plain object with 2 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
});
describe('.image()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.image);
});
it('works', function () {
var instance = this.applyFn();
var ui = this.xSettings.publicHref + 'images/ui/';
assert.strictEqual(instance.image(), ui + 'undefined.svg');
assert.strictEqual(instance.image(1), ui + '1.svg');
assert.strictEqual(instance.image(''), ui + '.svg');
assert.strictEqual(instance.image('a'), ui + 'a.svg');
});
});
describe('.icon()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.icon);
});
it('works', function () {
var instance = this.applyFn();
var themes = this.xSettings.publicHref + 'images/themes/';
assert.strictEqual(instance.icon(''), themes + 'default/file.svg');
assert.strictEqual(instance.icon('a'), themes + 'myTheme/a.svg');
assert.strictEqual(instance.icon('a-sub'), themes + 'myTheme/a.svg');
assert.strictEqual(instance.icon('b'), themes + 'myTheme/b.jpg');
assert.strictEqual(instance.icon('x'), themes + 'default/x.svg');
assert.strictEqual(instance.icon('y'), themes + 'default/file.svg');
assert.strictEqual(instance.icon('y-sub'), themes + 'default/file.svg');
});
});
});
}()); }());

View File

@@ -1,193 +1,169 @@
(function () { (function () {
'use strict'; var ID = 'core/server';
var DEPS = ['_', '$'];
var $submitEl;
var ID = 'core/server'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', '$']; before(function () {
var $submitEl; this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xAjaxResult = {
done: sinon.stub().returnsThis(),
before(function () { fail: sinon.stub().returnsThis(),
always: sinon.stub().returnsThis()
this.definition = modulejs._private.definitions[ID];
this.xAjaxResult = {
done: sinon.stub().returnsThis(),
fail: sinon.stub().returnsThis(),
always: sinon.stub().returnsThis()
};
this.xAjax = sinon.stub($, 'ajax').returns(this.xAjaxResult);
this.xSubmit = sinon.stub($.fn, 'submit', function () {
$submitEl = this;
return this;
});
this.applyFn = function () {
this.xAjaxResult.done.reset();
this.xAjaxResult.fail.reset();
this.xAjaxResult.always.reset();
this.xAjax.reset();
this.xSubmit.reset();
$submitEl = undefined;
return this.definition.fn(_, $);
};
});
after(function () {
this.xAjax.restore();
this.xSubmit.restore();
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns plain object with 2 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
});
describe('.request()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.request);
});
it('done() works', function () {
var instance = this.applyFn();
var xData = uniq.obj();
var xResult = uniq.obj();
var spy = sinon.spy();
var res = instance.request(xData, spy);
assert.isUndefined(res);
assert.isTrue(this.xAjax.calledOnce);
assert.deepEqual(this.xAjax.lastCall.args, [{
url: '?',
data: xData,
type: 'post',
dataType: 'json'
}]);
assert.isTrue(this.xAjaxResult.done.calledOnce);
assert.isTrue(this.xAjaxResult.fail.calledOnce);
assert.isFalse(spy.called);
this.xAjaxResult.done.callArgWith(0, xResult);
assert.isTrue(spy.calledOnce);
assert.deepEqual(spy.firstCall.args, [xResult]);
});
it('fail() works', function () {
var instance = this.applyFn();
var xData = uniq.obj();
var spy = sinon.spy();
var res = instance.request(xData, spy);
assert.isUndefined(res);
assert.isTrue(this.xAjax.calledOnce);
assert.deepEqual(this.xAjax.lastCall.args, [{
url: '?',
data: xData,
type: 'post',
dataType: 'json'
}]);
assert.isTrue(this.xAjaxResult.done.calledOnce);
assert.isTrue(this.xAjaxResult.fail.calledOnce);
assert.isFalse(spy.called);
this.xAjaxResult.fail.callArg(0);
assert.isTrue(spy.calledOnce);
assert.deepEqual(spy.firstCall.args, []);
});
});
describe('.formRequest()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.formRequest);
});
it('works', function () {
var instance = this.applyFn();
var xData = {
a: uniq.id(),
b: uniq.id()
}; };
var res = instance.formRequest(xData); this.xAjax = sinon.stub($, 'ajax').returns(this.xAjaxResult);
this.xSubmit = sinon.stub($.fn, 'submit', function () {
$submitEl = this;
return this;
});
assert.isUndefined(res); this.applyFn = function () {
this.xAjaxResult.done.reset();
this.xAjaxResult.fail.reset();
this.xAjaxResult.always.reset();
this.xAjax.reset();
this.xSubmit.reset();
$submitEl = undefined;
assert.isTrue(this.xSubmit.calledOnce); return this.definition.fn(_, $);
};
});
assert.lengthOf($submitEl, 1); after(function () {
assert.strictEqual($submitEl.get(0).tagName.toLowerCase(), 'form'); this.xAjax.restore();
assert.strictEqual($submitEl.attr('method'), 'post'); this.xSubmit.restore();
assert.strictEqual($submitEl.attr('style').replace(/\s+/g, ''), 'display:none;'); });
assert.strictEqual($submitEl.attr('action'), '?');
var $children = $submitEl.children(); describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.lengthOf($children, 2); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
assert.strictEqual($children.eq(0).attr('type'), 'hidden'); it('requires correct', function () {
assert.strictEqual($children.eq(0).attr('name'), 'a'); assert.deepEqual(this.definition.deps, DEPS);
assert.strictEqual($children.eq(0).attr('value'), xData.a); });
assert.strictEqual($children.eq(1).attr('type'), 'hidden'); it('args for each request', function () {
assert.strictEqual($children.eq(1).attr('name'), 'b'); assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
assert.strictEqual($children.eq(1).attr('value'), xData.b); });
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns plain object with 2 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
});
describe('.request()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.request);
});
it('done() works', function () {
var instance = this.applyFn();
var xData = uniq.obj();
var xResult = uniq.obj();
var spy = sinon.spy();
var res = instance.request(xData, spy);
assert.isUndefined(res);
assert.isTrue(this.xAjax.calledOnce);
assert.deepEqual(this.xAjax.lastCall.args, [{
url: '?',
data: xData,
type: 'post',
dataType: 'json'
}]);
assert.isTrue(this.xAjaxResult.done.calledOnce);
assert.isTrue(this.xAjaxResult.fail.calledOnce);
assert.isFalse(spy.called);
this.xAjaxResult.done.callArgWith(0, xResult);
assert.isTrue(spy.calledOnce);
assert.deepEqual(spy.firstCall.args, [xResult]);
});
it('fail() works', function () {
var instance = this.applyFn();
var xData = uniq.obj();
var spy = sinon.spy();
var res = instance.request(xData, spy);
assert.isUndefined(res);
assert.isTrue(this.xAjax.calledOnce);
assert.deepEqual(this.xAjax.lastCall.args, [{
url: '?',
data: xData,
type: 'post',
dataType: 'json'
}]);
assert.isTrue(this.xAjaxResult.done.calledOnce);
assert.isTrue(this.xAjaxResult.fail.calledOnce);
assert.isFalse(spy.called);
this.xAjaxResult.fail.callArg(0);
assert.isTrue(spy.calledOnce);
assert.deepEqual(spy.firstCall.args, []);
});
});
describe('.formRequest()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.formRequest);
});
it('works', function () {
var instance = this.applyFn();
var xData = {
a: uniq.id(),
b: uniq.id()
};
var res = instance.formRequest(xData);
assert.isUndefined(res);
assert.isTrue(this.xSubmit.calledOnce);
assert.lengthOf($submitEl, 1);
assert.strictEqual($submitEl.get(0).tagName.toLowerCase(), 'form');
assert.strictEqual($submitEl.attr('method'), 'post');
assert.strictEqual($submitEl.attr('style').replace(/\s+/g, ''), 'display:none;');
assert.strictEqual($submitEl.attr('action'), '?');
var $children = $submitEl.children();
assert.lengthOf($children, 2);
assert.strictEqual($children.eq(0).attr('type'), 'hidden');
assert.strictEqual($children.eq(0).attr('name'), 'a');
assert.strictEqual($children.eq(0).attr('value'), xData.a);
assert.strictEqual($children.eq(1).attr('type'), 'hidden');
assert.strictEqual($children.eq(1).attr('name'), 'b');
assert.strictEqual($children.eq(1).attr('value'), xData.b);
});
}); });
}); });
});
}()); }());

View File

@@ -1,104 +1,83 @@
(function () { (function () {
'use strict'; var ID = 'core/settings';
var DEPS = ['_', 'config'];
var ID = 'core/settings'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'config']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xConfig = {
options: {
before(function () { someOptions: uniq.obj(),
otherOptions: uniq.obj(),
this.definition = modulejs._private.definitions[ID]; more: uniq.obj()
},
this.xConfig = { setup: {
options: { PUBLIC_HREF: uniq.id(),
someOptions: uniq.obj(), ROOT_HREF: uniq.id()
otherOptions: uniq.obj(), }
more: uniq.obj() };
}, this.applyFn = function () {
setup: { return this.definition.fn(_, this.xConfig);
PUBLIC_HREF: uniq.id(), };
ROOT_HREF: uniq.id()
}
};
this.applyFn = function () {
return this.definition.fn(_, this.xConfig);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with properties', function () {
assert.deepEqual(this.definition.deps, DEPS); var instance = this.applyFn();
assert.isPlainObject(instance);
assert.isAbove(_.keys(instance).length, 0);
});
}); });
it('args for each request', function () { describe('publics', function () {
it('extended from options', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); var instance = this.applyFn();
assert.strictEqual(instance.someOptions, this.xConfig.options.someOptions);
assert.strictEqual(instance.otherOptions, this.xConfig.options.otherOptions);
assert.strictEqual(instance.more, this.xConfig.options.more);
assert.strictEqual(_.keys(instance).length, _.keys(this.xConfig.options).length + 2);
});
}); });
it('has no instance', function () { describe('.publicHref', function () {
it('set correct', function () {
assert.notProperty(modulejs._private.instances, ID); var instance = this.applyFn();
assert.strictEqual(instance.publicHref, this.xConfig.setup.PUBLIC_HREF);
});
}); });
it('inits without errors', function () { describe('.rootHref', function () {
it('set correct', function () {
this.applyFn(); var instance = this.applyFn();
assert.strictEqual(instance.rootHref, this.xConfig.setup.ROOT_HREF);
});
}); });
}); });
describe('application', function () {
it('returns plain object with properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.isAbove(_.keys(instance).length, 0);
});
});
describe('publics', function () {
it('extended from options', function () {
var instance = this.applyFn();
assert.strictEqual(instance.someOptions, this.xConfig.options.someOptions);
assert.strictEqual(instance.otherOptions, this.xConfig.options.otherOptions);
assert.strictEqual(instance.more, this.xConfig.options.more);
assert.strictEqual(_.keys(instance).length, _.keys(this.xConfig.options).length + 2);
});
});
describe('.publicHref', function () {
it('set correct', function () {
var instance = this.applyFn();
assert.strictEqual(instance.publicHref, this.xConfig.setup.PUBLIC_HREF);
});
});
describe('.rootHref', function () {
it('set correct', function () {
var instance = this.applyFn();
assert.strictEqual(instance.rootHref, this.xConfig.setup.ROOT_HREF);
});
});
});
}()); }());

View File

@@ -1,131 +1,108 @@
(function () { (function () {
'use strict'; var ID = 'core/store';
var DEPS = ['core/modernizr'];
var ID = 'core/store'; describe('module \'' + ID + '\'', function () {
var DEPS = ['core/modernizr']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.storeKey = '_h5ai';
this.xModernizr = {localstorage: true};
before(function () { this.applyFn = function () {
return this.definition.fn(this.xModernizr);
this.definition = modulejs._private.definitions[ID]; };
this.storeKey = '_h5ai';
this.xModernizr = {localstorage: true};
this.applyFn = function () {
return this.definition.fn(this.xModernizr);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS);
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns plain object with 2 properties', function () {
assert.notProperty(modulejs._private.instances, ID); var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
}); });
it('inits without errors', function () { describe('.put()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.put);
});
});
this.applyFn(); describe('.get()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.get);
});
});
describe('works', function () {
it('works', function () {
var key1 = 'test1';
var value1 = '1234';
var key2 = 'test2';
var value2 = '5678';
var instance = this.applyFn();
assert.isNull(window.localStorage.getItem(this.storeKey));
assert.isUndefined(instance.get(key1));
assert.isNull(window.localStorage.getItem(this.storeKey));
assert.isUndefined(instance.put(key1, value1));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234"}');
assert.strictEqual(instance.get(key1), value1);
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234"}');
assert.isUndefined(instance.put(key1, undefined));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{}');
assert.isUndefined(instance.get(key1));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{}');
assert.isUndefined(instance.put(key1, value1));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234"}');
assert.isUndefined(instance.put(key2, value2));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234","test2":"5678"}');
assert.isUndefined(instance.put(key1, undefined));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test2":"5678"}');
});
}); });
}); });
describe('application', function () {
it('returns plain object with 2 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
});
describe('.put()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.put);
});
});
describe('.get()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.get);
});
});
describe('works', function () {
it('works', function () {
var key1 = 'test1';
var value1 = '1234';
var key2 = 'test2';
var value2 = '5678';
var instance = this.applyFn();
assert.isNull(window.localStorage.getItem(this.storeKey));
assert.isUndefined(instance.get(key1));
assert.isNull(window.localStorage.getItem(this.storeKey));
assert.isUndefined(instance.put(key1, value1));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234"}');
assert.strictEqual(instance.get(key1), value1);
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234"}');
assert.isUndefined(instance.put(key1, undefined));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{}');
assert.isUndefined(instance.get(key1));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{}');
assert.isUndefined(instance.put(key1, value1));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234"}');
assert.isUndefined(instance.put(key2, value2));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test1":"1234","test2":"5678"}');
assert.isUndefined(instance.put(key1, undefined));
assert.strictEqual(window.localStorage.getItem(this.storeKey), '{"test2":"5678"}');
});
});
});
}()); }());

View File

@@ -1,103 +1,84 @@
(function () { (function () {
'use strict'; var ID = 'core/types';
var DEPS = ['_', 'config'];
var ID = 'core/types'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'config']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xConfig = {types: {
a: ['*.a', '*.aa'],
before(function () { b: ['*.b'],
c: ['*.c']
this.definition = modulejs._private.definitions[ID]; }};
this.applyFn = function () {
this.xConfig = {types: { return this.definition.fn(_, this.xConfig);
a: ['*.a', '*.aa'], };
b: ['*.b'],
c: ['*.c']
}};
this.applyFn = function () {
return this.definition.fn(_, this.xConfig);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with 1 property', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns plain object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
});
describe('.getType()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getType);
});
_.each([
['file.a', 'a'],
['file.aa', 'a'],
['foo.b', 'b'],
['some/path/file.c', 'c'],
['/some/abs/path/file.c', 'c'],
['file.x', 'file'],
['foo', 'file'],
['some/path/foo', 'file'],
['/some/path/foo', 'file'],
['foo/', 'folder'],
['/', 'folder'],
['some/path/foo/', 'folder'],
['/some/path/foo/', 'folder']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn(); var instance = this.applyFn();
assert.strictEqual(instance.getType(arg), exp); assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
});
describe('.getType()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.getType);
});
_.each([
['file.a', 'a'],
['file.aa', 'a'],
['foo.b', 'b'],
['some/path/file.c', 'c'],
['/some/abs/path/file.c', 'c'],
['file.x', 'file'],
['foo', 'file'],
['some/path/foo', 'file'],
['/some/path/foo', 'file'],
['foo/', 'folder'],
['/', 'folder'],
['some/path/foo/', 'folder'],
['/some/path/foo/', 'folder']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.getType(arg), exp);
});
}); });
}); });
}); });
});
}()); }());

View File

@@ -1,232 +1,201 @@
(function () { (function () {
'use strict'; var ID = 'core/util';
var DEPS = ['_'];
var ID = 'core/util'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.applyFn = function () {
return this.definition.fn(_);
before(function () { };
this.definition = modulejs._private.definitions[ID];
this.applyFn = function () {
return this.definition.fn(_);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with 4 properties', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns plain object with 4 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 4);
});
});
describe('.regularCmpFn()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.regularCmpFn);
});
_.each([
[0, 0, 0],
[1, 0, 1],
[1, 2, -1],
['a', 'a', 0],
['b', 'a', 1],
['a', 'b', -1],
['a 2', 'a 10', 1]
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn(); var instance = this.applyFn();
assert.strictEqual(instance.regularCmpFn(arg1, arg2), exp); assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 4);
});
});
describe('.regularCmpFn()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.regularCmpFn);
});
_.each([
[0, 0, 0],
[1, 0, 1],
[1, 2, -1],
['a', 'a', 0],
['b', 'a', 1],
['a', 'b', -1],
['a 2', 'a 10', 1]
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.regularCmpFn(arg1, arg2), exp);
});
});
});
describe('.naturalCmpFn()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.naturalCmpFn);
});
_.each([
[0, 0, 0],
[1, 0, 1],
[1, 2, -1],
['a', 'a', 0],
['b', 'a', 1],
['a', 'b', -1],
['a 2', 'a 10', -1]
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.naturalCmpFn(arg1, arg2), exp);
});
});
});
describe('.escapePattern()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.escapePattern);
});
_.each([
['a', 'a'],
['1', '1'],
['ä', 'ä'],
['~', '~'],
[':', ':'],
['_', '_'],
['<', '<'],
['-', '\\-'],
['[', '\\['],
[']', '\\]'],
['{', '\\{'],
['}', '\\}'],
['(', '\\('],
[')', '\\)'],
['*', '\\*'],
['+', '\\+'],
['?', '\\?'],
['.', '\\.'],
[',', '\\,'],
['\\', '\\\\'],
['$', '\\$'],
['^', '\\^'],
['|', '\\|'],
['#', '\\#'],
[' ', '\\ '],
['-[]{}()*+?.,\\$^|# ', '\\-\\[\\]\\{\\}\\(\\)\\*\\+\\?\\.\\,\\\\\\$\\^\\|\\#\\ '],
['abc123', 'abc123'],
['a.b+c*1', 'a\\.b\\+c\\*1']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.escapePattern(arg), exp);
});
});
});
describe('.parsePattern()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.parsePattern);
});
_.each([
['a', false, 'a'],
['1', false, '1'],
['ä', false, 'ä'],
['~', false, '~'],
[':', false, ':'],
['_', false, '_'],
['<', false, '<'],
['-', false, '\\-'],
['[', false, '\\['],
[']', false, '\\]'],
['{', false, '\\{'],
['}', false, '\\}'],
['(', false, '\\('],
[')', false, '\\)'],
['*', false, '\\*'],
['+', false, '\\+'],
['?', false, '\\?'],
['.', false, '\\.'],
[',', false, '\\,'],
['\\', false, '\\\\'],
['$', false, '\\$'],
['^', false, '\\^'],
['|', false, '\\|'],
['#', false, '\\#'],
[' ', false, '\\ '],
['-[]{}()*+?.,\\$^|# ', false, '\\-\\[\\]\\{\\}\\(\\)\\*\\+\\?\\.\\,\\\\\\$\\^\\|\\#\\ '],
['abc123', false, 'abc123'],
['a.b+c*1', false, 'a\\.b\\+c\\*1'],
['abc', true, 'a.*?b.*?c'],
['abc def', true, 'a.*?b.*?c|d.*?e.*?f'],
['*#a b.=', true, '\\*.*?\\#.*?a|b.*?\\..*?='],
['re:.', true, '.'],
[' .', true, '\\.'],
['re: .', true, ' .']
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.parsePattern(arg1, arg2), exp);
});
}); });
}); });
}); });
describe('.naturalCmpFn()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.naturalCmpFn);
});
_.each([
[0, 0, 0],
[1, 0, 1],
[1, 2, -1],
['a', 'a', 0],
['b', 'a', 1],
['a', 'b', -1],
['a 2', 'a 10', -1]
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.naturalCmpFn(arg1, arg2), exp);
});
});
});
describe('.escapePattern()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.escapePattern);
});
_.each([
['a', 'a'],
['1', '1'],
['ä', 'ä'],
['~', '~'],
[':', ':'],
['_', '_'],
['<', '<'],
['-', '\\-'],
['[', '\\['],
[']', '\\]'],
['{', '\\{'],
['}', '\\}'],
['(', '\\('],
[')', '\\)'],
['*', '\\*'],
['+', '\\+'],
['?', '\\?'],
['.', '\\.'],
[',', '\\,'],
['\\', '\\\\'],
['$', '\\$'],
['^', '\\^'],
['|', '\\|'],
['#', '\\#'],
[' ', '\\ '],
['-[]{}()*+?.,\\$^|# ', '\\-\\[\\]\\{\\}\\(\\)\\*\\+\\?\\.\\,\\\\\\$\\^\\|\\#\\ '],
['abc123', 'abc123'],
['a.b+c*1', 'a\\.b\\+c\\*1']
], function (data) {
var arg = data[0];
var exp = data[1];
it(arg + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.escapePattern(arg), exp);
});
});
});
describe('.parsePattern()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.parsePattern);
});
_.each([
['a', false, 'a'],
['1', false, '1'],
['ä', false, 'ä'],
['~', false, '~'],
[':', false, ':'],
['_', false, '_'],
['<', false, '<'],
['-', false, '\\-'],
['[', false, '\\['],
[']', false, '\\]'],
['{', false, '\\{'],
['}', false, '\\}'],
['(', false, '\\('],
[')', false, '\\)'],
['*', false, '\\*'],
['+', false, '\\+'],
['?', false, '\\?'],
['.', false, '\\.'],
[',', false, '\\,'],
['\\', false, '\\\\'],
['$', false, '\\$'],
['^', false, '\\^'],
['|', false, '\\|'],
['#', false, '\\#'],
[' ', false, '\\ '],
['-[]{}()*+?.,\\$^|# ', false, '\\-\\[\\]\\{\\}\\(\\)\\*\\+\\?\\.\\,\\\\\\$\\^\\|\\#\\ '],
['abc123', false, 'abc123'],
['a.b+c*1', false, 'a\\.b\\+c\\*1'],
['abc', true, 'a.*?b.*?c'],
['abc def', true, 'a.*?b.*?c|d.*?e.*?f'],
['*#a b.=', true, '\\*.*?\\#.*?a|b.*?\\..*?='],
['re:.', true, '.'],
[' .', true, '\\.'],
['re: .', true, ' .']
], function (data) {
var arg1 = data[0];
var arg2 = data[1];
var exp = data[2];
it(arg1 + ', ' + arg2 + ' => ' + exp, function () {
var instance = this.applyFn();
assert.strictEqual(instance.parsePattern(arg1, arg2), exp);
});
});
});
});
}()); }());

View File

@@ -1,125 +1,104 @@
(function () { (function () {
'use strict'; var ID = 'ext/title';
var DEPS = ['_', 'core/event', 'core/settings'];
var ID = 'ext/title'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'core/event', 'core/settings']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xEvent = {
sub: sinon.stub()
};
this.xSettings = {title: {
enabled: true
}};
before(function () { this.applyFn = function () {
this.xEvent.sub.reset();
this.definition = modulejs._private.definitions[ID]; return this.definition.fn(_, this.xEvent, this.xSettings);
};
this.xEvent = {
sub: sinon.stub()
};
this.xSettings = {title: {
enabled: true
}};
this.applyFn = function () {
this.xEvent.sub.reset();
return this.definition.fn(_, this.xEvent, this.xSettings);
};
});
after(function () {
util.restoreHtml();
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.deepEqual(this.definition.deps, DEPS); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('args for each request', function () { describe('application', function () {
it('returns undefined', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); var instance = this.applyFn();
}); assert.isUndefined(instance);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
it('subscribes to location.changed', function () {
this.xSettings.title.enabled = true;
this.applyFn();
assert.isTrue(this.xEvent.sub.calledOnce);
assert.strictEqual(this.xEvent.sub.lastCall.args[0], 'location.changed');
});
it('does not subscribe to events if disabled', function () {
this.xSettings.title.enabled = false;
this.applyFn();
assert.isFalse(this.xEvent.sub.called);
});
});
describe('sets title on location.changed', function () {
_.each([
[''],
['a', 'a'],
['a', 'b', 'b - a > b'],
['a', 'b', 'c', 'c - a > b > c']
], function (data) {
var labels = data.slice(0, -1);
var exp = data.slice(-1)[0];
it(labels + ' => ' + exp, function () {
it('subscribes to location.changed', function () {
this.xSettings.title.enabled = true; this.xSettings.title.enabled = true;
this.applyFn(); this.applyFn();
assert.isTrue(this.xEvent.sub.calledOnce);
assert.strictEqual(this.xEvent.sub.lastCall.args[0], 'location.changed');
});
var fn = this.xEvent.sub.lastCall.args[1]; it('does not subscribe to events if disabled', function () {
var crumb = _.map(labels, function (x) { return {label: x}; }); this.xSettings.title.enabled = false;
var item = {
getCrumb: sinon.stub().returns(crumb)
};
fn(item); this.applyFn();
assert.isFalse(this.xEvent.sub.called);
});
});
assert.isTrue(item.getCrumb.calledOnce); describe('sets title on location.changed', function () {
assert.strictEqual(document.title, exp); _.each([
[''],
['a', 'a'],
['a', 'b', 'b - a > b'],
['a', 'b', 'c', 'c - a > b > c']
], function (data) {
var labels = data.slice(0, -1);
var exp = data.slice(-1)[0];
it(labels + ' => ' + exp, function () {
this.xSettings.title.enabled = true;
this.applyFn();
var fn = this.xEvent.sub.lastCall.args[1];
var crumb = _.map(labels, function (x) { return {label: x}; });
var item = {
getCrumb: sinon.stub().returns(crumb)
};
fn(item);
assert.isTrue(item.getCrumb.calledOnce);
assert.strictEqual(document.title, exp);
});
}); });
}); });
}); });
});
}()); }());

View File

@@ -1,39 +1,29 @@
(function () { (function () {
'use strict'; describe('libs', function () {
var libs = {
describe('libs', function () {
var libs = {
_: window._, _: window._,
$: window.jQuery, $: window.jQuery,
marked: window.marked, marked: window.marked,
prism: window.Prism prism: window.Prism
}; };
_.each(libs, function (lib, id) { _.each(libs, function (lib, id) {
describe('module \'' + id + '\'', function () {
it('is defined', function () {
assert.isDefined(modulejs._private.definitions[id]);
});
describe('module \'' + id + '\'', function () { it('has no instance', function () {
assert.notProperty(modulejs._private.instances, id);
});
it('is defined', function () { it('returns global lib', function () {
var definition = modulejs._private.definitions[id];
assert.isDefined(modulejs._private.definitions[id]); var instance = definition.fn();
}); assert.isDefined(instance);
assert.strictEqual(instance, lib);
it('has no instance', function () { });
assert.notProperty(modulejs._private.instances, id);
});
it('returns global lib', function () {
var definition = modulejs._private.definitions[id];
var instance = definition.fn();
assert.isDefined(instance);
assert.strictEqual(instance, lib);
}); });
}); });
}); });
});
}()); }());

View File

@@ -1,125 +1,102 @@
(function () { (function () {
'use strict'; var ID = 'main/index';
var DEPS = ['_', 'core/location'];
var ID = 'main/index'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'core/location']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xLocation = {setLocation: sinon.stub()};
this.xRequire = sinon.stub(modulejs, 'require');
before(function () { this.applyFn = function () {
this.xLocation.setLocation.reset();
this.definition = modulejs._private.definitions[ID]; this.xRequire.reset();
return this.definition.fn(_, this.xLocation);
this.xLocation = {setLocation: sinon.stub()}; };
this.xRequire = sinon.stub(modulejs, 'require');
this.applyFn = function () {
this.xLocation.setLocation.reset();
this.xRequire.reset();
return this.definition.fn(_, this.xLocation);
};
});
after(function () {
this.xRequire.restore();
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
this.xRequire.restore();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.deepEqual(this.definition.deps, DEPS); it('has correct id', function () {
}); assert.strictEqual(this.definition.id, ID);
});
it('args for each request', function () { it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('args for each request', function () {
}); assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () { it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
assert.notProperty(modulejs._private.instances, ID); it('inits without errors', function () {
}); this.applyFn();
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
it('requires view/viewmode', function () {
this.applyFn();
assert.isTrue(this.xRequire.calledWithExactly('view/viewmode'));
});
it('requires all extensions', function () {
this.applyFn();
var re = /^ext\//;
var self = this;
_.each(modulejs.state(), function (state, id) {
if (re.test(id)) {
assert.isTrue(self.xRequire.calledWithExactly(id));
}
}); });
}); });
it('requires only views and extensions', function () { describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
this.applyFn(); it('requires view/viewmode', function () {
assert.isTrue(this.xRequire.alwaysCalledWithMatch(/^(view|ext)\//)); this.applyFn();
}); assert.isTrue(this.xRequire.calledWithExactly('view/viewmode'));
});
it('requires views before extensions', function () { it('requires all extensions', function () {
this.applyFn();
var re = /^ext\//;
var self = this;
this.applyFn(); _.each(modulejs.state(), function (state, id) {
var foundExtension = false; if (re.test(id)) {
var reView = /^view\//; assert.isTrue(self.xRequire.calledWithExactly(id));
var reExt = /^ext\//; }
});
});
_.each(this.xRequire.args, function (args) { it('requires only views and extensions', function () {
this.applyFn();
assert.isTrue(this.xRequire.alwaysCalledWithMatch(/^(view|ext)\//));
});
if (foundExtension) { it('requires views before extensions', function () {
assert.match(args[0], reExt); this.applyFn();
} else if (reExt.test(args[0])) { var foundExtension = false;
foundExtension = true; var reView = /^view\//;
} else { var reExt = /^ext\//;
assert.match(args[0], reView);
} _.each(this.xRequire.args, function (args) {
if (foundExtension) {
assert.match(args[0], reExt);
} else if (reExt.test(args[0])) {
foundExtension = true;
} else {
assert.match(args[0], reView);
}
});
});
it('calls setLocation with current href, keeping browser url', function () {
this.applyFn();
assert.isTrue(this.xLocation.setLocation.calledOnce);
assert.deepEqual(this.xLocation.setLocation.firstCall.args, [document.location.href, true]);
assert.isTrue(this.xLocation.setLocation.calledAfter(this.xRequire));
}); });
}); });
it('calls setLocation with current href, keeping browser url', function () {
this.applyFn();
assert.isTrue(this.xLocation.setLocation.calledOnce);
assert.deepEqual(this.xLocation.setLocation.firstCall.args, [document.location.href, true]);
assert.isTrue(this.xLocation.setLocation.calledAfter(this.xRequire));
});
}); });
});
}()); }());

View File

@@ -1,213 +1,180 @@
(function () { (function () {
'use strict'; var ID = 'main/info';
var DEPS = ['$', 'config', 'core/resource', 'core/server'];
var ID = 'main/info'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$', 'config', 'core/resource', 'core/server']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xConfig = {
setup: {
VERSION: uniq.id()
},
options: {}
};
this.xResource = {
image: sinon.stub()
};
this.xServer = {
request: sinon.stub()
};
before(function () { this.applyFn = function () {
this.xServer.request.reset();
this.definition = modulejs._private.definitions[ID]; return this.definition.fn($, this.xConfig, this.xResource, this.xServer);
};
this.xConfig = {
setup: {
VERSION: uniq.id()
},
options: {}
};
this.xResource = {
image: sinon.stub()
};
this.xServer = {
request: sinon.stub()
};
this.applyFn = function () {
this.xServer.request.reset();
return this.definition.fn($, this.xConfig, this.xResource, this.xServer);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
$('<div id="content"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); $('<div id="content"/>').appendTo('body');
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); assert.isPlainObject(this.definition);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
it('adds HTML #support to #content', function () {
this.applyFn();
assert.lengthOf($('#content > #support'), 1);
assert.lengthOf($('#support > .paypal'), 1);
assert.lengthOf($('.paypal > form'), 1);
});
it('adds HTML #login-wrapper to #content', function () {
this.applyFn();
assert.lengthOf($('#content > #login-wrapper'), 1);
});
describe('no admin', function () {
it('adds HTML #pass to #login-wrapper', function () {
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#login-wrapper > #pass'), 1);
}); });
it('sets #pass val to empty string', function () { it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.strictEqual($('#login-wrapper > #pass').val(), '');
}); });
it('adds HTML #login to #login-wrapper', function () { it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#login-wrapper > #login'), 1);
}); });
it('does not add HTML #logout to #login-wrapper', function () { it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#login-wrapper > #logout'), 0);
}); });
it('does not add HTML #tests to #content', function () { it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#content > #tests'), 0);
}); });
it('login works', function () { it('inits without errors', function () {
this.applyFn();
});
});
var pass = uniq.id(); describe('application', function () {
var expectedData = { it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
it('adds HTML #support to #content', function () {
this.applyFn();
assert.lengthOf($('#content > #support'), 1);
assert.lengthOf($('#support > .paypal'), 1);
assert.lengthOf($('.paypal > form'), 1);
});
it('adds HTML #login-wrapper to #content', function () {
this.applyFn();
assert.lengthOf($('#content > #login-wrapper'), 1);
});
describe('no admin', function () {
it('adds HTML #pass to #login-wrapper', function () {
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#login-wrapper > #pass'), 1);
});
it('sets #pass val to empty string', function () {
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.strictEqual($('#login-wrapper > #pass').val(), '');
});
it('adds HTML #login to #login-wrapper', function () {
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#login-wrapper > #login'), 1);
});
it('does not add HTML #logout to #login-wrapper', function () {
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#login-wrapper > #logout'), 0);
});
it('does not add HTML #tests to #content', function () {
this.xConfig.setup.AS_ADMIN = false;
this.applyFn();
assert.lengthOf($('#content > #tests'), 0);
});
it('login works', function () {
var pass = uniq.id();
var expectedData = {
action: 'login', action: 'login',
pass: pass pass: pass
}; };
this.xConfig.setup.AS_ADMIN = false; this.xConfig.setup.AS_ADMIN = false;
this.applyFn(); this.applyFn();
$('#pass').val(pass); $('#pass').val(pass);
$('#login').trigger('click'); $('#login').trigger('click');
assert.isTrue(this.xServer.request.calledOnce); assert.isTrue(this.xServer.request.calledOnce);
assert.isPlainObject(this.xServer.request.lastCall.args[0]); assert.isPlainObject(this.xServer.request.lastCall.args[0]);
assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData); assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData);
assert.isFunction(this.xServer.request.lastCall.args[1]); assert.isFunction(this.xServer.request.lastCall.args[1]);
}); });
});
describe('as admin', function () {
it('does not add HTML #pass to #login-wrapper', function () {
this.xConfig.setup.AS_ADMIN = true;
this.applyFn();
assert.lengthOf($('#login-wrapper > #pass'), 0);
}); });
it('does not add #login to #login-wrapper', function () { describe('as admin', function () {
it('does not add HTML #pass to #login-wrapper', function () {
this.xConfig.setup.AS_ADMIN = true;
this.applyFn();
assert.lengthOf($('#login-wrapper > #pass'), 0);
});
this.xConfig.setup.AS_ADMIN = true; it('does not add #login to #login-wrapper', function () {
this.applyFn(); this.xConfig.setup.AS_ADMIN = true;
assert.lengthOf($('#login-wrapper > #login'), 0); this.applyFn();
}); assert.lengthOf($('#login-wrapper > #login'), 0);
});
it('adds HTML #logout to #login-wrapper', function () { it('adds HTML #logout to #login-wrapper', function () {
this.xConfig.setup.AS_ADMIN = true;
this.applyFn();
assert.lengthOf($('#login-wrapper > #logout'), 1);
});
this.xConfig.setup.AS_ADMIN = true; it('adds HTML #tests to #content', function () {
this.applyFn(); this.xConfig.setup.AS_ADMIN = true;
assert.lengthOf($('#login-wrapper > #logout'), 1); this.applyFn();
}); assert.lengthOf($('#content > #tests'), 1);
});
it('adds HTML #tests to #content', function () { it('adds HTML #test 15x to #tests', function () {
this.xConfig.setup.AS_ADMIN = true;
this.applyFn();
assert.strictEqual($('#tests > .test').length, 15);
});
this.xConfig.setup.AS_ADMIN = true; it('logout works', function () {
this.applyFn(); var expectedData = {
assert.lengthOf($('#content > #tests'), 1);
});
it('adds HTML #test 15x to #tests', function () {
this.xConfig.setup.AS_ADMIN = true;
this.applyFn();
assert.strictEqual($('#tests > .test').length, 15);
});
it('logout works', function () {
var expectedData = {
action: 'logout' action: 'logout'
}; };
this.xConfig.setup.AS_ADMIN = true; this.xConfig.setup.AS_ADMIN = true;
this.applyFn(); this.applyFn();
$('#logout').trigger('click'); $('#logout').trigger('click');
assert.isTrue(this.xServer.request.calledOnce); assert.isTrue(this.xServer.request.calledOnce);
assert.isPlainObject(this.xServer.request.lastCall.args[0]); assert.isPlainObject(this.xServer.request.lastCall.args[0]);
assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData); assert.deepEqual(this.xServer.request.lastCall.args[0], expectedData);
assert.isFunction(this.xServer.request.lastCall.args[1]); assert.isFunction(this.xServer.request.lastCall.args[1]);
});
}); });
}); });
}); });
});
}()); }());

View File

@@ -1,444 +1,356 @@
(function () { (function () {
'use strict'; var ID = 'model/item';
var DEPS = ['_', 'core/event', 'core/location', 'core/server', 'core/settings', 'core/types'];
var ID = 'model/item'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', 'core/event', 'core/location', 'core/server', 'core/settings', 'core/types']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xRootName = uniq.id();
this.xTypes = {
before(function () { getType: sinon.stub().returns(uniq.id())
};
this.definition = modulejs._private.definitions[ID]; this.xEvent = uniq.obj();
this.xSettings = {
this.xRootName = uniq.id(); rootHref: uniq.path('/' + this.xRootName + '/')
this.xTypes = { };
getType: sinon.stub().returns(uniq.id()) this.xServer = uniq.obj();
}; this.xLocation = {
this.xEvent = uniq.obj(); forceEncoding: sinon.stub().returnsArg(0),
this.xSettings = { getDomain: sinon.stub().returns(uniq.id()),
rootHref: uniq.path('/' + this.xRootName + '/') getAbsHref: sinon.stub().returns(uniq.id())
}; };
this.xServer = uniq.obj(); this.applyFn = function () {
this.xLocation = { return this.definition.fn(_, this.xEvent, this.xLocation, this.xServer, this.xSettings, this.xTypes);
forceEncoding: sinon.stub().returnsArg(0), };
getDomain: sinon.stub().returns(uniq.id()),
getAbsHref: sinon.stub().returns(uniq.id())
};
this.applyFn = function () {
return this.definition.fn(_, this.xEvent, this.xLocation, this.xServer, this.xSettings, this.xTypes);
};
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.id, ID); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('requires correct', function () { describe('application', function () {
it('returns plain object with 2 properties', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns plain object with 2 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
});
describe('.get()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.get);
});
it('returns null with no argument', function () {
var instance = this.applyFn();
assert.isNull(instance.get());
});
it('returns null for no string argument', function () {
var instance = this.applyFn();
assert.isNull(instance.get(1));
});
it('returns null for href not starting with rootHref', function () {
var instance = this.applyFn();
assert.isNull(instance.get('/a/'));
});
describe('for rootHref', function () {
beforeEach(function () {
var instance = this.applyFn(); var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref); assert.isPlainObject(instance);
}); assert.lengthOfKeys(instance, 2);
it('returns object', function () {
assert.isObject(this.item);
});
it('sets href correct', function () {
assert.strictEqual(this.item.absHref, this.xSettings.rootHref);
});
it('sets type correct', function () {
assert.strictEqual(this.item.type, this.xTypes.getType(this.absHref));
});
it('sets label correct', function () {
assert.strictEqual(this.item.label, this.xRootName);
});
it('sets time to null', function () {
assert.isNull(this.item.time);
});
it('sets size to null', function () {
assert.isNull(this.item.size);
});
it('sets parent to null', function () {
assert.isNull(this.item.parent);
});
it('sets isManaged to null', function () {
assert.isNull(this.item.isManaged);
});
it('sets content correct', function () {
assert.isPlainObject(this.item.content);
assert.lengthOfKeys(this.item.content, 0);
});
it('.isFolder() returns true', function () {
assert.isTrue(this.item.isFolder());
});
it('.isCurrentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentFolder());
});
it('.isInCurrentFolder() returns false', function () {
assert.isFalse(this.item.isInCurrentFolder());
});
it('.isCurrentParentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentParentFolder());
});
it('.isDomain() returns false', function () {
assert.isFalse(this.item.isDomain());
});
it('.isRoot() returns true', function () {
assert.isTrue(this.item.isRoot());
});
it('.isEmpty() returns true', function () {
assert.isTrue(this.item.isEmpty());
}); });
}); });
describe('for folder href other than rootHref', function () { describe('.get()', function () {
it('is function', function () {
beforeEach(function () {
var instance = this.applyFn(); var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref + 'a/'); assert.isFunction(instance.get);
}); });
it('returns object', function () { it('returns null with no argument', function () {
var instance = this.applyFn();
assert.isObject(this.item); assert.isNull(instance.get());
}); });
it('sets href correct', function () { it('returns null for no string argument', function () {
var instance = this.applyFn();
assert.strictEqual(this.item.absHref, this.xSettings.rootHref + 'a/'); assert.isNull(instance.get(1));
}); });
it('sets type correct', function () { it('returns null for href not starting with rootHref', function () {
var instance = this.applyFn();
assert.strictEqual(this.item.type, this.xTypes.getType(this.absHref)); assert.isNull(instance.get('/a/'));
}); });
it('sets label correct', function () { describe('for rootHref', function () {
beforeEach(function () {
var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref);
});
assert.strictEqual(this.item.label, 'a'); it('returns object', function () {
assert.isObject(this.item);
});
it('sets href correct', function () {
assert.strictEqual(this.item.absHref, this.xSettings.rootHref);
});
it('sets type correct', function () {
assert.strictEqual(this.item.type, this.xTypes.getType(this.absHref));
});
it('sets label correct', function () {
assert.strictEqual(this.item.label, this.xRootName);
});
it('sets time to null', function () {
assert.isNull(this.item.time);
});
it('sets size to null', function () {
assert.isNull(this.item.size);
});
it('sets parent to null', function () {
assert.isNull(this.item.parent);
});
it('sets isManaged to null', function () {
assert.isNull(this.item.isManaged);
});
it('sets content correct', function () {
assert.isPlainObject(this.item.content);
assert.lengthOfKeys(this.item.content, 0);
});
it('.isFolder() returns true', function () {
assert.isTrue(this.item.isFolder());
});
it('.isCurrentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentFolder());
});
it('.isInCurrentFolder() returns false', function () {
assert.isFalse(this.item.isInCurrentFolder());
});
it('.isCurrentParentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentParentFolder());
});
it('.isDomain() returns false', function () {
assert.isFalse(this.item.isDomain());
});
it('.isRoot() returns true', function () {
assert.isTrue(this.item.isRoot());
});
it('.isEmpty() returns true', function () {
assert.isTrue(this.item.isEmpty());
});
}); });
it('sets time to null', function () { describe('for folder href other than rootHref', function () {
beforeEach(function () {
var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref + 'a/');
});
assert.isNull(this.item.time); it('returns object', function () {
assert.isObject(this.item);
});
it('sets href correct', function () {
assert.strictEqual(this.item.absHref, this.xSettings.rootHref + 'a/');
});
it('sets type correct', function () {
assert.strictEqual(this.item.type, this.xTypes.getType(this.absHref));
});
it('sets label correct', function () {
assert.strictEqual(this.item.label, 'a');
});
it('sets time to null', function () {
assert.isNull(this.item.time);
});
it('sets size to null', function () {
assert.isNull(this.item.size);
});
it('sets parent to object', function () {
assert.isObject(this.item.parent);
});
it('parent has same constructor', function () {
assert.strictEqual(this.item.constructor, this.item.parent.constructor);
});
it('sets isManaged to null', function () {
assert.isNull(this.item.isManaged);
});
it('sets content correct', function () {
assert.isPlainObject(this.item.content);
assert.lengthOfKeys(this.item.content, 0);
});
it('.isFolder() returns true', function () {
assert.isTrue(this.item.isFolder());
});
it('.isCurrentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentFolder());
});
it('.isInCurrentFolder() returns false', function () {
assert.isFalse(this.item.isInCurrentFolder());
});
it('.isCurrentParentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentParentFolder());
});
it('.isDomain() returns false', function () {
assert.isFalse(this.item.isDomain());
});
it('.isRoot() returns false', function () {
assert.isFalse(this.item.isRoot());
});
it('.isEmpty() returns true', function () {
assert.isTrue(this.item.isEmpty());
});
}); });
it('sets size to null', function () { describe('for file href', function () {
beforeEach(function () {
var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref + 'a');
});
assert.isNull(this.item.size); it('returns object', function () {
assert.isObject(this.item);
});
it('sets href correct', function () {
assert.strictEqual(this.item.absHref, this.xSettings.rootHref + 'a');
});
it('sets type correct', function () {
assert.strictEqual(this.item.type, this.xTypes.getType(this.absHref));
});
it('sets label correct', function () {
assert.strictEqual(this.item.label, 'a');
});
it('sets time to null', function () {
assert.isNull(this.item.time);
});
it('sets size to null', function () {
assert.isNull(this.item.size);
});
it('sets parent to object', function () {
assert.isObject(this.item.parent);
});
it('parent has same constructor', function () {
assert.strictEqual(this.item.constructor, this.item.parent.constructor);
});
it('sets isManaged to null', function () {
assert.isNull(this.item.isManaged);
});
it('sets content correct', function () {
assert.isPlainObject(this.item.content);
assert.lengthOfKeys(this.item.content, 0);
});
it('.isFolder() returns false', function () {
assert.isFalse(this.item.isFolder());
});
it('.isCurrentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentFolder());
});
it('.isInCurrentFolder() returns false', function () {
assert.isFalse(this.item.isInCurrentFolder());
});
it('.isCurrentParentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentParentFolder());
});
it('.isDomain() returns false', function () {
assert.isFalse(this.item.isDomain());
});
it('.isRoot() returns false', function () {
assert.isFalse(this.item.isRoot());
});
it('.isEmpty() returns true', function () {
assert.isTrue(this.item.isEmpty());
});
}); });
it('sets parent to object', function () { describe('parents', function () {
beforeEach(function () {
var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref + 'p/a/');
this.parent = this.item.parent;
this.grandpa = this.parent.parent;
});
assert.isObject(this.item.parent); it('parent is object', function () {
}); assert.isObject(this.parent);
});
it('parent has same constructor', function () { it('parent has correct href', function () {
assert.strictEqual(this.parent.absHref, this.xSettings.rootHref + 'p/');
});
assert.strictEqual(this.item.constructor, this.item.parent.constructor); it('parent has correct label', function () {
}); assert.strictEqual(this.parent.label, 'p');
});
it('sets isManaged to null', function () { it('parent .isEmpty() returns false', function () {
assert.isFalse(this.parent.isEmpty());
});
assert.isNull(this.item.isManaged); it('grandpa is object', function () {
}); assert.isObject(this.grandpa);
});
it('sets content correct', function () { it('grandpa has correct href', function () {
assert.strictEqual(this.grandpa.absHref, this.xSettings.rootHref);
});
assert.isPlainObject(this.item.content); it('grandpa has correct label', function () {
assert.lengthOfKeys(this.item.content, 0); assert.strictEqual(this.grandpa.label, this.xRootName);
}); });
it('.isFolder() returns true', function () { it('grandpa .isEmpty() returns false', function () {
assert.isFalse(this.grandpa.isEmpty());
assert.isTrue(this.item.isFolder()); });
});
it('.isCurrentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentFolder());
});
it('.isInCurrentFolder() returns false', function () {
assert.isFalse(this.item.isInCurrentFolder());
});
it('.isCurrentParentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentParentFolder());
});
it('.isDomain() returns false', function () {
assert.isFalse(this.item.isDomain());
});
it('.isRoot() returns false', function () {
assert.isFalse(this.item.isRoot());
});
it('.isEmpty() returns true', function () {
assert.isTrue(this.item.isEmpty());
}); });
}); });
describe('for file href', function () { describe('.remove()', function () {
it('is function', function () {
beforeEach(function () {
var instance = this.applyFn(); var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref + 'a'); assert.isFunction(instance.remove);
});
it('returns object', function () {
assert.isObject(this.item);
});
it('sets href correct', function () {
assert.strictEqual(this.item.absHref, this.xSettings.rootHref + 'a');
});
it('sets type correct', function () {
assert.strictEqual(this.item.type, this.xTypes.getType(this.absHref));
});
it('sets label correct', function () {
assert.strictEqual(this.item.label, 'a');
});
it('sets time to null', function () {
assert.isNull(this.item.time);
});
it('sets size to null', function () {
assert.isNull(this.item.size);
});
it('sets parent to object', function () {
assert.isObject(this.item.parent);
});
it('parent has same constructor', function () {
assert.strictEqual(this.item.constructor, this.item.parent.constructor);
});
it('sets isManaged to null', function () {
assert.isNull(this.item.isManaged);
});
it('sets content correct', function () {
assert.isPlainObject(this.item.content);
assert.lengthOfKeys(this.item.content, 0);
});
it('.isFolder() returns false', function () {
assert.isFalse(this.item.isFolder());
});
it('.isCurrentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentFolder());
});
it('.isInCurrentFolder() returns false', function () {
assert.isFalse(this.item.isInCurrentFolder());
});
it('.isCurrentParentFolder() returns false', function () {
assert.isFalse(this.item.isCurrentParentFolder());
});
it('.isDomain() returns false', function () {
assert.isFalse(this.item.isDomain());
});
it('.isRoot() returns false', function () {
assert.isFalse(this.item.isRoot());
});
it('.isEmpty() returns true', function () {
assert.isTrue(this.item.isEmpty());
});
});
describe('parents', function () {
beforeEach(function () {
var instance = this.applyFn();
this.item = instance.get(this.xSettings.rootHref + 'p/a/');
this.parent = this.item.parent;
this.grandpa = this.parent.parent;
});
it('parent is object', function () {
assert.isObject(this.parent);
});
it('parent has correct href', function () {
assert.strictEqual(this.parent.absHref, this.xSettings.rootHref + 'p/');
});
it('parent has correct label', function () {
assert.strictEqual(this.parent.label, 'p');
});
it('parent .isEmpty() returns false', function () {
assert.isFalse(this.parent.isEmpty());
});
it('grandpa is object', function () {
assert.isObject(this.grandpa);
});
it('grandpa has correct href', function () {
assert.strictEqual(this.grandpa.absHref, this.xSettings.rootHref);
});
it('grandpa has correct label', function () {
assert.strictEqual(this.grandpa.label, this.xRootName);
});
it('grandpa .isEmpty() returns false', function () {
assert.isFalse(this.grandpa.isEmpty());
}); });
}); });
}); });
describe('.remove()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isFunction(instance.remove);
});
});
});
}()); }());

View File

@@ -1,48 +1,36 @@
(function () { (function () {
'use strict'; describe('modulejs', function () {
it('is global object', function () {
assert.isPlainObject(modulejs);
assert.strictEqual(modulejs, window.modulejs);
});
describe('modulejs', function () { it('.define() is function', function () {
assert.isFunction(modulejs.define);
});
it('is global object', function () { it('.require() is function', function () {
assert.isFunction(modulejs.require);
});
assert.isPlainObject(modulejs); it('.state() is function', function () {
assert.strictEqual(modulejs, window.modulejs); assert.isFunction(modulejs.state);
});
it('.log() is function', function () {
assert.isFunction(modulejs.log);
});
it('._private is object', function () {
assert.isObject(modulejs._private);
});
it('has definitions', function () {
assert.isAbove(_.keys(modulejs._private.definitions).length, 0);
});
it('has no instances', function () {
assert.lengthOfKeys(modulejs._private.instances, 0);
});
}); });
it('.define() is function', function () {
assert.isFunction(modulejs.define);
});
it('.require() is function', function () {
assert.isFunction(modulejs.require);
});
it('.state() is function', function () {
assert.isFunction(modulejs.state);
});
it('.log() is function', function () {
assert.isFunction(modulejs.log);
});
it('._private is object', function () {
assert.isObject(modulejs._private);
});
it('has definitions', function () {
assert.isAbove(_.keys(modulejs._private.definitions).length, 0);
});
it('has no instances', function () {
assert.lengthOfKeys(modulejs._private.instances, 0);
});
});
}()); }());

View File

@@ -1,93 +1,73 @@
(function () { (function () {
'use strict'; var ID = 'view/content';
var DEPS = ['$', 'view/mainrow'];
var ID = 'view/content'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$', 'view/mainrow']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xMainrow = {$el: null};
this.applyFn = function () {
before(function () { return this.definition.fn($, this.xMainrow);
};
this.definition = modulejs._private.definitions[ID];
this.xMainrow = {$el: null};
this.applyFn = function () {
return this.definition.fn($, this.xMainrow);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
this.xMainrow.$el = $('<div id="mainrow"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); this.xMainrow.$el = $('<div id="mainrow"/>').appendTo('body');
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
assert.notProperty(modulejs._private.instances, ID); it('adds HTML #content to #mainrow', function () {
this.applyFn();
assert.lengthOf($('#mainrow > #content'), 1);
});
}); });
it('inits without errors', function () { describe('.$el', function () {
it('is $(\'#content\')', function () {
this.applyFn(); var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'content');
});
}); });
}); });
describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
it('adds HTML #content to #mainrow', function () {
this.applyFn();
assert.lengthOf($('#mainrow > #content'), 1);
});
});
describe('.$el', function () {
it('is $(\'#content\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'content');
});
});
});
}()); }());

View File

@@ -1,93 +1,73 @@
(function () { (function () {
'use strict'; var ID = 'view/mainrow';
var DEPS = ['$', 'view/root'];
var ID = 'view/mainrow'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$', 'view/root']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xRoot = {$el: null};
this.applyFn = function () {
before(function () { return this.definition.fn($, this.xRoot);
};
this.definition = modulejs._private.definitions[ID];
this.xRoot = {$el: null};
this.applyFn = function () {
return this.definition.fn($, this.xRoot);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
this.xRoot.$el = $('<div id="root"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); this.xRoot.$el = $('<div id="root"/>').appendTo('body');
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
assert.notProperty(modulejs._private.instances, ID); it('adds HTML #mainrow to #root', function () {
this.applyFn();
assert.lengthOf($('#root > #mainrow'), 1);
});
}); });
it('inits without errors', function () { describe('.$el', function () {
it('is $(\'#mainrow\')', function () {
this.applyFn(); var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'mainrow');
});
}); });
}); });
describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
it('adds HTML #mainrow to #root', function () {
this.applyFn();
assert.lengthOf($('#root > #mainrow'), 1);
});
});
describe('.$el', function () {
it('is $(\'#mainrow\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'mainrow');
});
});
});
}()); }());

View File

@@ -1,125 +1,102 @@
(function () { (function () {
'use strict'; var ID = 'view/notification';
var DEPS = ['$', 'view/root'];
var ID = 'view/notification'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$', 'view/root']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xRoot = {$el: null};
this.applyFn = function () {
before(function () { return this.definition.fn($, this.xRoot);
};
this.definition = modulejs._private.definitions[ID];
this.xRoot = {$el: null};
this.applyFn = function () {
return this.definition.fn($, this.xRoot);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
this.xRoot.$el = $('<div id="root"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); this.xRoot.$el = $('<div id="root"/>').appendTo('body');
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns plain object with 2 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
assert.notProperty(modulejs._private.instances, ID); it('adds HTML #notification to #root (hidden)', function () {
this.applyFn();
assert.lengthOf($('#root > #notification'), 1);
assert.lengthOf($('#notification:visible'), 0);
assert.strictEqual($('#notification').text(), '');
});
}); });
it('inits without errors', function () { describe('.$el', function () {
it('is $(\'#notification\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'notification');
});
});
this.applyFn(); describe('.set()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.set));
});
it('works', function () {
var instance = this.applyFn();
instance.set();
assert.lengthOf($('#notification:visible'), 0);
assert.strictEqual($('#notification').text(), '');
instance.set('hello');
assert.lengthOf($('#notification:visible'), 1);
assert.strictEqual($('#notification').text(), 'hello');
instance.set('world');
assert.lengthOf($('#notification:visible'), 1);
assert.strictEqual($('#notification').text(), 'world');
instance.set();
// assert.lengthOf($('#notification:visible'), 0);
assert.strictEqual($('#notification').text(), 'world');
});
}); });
}); });
describe('application', function () {
it('returns plain object with 2 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 2);
});
it('adds HTML #notification to #root (hidden)', function () {
this.applyFn();
assert.lengthOf($('#root > #notification'), 1);
assert.lengthOf($('#notification:visible'), 0);
assert.strictEqual($('#notification').text(), '');
});
});
describe('.$el', function () {
it('is $(\'#notification\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'notification');
});
});
describe('.set()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.set));
});
it('works', function () {
var instance = this.applyFn();
instance.set();
assert.lengthOf($('#notification:visible'), 0);
assert.strictEqual($('#notification').text(), '');
instance.set('hello');
assert.lengthOf($('#notification:visible'), 1);
assert.strictEqual($('#notification').text(), 'hello');
instance.set('world');
assert.lengthOf($('#notification:visible'), 1);
assert.strictEqual($('#notification').text(), 'world');
instance.set();
// assert.lengthOf($('#notification:visible'), 0);
assert.strictEqual($('#notification').text(), 'world');
});
});
});
}()); }());

View File

@@ -1,105 +1,83 @@
(function () { (function () {
'use strict'; var ID = 'view/root';
var DEPS = ['$'];
var ID = 'view/root'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.applyFn = function () {
return this.definition.fn($);
before(function () { };
this.definition = modulejs._private.definitions[ID];
this.applyFn = function () {
return this.definition.fn($);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
$('<div id="fallback"/>').appendTo('body');
$('<div id="fallback-hints"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); $('<div id="fallback"/>').appendTo('body');
$('<div id="fallback-hints"/>').appendTo('body');
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
assert.notProperty(modulejs._private.instances, ID); it('adds id root to body', function () {
this.applyFn();
assert.strictEqual($('body').attr('id'), 'root');
});
it('removes HTML #fallback', function () {
this.applyFn();
assert.lengthOf($('#fallback'), 0);
});
it('removes HTML #fallback-hints', function () {
this.applyFn();
assert.lengthOf($('#fallback-hints'), 0);
});
}); });
it('inits without errors', function () { describe('.$el', function () {
it('is $(\'#root\')', function () {
this.applyFn(); var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'root');
});
}); });
}); });
describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
it('adds id root to body', function () {
this.applyFn();
assert.strictEqual($('body').attr('id'), 'root');
});
it('removes HTML #fallback', function () {
this.applyFn();
assert.lengthOf($('#fallback'), 0);
});
it('removes HTML #fallback-hints', function () {
this.applyFn();
assert.lengthOf($('#fallback-hints'), 0);
});
});
describe('.$el', function () {
it('is $(\'#root\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'root');
});
});
});
}()); }());

View File

@@ -1,142 +1,121 @@
(function () { (function () {
'use strict'; var ID = 'view/sidebar';
var DEPS = ['$', 'core/resource', 'core/store', 'view/mainrow', 'view/topbar'];
var ID = 'view/sidebar'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$', 'core/resource', 'core/store', 'view/mainrow', 'view/topbar']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xResource = {
image: sinon.stub().throws('invalid image request')
};
this.xResource.image.withArgs('back').returns(uniq.path('-back.png'));
this.xResource.image.withArgs('sidebar').returns(uniq.path('-sidebar.png'));
this.xStore = {
get: sinon.stub().returns(false),
put: sinon.stub()
};
this.xStore.get.returns(false);
this.xMainrow = {$el: null};
this.xTopbar = {$toolbar: null};
this.applyFn = function () {
this.xResource.image.reset();
this.xStore.get.reset();
this.xStore.put.reset();
before(function () { return this.definition.fn($, this.xResource, this.xStore, this.xMainrow, this.xTopbar);
};
this.definition = modulejs._private.definitions[ID];
this.xResource = {
image: sinon.stub().throws('invalid image request')
};
this.xResource.image.withArgs('back').returns(uniq.path('-back.png'));
this.xResource.image.withArgs('sidebar').returns(uniq.path('-sidebar.png'));
this.xStore = {
get: sinon.stub().returns(false),
put: sinon.stub()
};
this.xStore.get.returns(false);
this.xMainrow = {$el: null};
this.xTopbar = {$toolbar: null};
this.applyFn = function () {
this.xResource.image.reset();
this.xStore.get.reset();
this.xStore.put.reset();
return this.definition.fn($, this.xResource, this.xStore, this.xMainrow, this.xTopbar);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
this.xMainrow.$el = $('<div id="mainrow"/>').appendTo('body');
this.xTopbar.$toolbar = $('<div id="toolbar"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); this.xMainrow.$el = $('<div id="mainrow"/>').appendTo('body');
this.xTopbar.$toolbar = $('<div id="toolbar"/>').appendTo('body');
}); });
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.instance = this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
assert.notProperty(modulejs._private.instances, ID); it('adds HTML #sidebar-toggle to #toolbar', function () {
this.applyFn();
assert.lengthOf($('#toolbar > #sidebar-toggle'), 1);
});
it('toggle works', function () {
this.applyFn();
assert.lengthOf($('#sidebar:visible'), 0);
this.xStore.get.returns(false).reset();
this.xStore.put.reset();
$('#sidebar-toggle').trigger('click');
assert.isTrue(this.xStore.get.calledOnce);
assert.strictEqual(this.xStore.get.lastCall.args[0], 'sidebarIsVisible');
assert.isTrue(this.xStore.put.calledOnce);
assert.strictEqual(this.xStore.put.lastCall.args[0], 'sidebarIsVisible');
assert.isTrue(this.xStore.put.lastCall.args[1]);
assert.lengthOf($('#sidebar:visible'), 1);
this.xStore.get.returns(true).reset();
this.xStore.put.reset();
$('#sidebar-toggle').trigger('click');
assert.isTrue(this.xStore.get.calledOnce);
assert.strictEqual(this.xStore.get.lastCall.args[0], 'sidebarIsVisible');
assert.isTrue(this.xStore.put.calledOnce);
assert.strictEqual(this.xStore.put.lastCall.args[0], 'sidebarIsVisible');
assert.isFalse(this.xStore.put.lastCall.args[1]);
assert.lengthOf($('#sidebar:visible'), 0);
});
}); });
it('inits without errors', function () { describe('.$el', function () {
it('is $(\'#sidebar\')', function () {
this.instance = this.applyFn(); var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'sidebar');
});
}); });
}); });
describe('application', function () {
it('returns object with 1 property', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 1);
});
it('adds HTML #sidebar-toggle to #toolbar', function () {
this.applyFn();
assert.lengthOf($('#toolbar > #sidebar-toggle'), 1);
});
it('toggle works', function () {
this.applyFn();
assert.lengthOf($('#sidebar:visible'), 0);
this.xStore.get.returns(false).reset();
this.xStore.put.reset();
$('#sidebar-toggle').trigger('click');
assert.isTrue(this.xStore.get.calledOnce);
assert.strictEqual(this.xStore.get.lastCall.args[0], 'sidebarIsVisible');
assert.isTrue(this.xStore.put.calledOnce);
assert.strictEqual(this.xStore.put.lastCall.args[0], 'sidebarIsVisible');
assert.isTrue(this.xStore.put.lastCall.args[1]);
assert.lengthOf($('#sidebar:visible'), 1);
this.xStore.get.returns(true).reset();
this.xStore.put.reset();
$('#sidebar-toggle').trigger('click');
assert.isTrue(this.xStore.get.calledOnce);
assert.strictEqual(this.xStore.get.lastCall.args[0], 'sidebarIsVisible');
assert.isTrue(this.xStore.put.calledOnce);
assert.strictEqual(this.xStore.put.lastCall.args[0], 'sidebarIsVisible');
assert.isFalse(this.xStore.put.lastCall.args[1]);
assert.lengthOf($('#sidebar:visible'), 0);
});
});
describe('.$el', function () {
it('is $(\'#sidebar\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'sidebar');
});
});
});
}()); }());

View File

@@ -1,154 +1,124 @@
(function () { (function () {
'use strict'; var ID = 'view/topbar';
var DEPS = ['$', 'view/root'];
var ID = 'view/topbar'; describe('module \'' + ID + '\'', function () {
var DEPS = ['$', 'view/root']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xRoot = {$el: null};
this.applyFn = function () {
before(function () { return this.definition.fn($, this.xRoot);
};
this.definition = modulejs._private.definitions[ID];
this.xRoot = {$el: null};
this.applyFn = function () {
return this.definition.fn($, this.xRoot);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
this.xRoot.$el = $('<div id="root"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); this.xRoot.$el = $('<div id="root"/>').appendTo('body');
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns object with 3 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 3);
});
assert.notProperty(modulejs._private.instances, ID); it('adds HTML #topbar to #root', function () {
this.applyFn();
assert.lengthOf($('#root > #topbar'), 1);
});
it('adds HTML #toolbar to #topbar', function () {
this.applyFn();
assert.lengthOf($('#topbar > #toolbar'), 1);
});
it('adds HTML #flowbar to #topbar', function () {
this.applyFn();
assert.lengthOf($('#topbar > #flowbar'), 1);
});
it('adds HTML #backlink to #topbar', function () {
this.applyFn();
assert.lengthOf($('#topbar > #backlink'), 1);
});
it('#backlink has correct href', function () {
this.applyFn();
assert.strictEqual($('#backlink').attr('href'), 'https://larsjung.de/h5ai/');
});
it('#backlink has correct title', function () {
this.applyFn();
assert.strictEqual($('#backlink').attr('title'), 'powered by h5ai - https://larsjung.de/h5ai/');
});
it('#backlink has correct text', function () {
this.applyFn();
assert.strictEqual($('#backlink > div').eq(0).text(), 'powered');
assert.strictEqual($('#backlink > div').eq(1).text(), 'by h5ai');
});
}); });
it('inits without errors', function () { describe('.$el', function () {
it('is $(\'#topbar\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'topbar');
});
});
this.applyFn(); describe('.$toolbar', function () {
it('is $(\'#toolbar\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$toolbar);
assert.lengthOf(instance.$toolbar, 1);
assert.isString(instance.$toolbar.jquery);
assert.strictEqual(instance.$toolbar.attr('id'), 'toolbar');
});
});
describe('.$flowbar', function () {
it('is $(\'#flowbar\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$flowbar);
assert.lengthOf(instance.$flowbar, 1);
assert.isString(instance.$flowbar.jquery);
assert.strictEqual(instance.$flowbar.attr('id'), 'flowbar');
});
}); });
}); });
describe('application', function () {
it('returns object with 3 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 3);
});
it('adds HTML #topbar to #root', function () {
this.applyFn();
assert.lengthOf($('#root > #topbar'), 1);
});
it('adds HTML #toolbar to #topbar', function () {
this.applyFn();
assert.lengthOf($('#topbar > #toolbar'), 1);
});
it('adds HTML #flowbar to #topbar', function () {
this.applyFn();
assert.lengthOf($('#topbar > #flowbar'), 1);
});
it('adds HTML #backlink to #topbar', function () {
this.applyFn();
assert.lengthOf($('#topbar > #backlink'), 1);
});
it('#backlink has correct href', function () {
this.applyFn();
assert.strictEqual($('#backlink').attr('href'), 'https://larsjung.de/h5ai/');
});
it('#backlink has correct title', function () {
this.applyFn();
assert.strictEqual($('#backlink').attr('title'), 'powered by h5ai - https://larsjung.de/h5ai/');
});
it('#backlink has correct text', function () {
this.applyFn();
assert.strictEqual($('#backlink > div').eq(0).text(), 'powered');
assert.strictEqual($('#backlink > div').eq(1).text(), 'by h5ai');
});
});
describe('.$el', function () {
it('is $(\'#topbar\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'topbar');
});
});
describe('.$toolbar', function () {
it('is $(\'#toolbar\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$toolbar);
assert.lengthOf(instance.$toolbar, 1);
assert.isString(instance.$toolbar.jquery);
assert.strictEqual(instance.$toolbar.attr('id'), 'toolbar');
});
});
describe('.$flowbar', function () {
it('is $(\'#flowbar\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$flowbar);
assert.lengthOf(instance.$flowbar, 1);
assert.isString(instance.$flowbar.jquery);
assert.strictEqual(instance.$flowbar.attr('id'), 'flowbar');
});
});
});
}()); }());

View File

@@ -1,455 +1,385 @@
(function () { (function () {
'use strict'; var ID = 'view/view';
var DEPS = ['_', '$', 'core/event', 'core/format', 'core/location', 'core/resource', 'core/settings', 'core/store', 'view/content'];
var ID = 'view/view'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', '$', 'core/event', 'core/format', 'core/location', 'core/resource', 'core/settings', 'core/store', 'view/content']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xEvent = {
sub: sinon.stub(),
pub: sinon.stub()
};
this.xFormat = {
setDefaultMetric: sinon.stub(),
formatDate: sinon.stub().returns(uniq.id()),
formatSize: sinon.stub().returns(uniq.id())
};
this.xLocation = {
setLink: sinon.stub().returns(uniq.id())
};
this.xResource = {
icon: sinon.stub().returns(uniq.id())
};
this.xSettings = {view: {
binaryPrefix: false,
hideFolders: false,
hideParentFolder: false,
modes: ['details', 'grid', 'icons'],
setParentFolderLabels: false,
sizes: [20, 40, 60, 80, 100, 150, 200, 250, 300, 350, 400]
}};
this.xStore = {
get: sinon.stub(),
put: sinon.stub()
};
this.xContent = {$el: null};
before(function () { this.applyFn = function () {
this.xEvent.sub.reset();
this.xEvent.pub.reset();
this.xFormat.setDefaultMetric.reset();
this.xFormat.formatDate.reset();
this.xFormat.formatSize.reset();
this.xLocation.setLink.reset();
this.xResource.icon.reset();
this.definition = modulejs._private.definitions[ID]; return this.definition.fn(_, $, this.xEvent, this.xFormat, this.xLocation, this.xResource, this.xSettings, this.xStore, this.xContent);
};
});
this.xEvent = { after(function () {
sub: sinon.stub(), util.restoreHtml();
pub: sinon.stub() });
};
this.xFormat = {
setDefaultMetric: sinon.stub(),
formatDate: sinon.stub().returns(uniq.id()),
formatSize: sinon.stub().returns(uniq.id())
};
this.xLocation = {
setLink: sinon.stub().returns(uniq.id())
};
this.xResource = {
icon: sinon.stub().returns(uniq.id())
};
this.xSettings = {view: {
binaryPrefix: false,
hideFolders: false,
hideParentFolder: false,
modes: ['details', 'grid', 'icons'],
setParentFolderLabels: false,
sizes: [20, 40, 60, 80, 100, 150, 200, 250, 300, 350, 400]
}};
this.xStore = {
get: sinon.stub(),
put: sinon.stub()
};
this.xContent = {$el: null};
this.applyFn = function () { beforeEach(function () {
util.restoreHtml();
this.xContent.$el = $('<div id="content"/>').appendTo('body');
});
this.xEvent.sub.reset(); describe('definition', function () {
this.xEvent.pub.reset(); it('is defined', function () {
this.xFormat.setDefaultMetric.reset(); assert.isPlainObject(this.definition);
this.xFormat.formatDate.reset(); });
this.xFormat.formatSize.reset();
this.xLocation.setLink.reset();
this.xResource.icon.reset();
return this.definition.fn(_, $, this.xEvent, this.xFormat, this.xLocation, this.xResource, this.xSettings, this.xStore, this.xContent); it('has correct id', function () {
}; assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns object with 12 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 12);
});
it('adds HTML #view to #content', function () {
this.applyFn();
assert.lengthOf($('#content > #view'), 1);
});
it('adds HTML #items to #view', function () {
this.applyFn();
assert.lengthOf($('#view > #items'), 1);
});
it('adds HTML #view-hint to #view', function () {
this.applyFn();
assert.lengthOf($('#view > #view-hint'), 1);
});
it('adds style to head', function () {
var styleTagCount = $('head > style').length;
this.applyFn();
assert.lengthOf($('head > style'), styleTagCount + 1);
});
it('style contains possibly correct text', function () {
this.xSettings.sizes = [20];
this.applyFn();
var text = $('head > style').eq(0).text();
assert.isTrue(text.indexOf('#view.view-details.view-size-20 ') >= 0);
assert.isTrue(text.indexOf('#view.view-grid.view-size-20 ') >= 0);
assert.isTrue(text.indexOf('#view.view-icons.view-size-20 ') >= 0);
});
it('sets default metric', function () {
this.applyFn();
assert.isTrue(this.xFormat.setDefaultMetric.calledOnce);
});
it('subscribes to 2 events', function () {
this.applyFn();
assert.isTrue(this.xEvent.sub.calledTwice);
});
it('subscribes to location.changed', function () {
this.applyFn();
assert.strictEqual(this.xEvent.sub.firstCall.args[0], 'location.changed');
assert.isFunction(this.xEvent.sub.firstCall.args[1]);
});
it('subscribes to location.refreshed', function () {
this.applyFn();
assert.strictEqual(this.xEvent.sub.secondCall.args[0], 'location.refreshed');
assert.isFunction(this.xEvent.sub.secondCall.args[1]);
});
});
describe('.$el', function () {
it('is $(\'#view\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'view');
});
});
describe('.$items', function () {
it('is $(\'#items\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$items);
assert.lengthOf(instance.$items, 1);
assert.isString(instance.$items.jquery);
assert.strictEqual(instance.$items.attr('id'), 'items');
});
});
describe('.setItems()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setItems));
});
it('publishes view.changed', function () {
var instance = this.applyFn();
instance.setItems();
assert.isTrue(this.xEvent.pub.calledTwice);
assert.strictEqual(this.xEvent.pub.lastCall.args[0], 'view.changed');
});
});
describe('.changeItems()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.changeItems));
});
it('publishes view.changed', function () {
var instance = this.applyFn();
instance.setItems();
assert.isTrue(this.xEvent.pub.calledTwice);
assert.strictEqual(this.xEvent.pub.lastCall.args[0], 'view.changed');
});
});
describe('.setLocation()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setLocation));
});
it('publishes view.changed', function () {
var instance = this.applyFn();
instance.setItems();
assert.isTrue(this.xEvent.pub.calledTwice);
assert.strictEqual(this.xEvent.pub.lastCall.args[0], 'view.changed');
});
});
describe('.setHint()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setHint));
});
it('sets correct class to #view-hint', function () {
var key = uniq.id();
var instance = this.applyFn();
instance.setHint(key);
assert.strictEqual($('#view-hint').attr('class'), 'l10n-' + key);
});
it('removes all other classes from #view-hint', function () {
var key = uniq.id();
var instance = this.applyFn();
$('#view-hint').addClass('a');
instance.setHint(key);
assert.strictEqual($('#view-hint').attr('class'), 'l10n-' + key);
});
});
describe('.getModes()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getModes));
});
});
describe('.getMode()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getMode));
});
});
describe('.setMode()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setMode));
});
it('.setMode(\'details\') changes #view class to .view-details', function () {
this.xSettings.view.modes = ['details', 'grid', 'icons'];
var instance = this.applyFn();
instance.setMode('details');
assert.isTrue($('#view').hasClass('view-details'));
assert.isFalse($('#view').hasClass('view-grid'));
assert.isFalse($('#view').hasClass('view-icons'));
});
it('.setMode(\'grid\') changes #view class to .view-grid', function () {
this.xSettings.view.modes = ['details', 'grid', 'icons'];
var instance = this.applyFn();
instance.setMode('grid');
assert.isFalse($('#view').hasClass('view-details'));
assert.isTrue($('#view').hasClass('view-grid'));
assert.isFalse($('#view').hasClass('view-icons'));
});
it('.setMode(\'icons\') changes #view class to .view-icons', function () {
this.xSettings.view.modes = ['details', 'grid', 'icons'];
var instance = this.applyFn();
instance.setMode('icons');
assert.isFalse($('#view').hasClass('view-details'));
assert.isFalse($('#view').hasClass('view-grid'));
assert.isTrue($('#view').hasClass('view-icons'));
});
});
describe('.getSizes()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getSizes));
});
it('returns sorted sizes', function () {
this.xSettings.view.sizes = [20, 60, 40];
var instance = this.applyFn();
assert.deepEqual(instance.getSizes(), [20, 40, 60]);
});
it('returns sorted sizes', function () {
this.xSettings.view.sizes = [60, 40, 20];
var instance = this.applyFn();
assert.deepEqual(instance.getSizes(), [20, 40, 60]);
});
});
describe('.getSize()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getSize));
});
});
describe('.setSize()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setSize));
});
it('.setSize(20) changes #view class to .view-size-20', function () {
this.xSettings.view.sizes = [20, 40, 60];
var instance = this.applyFn();
instance.setSize(20);
assert.isTrue($('#view').hasClass('view-size-20'), 20);
assert.isFalse($('#view').hasClass('view-size-40'), 40);
assert.isFalse($('#view').hasClass('view-size-60'), 60);
});
it('.setSize(40) changes #view class to .view-size-40', function () {
this.xSettings.view.sizes = [20, 40, 60];
var instance = this.applyFn();
instance.setSize(20);
instance.setSize(40);
assert.isFalse($('#view').hasClass('view-size-20'), 20);
assert.isTrue($('#view').hasClass('view-size-40'), 40);
assert.isFalse($('#view').hasClass('view-size-60'), 60);
});
it('.setSize(60) changes #view class to .view-size-60', function () {
this.xSettings.view.sizes = [20, 40, 60];
var instance = this.applyFn();
instance.setSize(20);
instance.setSize(60);
assert.isFalse($('#view').hasClass('view-size-20'), 20);
assert.isFalse($('#view').hasClass('view-size-40'), 40);
assert.isTrue($('#view').hasClass('view-size-60'), 60);
});
});
// describe('._.createHtml()', function () {
// before(function () {
// this.createItem = function () {
// return {
// isFolder: sinon.stub().returns(false),
// label: uniq.id(),
// time: 0,
// size: 0,
// type: uniq.id(),
// isManaged: false,
// icon: null,
// isCurrentParentFolder: sinon.stub().returns(false)
// };
// };
// });
// it('is function', function () {
// var instance = this.applyFn();
// assert.isFunction(instance._.createHtml);
// });
// it('returns jQuery instance of single HTML element', function () {
// var item = this.createItem();
// var instance = this.applyFn();
// var $item = instance._.createHtml(item);
// assert.isObject($item);
// assert.lengthOf($item, 1);
// assert.isString($item.jquery);
// });
// it('$item.data(\'item\') is back reference to item', function () {
// var item = this.createItem();
// var instance = this.applyFn();
// var $item = instance._.createHtml(item);
// assert.strictEqual($item.data('item'), item);
// });
// it('sets item.$view as reference to $item', function () {
// var item = this.createItem();
// var instance = this.applyFn();
// var $item = instance._.createHtml(item);
// assert.strictEqual(item.$view, $item);
// });
// });
}); });
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
this.xContent.$el = $('<div id="content"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
});
describe('application', function () {
it('returns object with 12 properties', function () {
var instance = this.applyFn();
assert.isPlainObject(instance);
assert.lengthOfKeys(instance, 12);
});
it('adds HTML #view to #content', function () {
this.applyFn();
assert.lengthOf($('#content > #view'), 1);
});
it('adds HTML #items to #view', function () {
this.applyFn();
assert.lengthOf($('#view > #items'), 1);
});
it('adds HTML #view-hint to #view', function () {
this.applyFn();
assert.lengthOf($('#view > #view-hint'), 1);
});
it('adds style to head', function () {
var styleTagCount = $('head > style').length;
this.applyFn();
assert.lengthOf($('head > style'), styleTagCount + 1);
});
it('style contains possibly correct text', function () {
this.xSettings.sizes = [20];
this.applyFn();
var text = $('head > style').eq(0).text();
assert.isTrue(text.indexOf('#view.view-details.view-size-20 ') >= 0);
assert.isTrue(text.indexOf('#view.view-grid.view-size-20 ') >= 0);
assert.isTrue(text.indexOf('#view.view-icons.view-size-20 ') >= 0);
});
it('sets default metric', function () {
this.applyFn();
assert.isTrue(this.xFormat.setDefaultMetric.calledOnce);
});
it('subscribes to 2 events', function () {
this.applyFn();
assert.isTrue(this.xEvent.sub.calledTwice);
});
it('subscribes to location.changed', function () {
this.applyFn();
assert.strictEqual(this.xEvent.sub.firstCall.args[0], 'location.changed');
assert.isFunction(this.xEvent.sub.firstCall.args[1]);
});
it('subscribes to location.refreshed', function () {
this.applyFn();
assert.strictEqual(this.xEvent.sub.secondCall.args[0], 'location.refreshed');
assert.isFunction(this.xEvent.sub.secondCall.args[1]);
});
});
describe('.$el', function () {
it('is $(\'#view\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$el);
assert.lengthOf(instance.$el, 1);
assert.isString(instance.$el.jquery);
assert.strictEqual(instance.$el.attr('id'), 'view');
});
});
describe('.$items', function () {
it('is $(\'#items\')', function () {
var instance = this.applyFn();
assert.isObject(instance.$items);
assert.lengthOf(instance.$items, 1);
assert.isString(instance.$items.jquery);
assert.strictEqual(instance.$items.attr('id'), 'items');
});
});
describe('.setItems()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setItems));
});
it('publishes view.changed', function () {
var instance = this.applyFn();
instance.setItems();
assert.isTrue(this.xEvent.pub.calledTwice);
assert.strictEqual(this.xEvent.pub.lastCall.args[0], 'view.changed');
});
});
describe('.changeItems()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.changeItems));
});
it('publishes view.changed', function () {
var instance = this.applyFn();
instance.setItems();
assert.isTrue(this.xEvent.pub.calledTwice);
assert.strictEqual(this.xEvent.pub.lastCall.args[0], 'view.changed');
});
});
describe('.setLocation()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setLocation));
});
it('publishes view.changed', function () {
var instance = this.applyFn();
instance.setItems();
assert.isTrue(this.xEvent.pub.calledTwice);
assert.strictEqual(this.xEvent.pub.lastCall.args[0], 'view.changed');
});
});
describe('.setHint()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setHint));
});
it('sets correct class to #view-hint', function () {
var key = uniq.id();
var instance = this.applyFn();
instance.setHint(key);
assert.strictEqual($('#view-hint').attr('class'), 'l10n-' + key);
});
it('removes all other classes from #view-hint', function () {
var key = uniq.id();
var instance = this.applyFn();
$('#view-hint').addClass('a');
instance.setHint(key);
assert.strictEqual($('#view-hint').attr('class'), 'l10n-' + key);
});
});
describe('.getModes()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getModes));
});
});
describe('.getMode()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getMode));
});
});
describe('.setMode()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setMode));
});
it('.setMode(\'details\') changes #view class to .view-details', function () {
this.xSettings.view.modes = ['details', 'grid', 'icons'];
var instance = this.applyFn();
instance.setMode('details');
assert.isTrue($('#view').hasClass('view-details'));
assert.isFalse($('#view').hasClass('view-grid'));
assert.isFalse($('#view').hasClass('view-icons'));
});
it('.setMode(\'grid\') changes #view class to .view-grid', function () {
this.xSettings.view.modes = ['details', 'grid', 'icons'];
var instance = this.applyFn();
instance.setMode('grid');
assert.isFalse($('#view').hasClass('view-details'));
assert.isTrue($('#view').hasClass('view-grid'));
assert.isFalse($('#view').hasClass('view-icons'));
});
it('.setMode(\'icons\') changes #view class to .view-icons', function () {
this.xSettings.view.modes = ['details', 'grid', 'icons'];
var instance = this.applyFn();
instance.setMode('icons');
assert.isFalse($('#view').hasClass('view-details'));
assert.isFalse($('#view').hasClass('view-grid'));
assert.isTrue($('#view').hasClass('view-icons'));
});
});
describe('.getSizes()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getSizes));
});
it('returns sorted sizes', function () {
this.xSettings.view.sizes = [20, 60, 40];
var instance = this.applyFn();
assert.deepEqual(instance.getSizes(), [20, 40, 60]);
});
it('returns sorted sizes', function () {
this.xSettings.view.sizes = [60, 40, 20];
var instance = this.applyFn();
assert.deepEqual(instance.getSizes(), [20, 40, 60]);
});
});
describe('.getSize()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.getSize));
});
});
describe('.setSize()', function () {
it('is function', function () {
var instance = this.applyFn();
assert.isTrue(_.isFunction(instance.setSize));
});
it('.setSize(20) changes #view class to .view-size-20', function () {
this.xSettings.view.sizes = [20, 40, 60];
var instance = this.applyFn();
instance.setSize(20);
assert.isTrue($('#view').hasClass('view-size-20'), 20);
assert.isFalse($('#view').hasClass('view-size-40'), 40);
assert.isFalse($('#view').hasClass('view-size-60'), 60);
});
it('.setSize(40) changes #view class to .view-size-40', function () {
this.xSettings.view.sizes = [20, 40, 60];
var instance = this.applyFn();
instance.setSize(20);
instance.setSize(40);
assert.isFalse($('#view').hasClass('view-size-20'), 20);
assert.isTrue($('#view').hasClass('view-size-40'), 40);
assert.isFalse($('#view').hasClass('view-size-60'), 60);
});
it('.setSize(60) changes #view class to .view-size-60', function () {
this.xSettings.view.sizes = [20, 40, 60];
var instance = this.applyFn();
instance.setSize(20);
instance.setSize(60);
assert.isFalse($('#view').hasClass('view-size-20'), 20);
assert.isFalse($('#view').hasClass('view-size-40'), 40);
assert.isTrue($('#view').hasClass('view-size-60'), 60);
});
});
// describe('._.createHtml()', function () {
// before(function () {
// this.createItem = function () {
// return {
// isFolder: sinon.stub().returns(false),
// label: uniq.id(),
// time: 0,
// size: 0,
// type: uniq.id(),
// isManaged: false,
// icon: null,
// isCurrentParentFolder: sinon.stub().returns(false)
// };
// };
// });
// it('is function', function () {
// var instance = this.applyFn();
// assert.isFunction(instance._.createHtml);
// });
// it('returns jQuery instance of single HTML element', function () {
// var item = this.createItem();
// var instance = this.applyFn();
// var $item = instance._.createHtml(item);
// assert.isObject($item);
// assert.lengthOf($item, 1);
// assert.isString($item.jquery);
// });
// it('$item.data(\'item\') is back reference to item', function () {
// var item = this.createItem();
// var instance = this.applyFn();
// var $item = instance._.createHtml(item);
// assert.strictEqual($item.data('item'), item);
// });
// it('sets item.$view as reference to $item', function () {
// var item = this.createItem();
// var instance = this.applyFn();
// var $item = instance._.createHtml(item);
// assert.strictEqual(item.$view, $item);
// });
// });
});
}()); }());

View File

@@ -1,219 +1,189 @@
(function () { (function () {
'use strict'; var ID = 'view/viewmode';
var DEPS = ['_', '$', 'core/event', 'core/resource', 'core/settings', 'view/sidebar', 'view/topbar', 'view/view'];
var ID = 'view/viewmode'; describe('module \'' + ID + '\'', function () {
var DEPS = ['_', '$', 'core/event', 'core/resource', 'core/settings', 'view/sidebar', 'view/topbar', 'view/view']; before(function () {
this.definition = modulejs._private.definitions[ID];
describe('module \'' + ID + '\'', function () { this.xEvent = {
sub: sinon.stub(),
pub: sinon.stub()
};
this.xResource = {
image: sinon.stub().returns(uniq.path('-image.png'))
};
this.xSettings = {view: {
modeToggle: false
}};
this.xSidebar = {$el: null};
this.xTopbar = {$el: null};
this.xView = {
$el: null,
getModes: sinon.stub().returns(['details', 'grid', 'icons']),
getMode: sinon.stub(),
setMode: sinon.stub(),
getSizes: sinon.stub().returns([20, 30, 40]),
getSize: sinon.stub(),
setSize: sinon.stub()
};
before(function () { this.applyFn = function () {
this.xEvent.sub.reset();
this.xEvent.pub.reset();
this.xResource.image.reset();
this.xView.getModes.reset();
this.xView.getMode.reset();
this.xView.setMode.reset();
this.xView.getSizes.reset();
this.xView.getSize.reset();
this.xView.setSize.reset();
this.definition = modulejs._private.definitions[ID]; return this.definition.fn(_, $, this.xEvent, this.xResource, this.xSettings, this.xSidebar, this.xTopbar, this.xView);
};
this.xEvent = {
sub: sinon.stub(),
pub: sinon.stub()
};
this.xResource = {
image: sinon.stub().returns(uniq.path('-image.png'))
};
this.xSettings = {view: {
modeToggle: false
}};
this.xSidebar = {$el: null};
this.xTopbar = {$el: null};
this.xView = {
$el: null,
getModes: sinon.stub().returns(['details', 'grid', 'icons']),
getMode: sinon.stub(),
setMode: sinon.stub(),
getSizes: sinon.stub().returns([20, 30, 40]),
getSize: sinon.stub(),
setSize: sinon.stub()
};
this.applyFn = function () {
this.xEvent.sub.reset();
this.xEvent.pub.reset();
this.xResource.image.reset();
this.xView.getModes.reset();
this.xView.getMode.reset();
this.xView.setMode.reset();
this.xView.getSizes.reset();
this.xView.getSize.reset();
this.xView.setSize.reset();
return this.definition.fn(_, $, this.xEvent, this.xResource, this.xSettings, this.xSidebar, this.xTopbar, this.xView);
};
});
after(function () {
util.restoreHtml();
});
beforeEach(function () {
util.restoreHtml();
this.xSidebar.$el = $('<div id="sidebar"/>').appendTo('body');
this.xTopbar.$el = $('<div id="topbar"/>').appendTo('body');
this.xView.$el = $('<div id="view"/>').appendTo('body');
});
describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
}); });
it('has correct id', function () { after(function () {
util.restoreHtml();
assert.strictEqual(this.definition.id, ID);
}); });
it('requires correct', function () { beforeEach(function () {
util.restoreHtml();
assert.deepEqual(this.definition.deps, DEPS); this.xSidebar.$el = $('<div id="sidebar"/>').appendTo('body');
this.xTopbar.$el = $('<div id="topbar"/>').appendTo('body');
this.xView.$el = $('<div id="view"/>').appendTo('body');
}); });
it('args for each request', function () { describe('definition', function () {
it('is defined', function () {
assert.isPlainObject(this.definition);
});
assert.strictEqual(this.definition.deps.length, this.definition.fn.length); it('has correct id', function () {
assert.strictEqual(this.definition.id, ID);
});
it('requires correct', function () {
assert.deepEqual(this.definition.deps, DEPS);
});
it('args for each request', function () {
assert.strictEqual(this.definition.deps.length, this.definition.fn.length);
});
it('has no instance', function () {
assert.notProperty(modulejs._private.instances, ID);
});
it('inits without errors', function () {
this.applyFn();
});
}); });
it('has no instance', function () { describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
assert.notProperty(modulejs._private.instances, ID); it('adds HTML #viewmode-settings to #sidebar', function () {
this.applyFn();
assert.lengthOf($('#sidebar > #viewmode-settings'), 1);
});
it('adds HTML #viewmode-details to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-details'), 1);
});
it('adds HTML #viewmode-grid to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-grid'), 1);
});
it('adds HTML #viewmode-icons to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-icons'), 1);
});
it('adds HTML #viewmode-size to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-size'), 1);
});
it('does not add HTML #viewmode-details, #viewmode-grid, #viewmode-icons when only one mode', function () {
this.xView.getModes.returns(['details']);
this.applyFn();
assert.lengthOf($('#viewmode-details'), 0);
assert.lengthOf($('#viewmode-grid'), 0);
assert.lengthOf($('#viewmode-icons'), 0);
});
it('does not add HTML #viewmode-size when only one size', function () {
this.xView.getSizes.returns([20]);
this.applyFn();
assert.lengthOf($('#viewmode-size'), 0);
});
}); });
it('inits without errors', function () { describe('works', function () {
it('clicking #viewmode-details triggers view.setMode(\'details\')', function () {
this.xView.getModes.returns(['details', 'grid', 'icons']);
this.applyFn();
$('#viewmode-details').trigger('click');
assert.isTrue(this.xView.setMode.calledOnce);
assert.deepEqual(this.xView.setMode.lastCall.args, ['details']);
});
this.applyFn(); it('clicking #viewmode-grid triggers view.setMode(\'grid\')', function () {
this.xView.getModes.returns(['details', 'grid', 'icons']);
this.applyFn();
$('#viewmode-grid').trigger('click');
assert.isTrue(this.xView.setMode.calledOnce);
assert.deepEqual(this.xView.setMode.lastCall.args, ['grid']);
});
it('clicking #viewmode-icons triggers view.setMode(\'icons\')', function () {
this.xView.getModes.returns(['details', 'grid', 'icons']);
this.applyFn();
$('#viewmode-icons').trigger('click');
assert.isTrue(this.xView.setMode.calledOnce);
assert.deepEqual(this.xView.setMode.lastCall.args, ['icons']);
});
it('changing #viewmode-size triggers view.setSize(*)', function () {
this.xView.getSizes.returns([20, 40, 60]);
this.applyFn();
$('#viewmode-size').val(0).trigger('change');
assert.isTrue(this.xView.setSize.calledOnce);
assert.deepEqual(this.xView.setSize.lastCall.args, [20]);
$('#viewmode-size').val(1).trigger('change');
assert.isTrue(this.xView.setSize.calledTwice);
assert.deepEqual(this.xView.setSize.lastCall.args, [40]);
$('#viewmode-size').val(2).trigger('change');
assert.isTrue(this.xView.setSize.calledThrice);
assert.deepEqual(this.xView.setSize.lastCall.args, [60]);
});
it('inputing #viewmode-size triggers view.setSize(*)', function () {
this.xView.getSizes.returns([20, 40, 60]);
this.applyFn();
$('#viewmode-size').val(0).trigger('input');
assert.isTrue(this.xView.setSize.calledOnce);
assert.deepEqual(this.xView.setSize.lastCall.args, [20]);
$('#viewmode-size').val(1).trigger('input');
assert.isTrue(this.xView.setSize.calledTwice);
assert.deepEqual(this.xView.setSize.lastCall.args, [40]);
$('#viewmode-size').val(2).trigger('input');
assert.isTrue(this.xView.setSize.calledThrice);
assert.deepEqual(this.xView.setSize.lastCall.args, [60]);
});
}); });
}); });
describe('application', function () {
it('returns undefined', function () {
var instance = this.applyFn();
assert.isUndefined(instance);
});
it('adds HTML #viewmode-settings to #sidebar', function () {
this.applyFn();
assert.lengthOf($('#sidebar > #viewmode-settings'), 1);
});
it('adds HTML #viewmode-details to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-details'), 1);
});
it('adds HTML #viewmode-grid to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-grid'), 1);
});
it('adds HTML #viewmode-icons to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-icons'), 1);
});
it('adds HTML #viewmode-size to #viewmode-settings', function () {
this.applyFn();
assert.lengthOf($('#viewmode-settings > #viewmode-size'), 1);
});
it('does not add HTML #viewmode-details, #viewmode-grid, #viewmode-icons when only one mode', function () {
this.xView.getModes.returns(['details']);
this.applyFn();
assert.lengthOf($('#viewmode-details'), 0);
assert.lengthOf($('#viewmode-grid'), 0);
assert.lengthOf($('#viewmode-icons'), 0);
});
it('does not add HTML #viewmode-size when only one size', function () {
this.xView.getSizes.returns([20]);
this.applyFn();
assert.lengthOf($('#viewmode-size'), 0);
});
});
describe('works', function () {
it('clicking #viewmode-details triggers view.setMode(\'details\')', function () {
this.xView.getModes.returns(['details', 'grid', 'icons']);
this.applyFn();
$('#viewmode-details').trigger('click');
assert.isTrue(this.xView.setMode.calledOnce);
assert.deepEqual(this.xView.setMode.lastCall.args, ['details']);
});
it('clicking #viewmode-grid triggers view.setMode(\'grid\')', function () {
this.xView.getModes.returns(['details', 'grid', 'icons']);
this.applyFn();
$('#viewmode-grid').trigger('click');
assert.isTrue(this.xView.setMode.calledOnce);
assert.deepEqual(this.xView.setMode.lastCall.args, ['grid']);
});
it('clicking #viewmode-icons triggers view.setMode(\'icons\')', function () {
this.xView.getModes.returns(['details', 'grid', 'icons']);
this.applyFn();
$('#viewmode-icons').trigger('click');
assert.isTrue(this.xView.setMode.calledOnce);
assert.deepEqual(this.xView.setMode.lastCall.args, ['icons']);
});
it('changing #viewmode-size triggers view.setSize(*)', function () {
this.xView.getSizes.returns([20, 40, 60]);
this.applyFn();
$('#viewmode-size').val(0).trigger('change');
assert.isTrue(this.xView.setSize.calledOnce);
assert.deepEqual(this.xView.setSize.lastCall.args, [20]);
$('#viewmode-size').val(1).trigger('change');
assert.isTrue(this.xView.setSize.calledTwice);
assert.deepEqual(this.xView.setSize.lastCall.args, [40]);
$('#viewmode-size').val(2).trigger('change');
assert.isTrue(this.xView.setSize.calledThrice);
assert.deepEqual(this.xView.setSize.lastCall.args, [60]);
});
it('inputing #viewmode-size triggers view.setSize(*)', function () {
this.xView.getSizes.returns([20, 40, 60]);
this.applyFn();
$('#viewmode-size').val(0).trigger('input');
assert.isTrue(this.xView.setSize.calledOnce);
assert.deepEqual(this.xView.setSize.lastCall.args, [20]);
$('#viewmode-size').val(1).trigger('input');
assert.isTrue(this.xView.setSize.calledTwice);
assert.deepEqual(this.xView.setSize.lastCall.args, [40]);
$('#viewmode-size').val(2).trigger('input');
assert.isTrue(this.xView.setSize.calledThrice);
assert.deepEqual(this.xView.setSize.lastCall.args, [60]);
});
});
});
}()); }());

View File

@@ -1,17 +1,12 @@
(function () { (function () {
'use strict'; var assert = window.chai.assert;
var assert = chai.assert; assert.lengthOfKeys = function (val, count, msg) {
var keyCount = _.keys(val).length;
assert.lengthOfKeys = function (val, count, msg) { assert(keyCount === count, msg ? msg : 'expected ' + val + ' to have ' + count + ' keys, but has ' + keyCount);
};
var keyCount = _.keys(val).length;
assert(keyCount === count, msg ? msg : 'expected ' + val + ' to have ' + count + ' keys, but has ' + keyCount);
};
assert.isPlainObject = function (val, msg) {
assert($.isPlainObject(val), msg ? msg : 'expected ' + val + ' to be a plain Object');
};
assert.isPlainObject = function (val, msg) {
assert($.isPlainObject(val), msg ? msg : 'expected ' + val + ' to be a plain Object');
};
}()); }());

View File

@@ -1,112 +1,107 @@
(function () { (function () {
'use strict'; var showOnlyFailures = false;
var template =
var showOnlyFailures = false; '<div id="mocha-bar">' +
var template = '<a class="title" href="?">' + document.title + '</a>' +
'<div id="mocha-bar">' + '<div class="stats"/>' +
'<a class="title" href="?">' + document.title + '</a>' + '<div class="progress"/>' +
'<div class="stats"/>' + '</div>';
'<div class="progress"/>' + var $mochaBar = $(template);
'</div>'; var $mochaStats = $mochaBar.find('.stats');
var $mochaBar = $(template); var $mochaProgress = $mochaBar.find('.progress');
var $mochaStats = $mochaBar.find('.stats');
var $mochaProgress = $mochaBar.find('.progress');
function toggleFailureFilter(ev) {
ev.stopImmediatePropagation();
showOnlyFailures = !showOnlyFailures;
if (showOnlyFailures) {
$('.suite, .test').hide();
$('.suite.fail, .test.fail').show();
} else {
$('.suite, .test').show();
}
}
function addSuiteStats() {
var $suite = $(this);
var tests = $suite.find('.test').length;
var passed = $suite.find('.test.pass').length;
var failed = tests - passed;
var $header = $suite.find('> h1 a');
var $list = $suite.find('> ul');
var $count = $('<span class="count"><span class="passed">' + passed + '</span><span class="failed">' + failed + '</span></span>');
var $toggle = $('<span class="toggle">-</span>');
var visible = true;
$toggle.on('click', function (ev) {
function toggleFailureFilter(ev) {
ev.stopImmediatePropagation(); ev.stopImmediatePropagation();
visible = !visible; showOnlyFailures = !showOnlyFailures;
if (visible) { if (showOnlyFailures) {
$toggle.text('-'); $('.suite, .test').hide();
$list.show(); $('.suite.fail, .test.fail').show();
} else { } else {
$toggle.text('+'); $('.suite, .test').show();
$list.hide();
} }
});
if (!failed) {
$count.find('.failed').remove();
} }
$suite.addClass(tests === passed ? 'pass' : 'fail'); function addSuiteStats() {
// $suite.append($toggle); var $suite = $(this);
$header.append($count);
}
function fixCodeFormatting() { var tests = $suite.find('.test').length;
var $code = $(this); var passed = $suite.find('.test.pass').length;
$code.text($code.text().trim().replace(/;\n\s*/g, ';\n')); var failed = tests - passed;
}
var $header = $suite.find('> h1 a');
var $list = $suite.find('> ul');
var $count = $('<span class="count"><span class="passed">' + passed + '</span><span class="failed">' + failed + '</span></span>');
var $toggle = $('<span class="toggle">-</span>');
var visible = true;
function onEnd() { $toggle.on('click', function (ev) {
var runner = this; ev.stopImmediatePropagation();
var failed = runner.stats.failures > 0;
var stats = (runner.stats.duration / 1000.0).toFixed(3) + 's';
if (failed) { visible = !visible;
$mochaStats.on('click', toggleFailureFilter); if (visible) {
$toggle.text('-');
$list.show();
} else {
$toggle.text('+');
$list.hide();
}
});
if (!failed) {
$count.find('.failed').remove();
}
$suite.addClass(tests === passed ? 'pass' : 'fail');
// $suite.append($toggle);
$header.append($count);
} }
$mochaBar.addClass(failed ? 'fail' : 'pass'); function fixCodeFormatting() {
$mochaProgress.hide(); var $code = $(this);
$mochaStats.text(stats); $code.text($code.text().trim().replace(/;\n\s*/g, ';\n'));
$('#mocha-report .suite').each(addSuiteStats);
$('#mocha-report code').each(fixCodeFormatting);
}
function onTest() {
var runner = this;
var percent = 100.0 * runner.stats.tests / runner.total;
var stats = ((new Date().getTime() - runner.stats.start) / 1000.0).toFixed(3) + 's';
if (runner.stats.failures) {
$mochaBar.addClass('fail');
} }
$mochaProgress.css('width', (100 - percent) + '%');
$mochaStats.text(stats);
}
function setupMocha() {
window.assert = chai.assert;
mocha.setup('bdd');
$(function () { $mochaBar.appendTo('#mocha'); });
}
function runMocha() { function onEnd() {
mocha.run().on('test', onTest).on('end', onEnd); var runner = this;
} var failed = runner.stats.failures > 0;
var stats = (runner.stats.duration / 1000.0).toFixed(3) + 's';
window.util = window.util || {}; if (failed) {
window.util.setupMocha = setupMocha; $mochaStats.on('click', toggleFailureFilter);
window.util.runMocha = runMocha; }
$mochaBar.addClass(failed ? 'fail' : 'pass');
$mochaProgress.hide();
$mochaStats.text(stats);
$('#mocha-report .suite').each(addSuiteStats);
$('#mocha-report code').each(fixCodeFormatting);
}
function onTest() {
var runner = this;
var percent = 100.0 * runner.stats.tests / runner.total;
var stats = ((new Date().getTime() - runner.stats.start) / 1000.0).toFixed(3) + 's';
if (runner.stats.failures) {
$mochaBar.addClass('fail');
}
$mochaProgress.css('width', 100 - percent + '%');
$mochaStats.text(stats);
}
function setupMocha() {
window.assert = window.chai.assert;
mocha.setup('bdd');
$(function () { $mochaBar.appendTo('#mocha'); });
}
function runMocha() {
mocha.run().on('test', onTest).on('end', onEnd);
}
window.util = window.util || {};
window.util.setupMocha = setupMocha;
window.util.runMocha = runMocha;
}()); }());

View File

@@ -1,21 +1,15 @@
(function () { (function () {
'use strict'; function clearModulejs() {
_.each(modulejs._private.instances, function (val, key) {
delete modulejs._private.instances[key];
});
}
function clearModulejs() { function mockConfigModule() {
modulejs.define('config', window.uniq.obj());
_.each(modulejs._private.instances, function (val, key) { }
delete modulejs._private.instances[key];
});
}
function mockConfigModule() {
modulejs.define('config', window.uniq.obj());
}
window.util = window.util || {};
window.util.clearModulejs = clearModulejs;
window.util.mockConfigModule = mockConfigModule;
window.util = window.util || {};
window.util.clearModulejs = clearModulejs;
window.util.mockConfigModule = mockConfigModule;
}()); }());

View File

@@ -1,38 +1,33 @@
(function () { (function () {
'use strict'; var title;
var htmlId;
var htmlClasses;
var bodyId;
var bodyClasses;
var $pinnedElements;
var title; function pinHtml() {
var htmlId; title = document.title;
var htmlClasses; htmlId = $('html').attr('id');
var bodyId; htmlClasses = $('html').attr('class');
var bodyClasses; bodyId = $('body').attr('id');
var $pinnedElements; bodyClasses = $('body').attr('class');
$pinnedElements = $('head,body').children();
function pinHtml() {
title = document.title;
htmlId = $('html').attr('id');
htmlClasses = $('html').attr('class');
bodyId = $('body').attr('id');
bodyClasses = $('body').attr('class');
$pinnedElements = $('head,body').children();
}
function restoreHtml() {
document.title = title;
$('html').attr('id', htmlId);
$('html').attr('class', htmlClasses);
$('body').attr('id', bodyId);
$('body').attr('class', bodyClasses);
$('head,body').children().not($pinnedElements).remove();
if (window.localStorage && window.localStorage.clear) {
window.localStorage.clear();
} }
}
window.util = window.util || {}; function restoreHtml() {
window.util.pinHtml = pinHtml; document.title = title;
window.util.restoreHtml = restoreHtml; $('html').attr('id', htmlId);
$('html').attr('class', htmlClasses);
$('body').attr('id', bodyId);
$('body').attr('class', bodyClasses);
$('head,body').children().not($pinnedElements).remove();
if (window.localStorage && window.localStorage.clear) {
window.localStorage.clear();
}
}
window.util = window.util || {};
window.util.pinHtml = pinHtml;
window.util.restoreHtml = restoreHtml;
}()); }());