feature(client) es2015-ify

This commit is contained in:
coderaiser 2017-02-09 14:44:27 +02:00
parent 8944d1522e
commit 6a5b254a75
79 changed files with 7365 additions and 9347 deletions

View file

@ -1,15 +0,0 @@
{
"env": {
"node": true,
"browser": true
},
"parserOptions": {
"ecmaVersion": 5,
"sourceType": "module"
},
"rules": {
"indent": ["error", 4],
"semi": "error"
},
"extends": ["eslint:recommended"]
}

View file

@ -1,19 +0,0 @@
{
"unused" : true,
"bitwise" : false,
"browser" : true,
"devel" : true,
"eqeqeq" : true,
"jquery" : false,
"newcap" : false,
"noarg" : true,
"node" : true,
"noempty" : true,
"nonew" : true,
"strict" : true,
"undef" : true,
"evil" : true,
"expr" : true,
"quotmark": "single",
"validthis": true
}

5
.gitignore vendored
View file

@ -12,8 +12,6 @@ modules/fancybox/lib/
modules/fancybox/demo modules/fancybox/demo
modules/fancybox/sprite.psd modules/fancybox/sprite.psd
modules/currify/dist/currify.js
legacy legacy
server_ server_
@ -21,3 +19,6 @@ server_
*.swp *.swp
dist
dist-debug

View file

@ -13,8 +13,10 @@ circle.yml
bin/release.js bin/release.js
bin/legacy.js bin/legacy.js
.es5 client
legacy/bin/release.js legacy/bin/release.js
legacy/bin/legacy.js legacy/bin/legacy.js
webpack.config.js

View file

@ -30,19 +30,13 @@
"dependencies": { "dependencies": {
"domtokenlist-shim": "~1.1.0", "domtokenlist-shim": "~1.1.0",
"fancybox": "~2.1.5", "fancybox": "~2.1.5",
"format-io": "~0.9.6",
"rendy": "~1.1.0",
"execon": "~1.2.8",
"emitify": "~2.1.1", "emitify": "~2.1.1",
"findit": "^1.1.5", "findit": "^1.1.5",
"menu": "~1.0.2", "menu": "~1.0.2",
"olark": "^1.0.0", "olark": "^1.0.0",
"philip": "^1.3.3", "philip": "^1.3.3",
"jonny": "1.0.1",
"promise-polyfill": "6.0.2", "promise-polyfill": "6.0.2",
"smalltalk": "2.1.3", "smalltalk": "2.1.3",
"jquery": "3.1.1", "jquery": "3.1.1"
"currify": "2.0.3",
"itype": "2.0.3"
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,63 +1,61 @@
/* global CloudCmd, Util, DOM, filepicker */ /* global CloudCmd, Util, DOM, filepicker */
(function(CloudCmd, Util, DOM) { 'use strict';
'use strict';
CloudCmd.Cloud = CloudProto;
CloudCmd.Cloud = CloudProto;
function CloudProto(callback) {
function CloudProto(callback) { function init(callback) {
function init(callback) { Util.exec.series([
Util.exec.series([ load,
load, callback,
callback, ]);
]);
}
this.uploadFile = function(name, data) {
var log = CloudCmd.log;
filepicker.store(data, {
mimetype: '',
filename: name
},
function(fpFile) {
log(fpFile);
filepicker.exportFile(fpFile, log, log);
});
};
this.saveFile = function(callback) {
filepicker.pick(function(fpFile) {
console.log(fpFile);
DOM.load.ajax({
url : fpFile.url,
responseType : 'arraybuffer',
success : function(data) {
Util.exec(callback, fpFile.filename, data);
}
});
});
};
function load(callback) {
Util.time('filepicker load');
DOM.load.js('//api.filepicker.io/v1/filepicker.js', function() {
DOM.Files.get('modules', function(error, modules) {
var storage = Util.findObjByNameInArr(modules, 'storage'),
picker = Util.findObjByNameInArr(storage, 'FilePicker'),
key = picker && picker.key;
filepicker.setKey(key);
DOM.Images.hide();
Util.timeEnd('filepicker loaded');
Util.exec(callback);
});
});
}
init(callback);
} }
})(CloudCmd, Util, DOM);
this.uploadFile = function(name, data) {
var log = CloudCmd.log;
filepicker.store(data, {
mimetype: '',
filename: name
},
function(fpFile) {
log(fpFile);
filepicker.exportFile(fpFile, log, log);
});
};
this.saveFile = function(callback) {
filepicker.pick(function(fpFile) {
console.log(fpFile);
DOM.load.ajax({
url : fpFile.url,
responseType : 'arraybuffer',
success : function(data) {
Util.exec(callback, fpFile.filename, data);
}
});
});
};
function load(callback) {
Util.time('filepicker load');
DOM.load.js('//api.filepicker.io/v1/filepicker.js', function() {
DOM.Files.get('modules', function(error, modules) {
var storage = Util.findObjByNameInArr(modules, 'storage'),
picker = Util.findObjByNameInArr(storage, 'FilePicker'),
key = picker && picker.key;
filepicker.setKey(key);
DOM.Images.hide();
Util.timeEnd('filepicker loaded');
Util.exec(callback);
});
});
}
init(callback);
}

View file

@ -1,104 +1,80 @@
var CloudCmd; 'use strict';
(function() { window.CloudCmd = (config) => {
'use strict'; window.Util = require('../common/util');
window.CloudFunc = require('../common/cloudfunc');
window.DOM = require('./dom');
CloudCmd = load; require('./events');
require('./storage');
require('./files');
require('./rest');
require('./load');
require('./notify');
require('./dialog');
function load(config) { window.CloudCmd = require('./client');
var prefix = getPrefix(config.prefix);
var modules = '/modules/';
var client = 'client/';
var files = [
'common/util',
'common/cloudfunc',
client + 'dom',
client + 'events',
client + 'rest',
client + 'load',
client + 'notify',
client + 'storage',
client + 'files',
client + 'dialog',
'client/client',
client + 'buffer',
client + 'listeners',
client + 'key',
client + 'directory',
client + 'sort'
];
var moduleFiles = [
window.Promise ? '' : 'promise-polyfill/promise.min',
libDir('format', 'format-io'),
libDir('rendy'),
libDir('exec', 'execon'),
libDir('jonny'),
libDist('emitify'),
libDist('currify'),
libDist('itype'),
].filter(function(name) {
return name;
}).map(function(name) {
return modules + name;
});
var allFiles = moduleFiles
.concat(files)
.concat('/join/join')
.map(function(name) {
return name + '.js';
});
var urlFiles = getJoinURL(allFiles);
createScript(prefix + urlFiles, function() {
CloudCmd.init(prefix, config);
});
}
function libDir(name, dir) { require('./buffer');
var lib = '/lib/'; require('./listeners');
require('./key');
if (!dir) require('./directory');
dir = name; require('./sort');
return dir + lib + name;
}
function libDist(name) { window.exec = require('execon');
return name + '/dist/' + name + '.min'; window.rendy = require('rendy');
}
function getPrefix(prefix) { const modules = '/modules/';
if (!prefix)
return '';
if (!prefix.indexOf('/'))
return prefix;
return '/' + prefix;
}
function createScript(url, callback) { var moduleFiles = [
var script = document.createElement('script'); window.Promise ? '' : 'promise-polyfill/promise.min',
].filter((name) => {
script.src = url; return name;
script.async = true; }).map((name) => {
return modules + name;
script.addEventListener('load', function load(event) { });
callback(event);
script.removeEventListener('load', load); const allFiles = moduleFiles
}); .concat('/join/join')
.map((name) => `${name}.js`);
document.body.appendChild(script);
} const urlFiles = getJoinURL(allFiles);
function getJoinURL(names) { const prefix = getPrefix(config.prefix);
var prefix = '/join:';
var url = prefix + names.join(':'); createScript(prefix + urlFiles, () => {
window.CloudCmd.init(prefix, config);
return url; });
} };
})();
function getPrefix(prefix) {
if (!prefix)
return '';
if (!prefix.indexOf('/'))
return prefix;
return '/' + prefix;
}
function createScript(url, callback) {
var script = document.createElement('script');
script.src = url;
script.async = true;
script.addEventListener('load', function load(event) {
callback(event);
script.removeEventListener('load', load);
});
document.body.appendChild(script);
}
function getJoinURL(names) {
const prefix = '/join:';
const url = prefix + names.join(':');
return url;
}

View file

@ -1,305 +1,300 @@
var CloudCmd, Util, DOM, io; 'use strict';
(function(CloudCmd, Util, DOM) { /* global CloudCmd, DOM, io */
'use strict';
const rendy = require('rendy');
const exec = require('execon');
const input = require('./input');
CloudCmd.Config = ConfigProto;
function ConfigProto() {
const config = CloudCmd.config;
const Key = CloudCmd.Key;
const Dialog = DOM.Dialog;
const Images = DOM.Images;
const Events = DOM.Events;
const Files = DOM.Files;
/* global rendy */ const showLoad = () => {
/* global input */ Images.show.load('top');
};
CloudCmd.Config = ConfigProto; const TITLE = 'Config';
const Notify = DOM.Notify;
const Config = this;
let Loading = true;
let Element;
let Template;
function init() {
Loading = true;
function ConfigProto() { showLoad();
var config = CloudCmd.config; exec.series([
var Loading = true, CloudCmd.View,
Key = CloudCmd.Key, function(callback) {
Dialog = DOM.Dialog, Loading = false;
Images = DOM.Images, exec(callback);
Events = DOM.Events, DOM.loadSocket(initSocket);
Files = DOM.Files,
showLoad = function() {
Images.show.load('top');
}, },
Config.show
]);
}
function getHost() {
var l = location,
href = l.origin || l.protocol + '//' + l.host;
return href;
}
function initSocket(error) {
var href = getHost();
var prefix = CloudCmd.PREFIX,
FIVE_SECONDS = 5000,
save = function(data) {
onSave(data);
socket.send(data);
};
Element, if (error)
Template, return;
TITLE = 'Config', var socket = io.connect(href + prefix + '/config', {
'max reconnection attempts' : Math.pow(2, 32),
Notify = DOM.Notify, 'reconnection limit' : FIVE_SECONDS,
Config = this; path: prefix + '/socket.io'
});
function init() {
Loading = true; authCheck(socket);
socket.on('connect', function() {
Config.save = save;
});
socket.on('config', function(config) {
DOM.Storage.setAllowed(config.localStorage);
});
socket.on('message', function(data) {
onSave(data);
});
socket.on('log', function(msg) {
CloudCmd.log(msg);
});
socket.on('disconnect', function() {
Config.save = saveHttp;
});
socket.on('err', function(error) {
Dialog.alert(TITLE, error);
});
}
function authCheck(socket) {
if (!config('auth'))
return;
socket.emit('auth', config('username'), config('password'));
socket.on('reject', function() {
Dialog.alert(TITLE, 'Wrong credentials!');
});
}
Config.save = saveHttp;
this.show = function() {
var prefix = CloudCmd.PREFIX,
funcs = [
exec.with(Files.get, 'config-tmpl'),
exec.with(DOM.load.parallel, [
prefix + '/css/config.css'
])
];
if (!Loading) {
showLoad(); showLoad();
Util.exec.series([ exec.parallel(funcs, fillTemplate);
CloudCmd.View,
function(callback) {
Loading = false;
Util.exec(callback);
DOM.loadSocket(initSocket);
},
Config.show
]);
} }
};
function fillTemplate(error, template) {
if (!Template)
Template = template;
function getHost() { Files.get('config', (error, config) => {
var l = location, if (error)
href = l.origin || l.protocol + '//' + l.host; return Dialog.alert(TITLE, 'Could not load config!');
return href; const obj = input.convert(config);
obj[obj.editor + '-selected'] = 'selected';
delete obj.editor;
obj[obj.packer + '-selected'] = 'selected';
delete obj.packer;
const inner = rendy(Template, obj);
Element = DOM.load({
name : 'div',
className : 'config',
inner,
attribute : {
'data-name': 'js-config'
}
});
const inputs = document.querySelectorAll('input, select', Element);
const inputFirst = inputs[0];
let focus;
if (inputFirst) {
onAuthChange(inputFirst.checked);
focus = () => {
inputFirst.focus();
};
}
[].forEach.call(inputs, (input) => {
Events.addKey(input, onKey)
.add('change', input, ({target}) => {
onChange(target);
});
});
CloudCmd.View.show(Element, {
autoSize: true,
afterShow: focus
});
});
}
this.hide = () => {
CloudCmd.View.hide();
};
function onChange(el) {
var obj = {},
name = input.getName(el),
data = input.getValue(name, Element),
type = el.type;
if (type === 'checkbox')
if (/^(diff|buffer|dirStorage)$/.test(name))
onLSChange(name, data);
else if (name === 'localStorage')
onLocalStorageChange();
else if (name === 'auth')
onAuthChange(data);
if (name === 'notifications') {
if (data && !Notify.check())
Notify.request();
} }
function initSocket(error) { obj[name] = data;
var href = getHost();
var prefix = CloudCmd.PREFIX, Config.save(obj);
FIVE_SECONDS = 5000, }
save = function(data) {
onSave(data); function onSave(obj) {
socket.send(data); Object.keys(obj).forEach((name) => {
}; const data = obj[name];
CloudCmd._config(name, data);
input.setValue(name, data, Element);
});
DOM.Storage.setAllowed(obj.localStorage);
}
function saveHttp(obj) {
const {RESTful} = DOM;
RESTful.Config.write(obj, (error) => {
if (error) if (error)
return; return;
var socket = io.connect(href + prefix + '/config', { onSave(obj);
'max reconnection attempts' : Math.pow(2, 32), });
'reconnection limit' : FIVE_SECONDS,
path: prefix + '/socket.io'
});
authCheck(socket);
socket.on('connect', function() {
Config.save = save;
});
socket.on('config', function(config) {
DOM.Storage.setAllowed(config.localStorage);
});
socket.on('message', function(data) {
onSave(data);
});
socket.on('log', function(msg) {
CloudCmd.log(msg);
});
socket.on('disconnect', function() {
Config.save = saveHttp;
});
socket.on('err', function(error) {
Dialog.alert(TITLE, error);
});
}
function authCheck(socket) {
if (!config('auth'))
return;
socket.emit('auth', config('username'), config('password'));
socket.on('reject', function() {
Dialog.alert(TITLE, 'Wrong credentials!');
});
}
Config.save = saveHttp;
this.show = function() {
var prefix = CloudCmd.PREFIX,
exec = Util.exec,
funcs = [
exec.with(Files.get, 'config-tmpl'),
exec.with(DOM.load.parallel, [
prefix + '/css/config.css',
prefix + CloudCmd.DIRCLIENT + 'input.js'
])
];
if (!Loading) {
showLoad();
exec.parallel(funcs, fillTemplate);
}
};
function fillTemplate(error, template) {
if (!Template)
Template = template;
Files.get('config', function(error, config) {
var data, inputs, inputFirst,
focus, obj;
if (error)
return Dialog.alert(TITLE, 'Could not load config!');
obj = input.convert(config);
obj[obj.editor + '-selected'] = 'selected';
delete obj.editor;
obj[obj.packer + '-selected'] = 'selected';
delete obj.packer;
data = rendy(Template, obj);
Element = DOM.load({
name : 'div',
className : 'config',
inner : data,
attribute : {
'data-name': 'js-config'
}
});
inputs = document.querySelectorAll('input, select', Element);
inputFirst = inputs[0];
if (inputFirst) {
onAuthChange(inputFirst.checked);
focus = function() {
inputFirst.focus();
};
}
[].forEach.call(inputs, function(input) {
Events.addKey(input, onKey)
.add('change', input, function(event) {
onChange(event.target);
});
});
CloudCmd.View.show(Element, {
autoSize: true,
afterShow: focus
});
});
}
this.hide = function() {
CloudCmd.View.hide();
};
function onChange(el) {
var obj = {},
name = input.getName(el),
data = input.getValue(name, Element),
type = el.type;
if (type === 'checkbox')
if (/^(diff|buffer|dirStorage)$/.test(name))
onLSChange(name, data);
else if (name === 'localStorage')
onLocalStorageChange();
else if (name === 'auth')
onAuthChange(data);
if (name === 'notifications') {
if (data && !Notify.check())
Notify.request();
}
obj[name] = data;
Config.save(obj);
}
function onSave(obj) {
Object.keys(obj).forEach(function(name) {
var data = obj[name];
CloudCmd._config(name, data);
input.setValue(name, data, Element);
});
DOM.Storage.setAllowed(obj.localStorage);
}
function saveHttp(obj) {
var RESTful = DOM.RESTful;
RESTful.Config.write(obj, function(error) {
if (!error)
onSave(obj);
});
}
function onLocalStorageChange() {
var names = ['diff', 'buffer', 'dirStorage', 'localStorage'],
elements = names.map(function(name) {
return input.getElementByName(name, Element);
}),
el = {},
msg = 'Diff, Buffer and Directory Storage do not work without localStorage',
isChecked;
elements.forEach(function(element) {
var name = input.getName(element);
el[name] = element;
if (element.checked)
isChecked = true;
});
if (isChecked && !el.localStorage.checked) {
Dialog.alert(TITLE, msg);
elements.forEach(function(element) {
if (element.checked) {
element.checked = false;
onChange(element);
}
return element;
});
}
}
function onLSChange(name, data) {
var elLocalStorage = input.getElementByName('localStorage', Element),
msg = name + ' depends on localStorage';
if (data && !elLocalStorage.checked) {
Dialog.alert(TITLE, msg);
elLocalStorage.checked = true;
}
}
function onAuthChange(checked) {
var elUsername = input.getElementByName('username', Element),
elPassword = input.getElementByName('password', Element);
elUsername.disabled =
elPassword.disabled = !checked;
}
function onKey(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case Key.ESC:
Config.hide();
break;
case Key.ENTER:
onChange(event.target);
break;
}
}
if (!CloudCmd.config('configDialog'))
return;
init();
} }
})(CloudCmd, Util, DOM); function onLocalStorageChange() {
var names = ['diff', 'buffer', 'dirStorage', 'localStorage'],
elements = names.map(function(name) {
return input.getElementByName(name, Element);
}),
el = {},
msg = 'Diff, Buffer and Directory Storage do not work without localStorage',
isChecked;
elements.forEach((element) => {
const name = input.getName(element);
el[name] = element;
if (element.checked)
isChecked = true;
});
if (!isChecked || el.localStorage.checked)
return;
Dialog.alert(TITLE, msg);
elements.forEach((element) => {
if (element.checked) {
element.checked = false;
onChange(element);
}
return element;
});
}
function onLSChange(name, data) {
const elLocalStorage = input.getElementByName('localStorage', Element);
const msg = name + ' depends on localStorage';
if (!data || elLocalStorage.checked)
return;
Dialog.alert(TITLE, msg);
elLocalStorage.checked = true;
}
function onAuthChange(checked) {
const elUsername = input.getElementByName('username', Element);
const elPassword = input.getElementByName('password', Element);
elUsername.disabled =
elPassword.disabled = !checked;
}
function onKey({keyCode, target}) {
switch (keyCode) {
case Key.ESC:
Config.hide();
break;
case Key.ENTER:
onChange(target);
break;
}
}
if (!CloudCmd.config('configDialog'))
return;
init();
}

View file

@ -2,124 +2,109 @@
/* global CloudFunc */ /* global CloudFunc */
/* global DOM */ /* global DOM */
(function() { 'use strict';
'use strict';
module.exports = uploadDirectory;
function uploadDirectory(items) {
const Images = DOM.Images;
const Info = DOM.CurrentInfo;
const load = DOM.load;
const Dialog = DOM.Dialog;
if (typeof module !== 'undefined' && module.exports) let array = [
module.exports = uploadDirectory; 'findit',
else 'philip'
DOM.uploadDirectory = uploadDirectory; ];
function uploadDirectory(items) { if (items.length)
var entries,
Images = DOM.Images,
Info = DOM.CurrentInfo,
load = DOM.load,
Dialog = DOM.Dialog,
url = '',
array = [
'findit',
'philip'
];
if (items.length)
Images.show('top');
entries = [].map.call(items, function(item) {
return item.webkitGetAsEntry();
});
array = array.map(function(name) {
var result = [
'/modules/' + name,
'/lib/' + name,
'.js'
].join('');
return result;
});
if (!window.Emitify)
array.unshift('/modules/emitify/dist/emitify.js');
if (!window.exec)
array.unshift('/modules/execon/lib/exec.js');
url = CloudCmd.join(array);
load.js(url, function() {
var path = Info.dirPath
.replace(/\/$/, ''),
uploader;
uploader = window.philip(entries, function(type, name, data, i, n, callback) {
var upload,
prefixURL = CloudCmd.PREFIX_URL,
FS = CloudFunc.FS,
full = prefixURL + FS + path + name;
switch(type) {
case 'file':
upload = uploadFile(full, data);
break;
case 'directory':
upload = uploadDir(full);
break;
}
upload.on('end', callback);
upload.on('progress', function(count) {
var current = percent(i, n),
next = percent(i + 1, n),
max = next - current,
value = current + percent(count, 100, max);
setProgress(value);
});
});
uploader.on('error', function(error) {
Dialog.alert(error);
uploader.abort();
});
uploader.on('progress', function(count) {
setProgress(count);
});
uploader.on('end', function() {
CloudCmd.refresh();
});
});
}
function percent(i, n, per) {
var value;
if (typeof per === 'undefined')
per = 100;
value = Math.round(i * per / n);
return value;
}
function setProgress(count) {
var Images = DOM.Images;
Images.setProgress(count);
Images.show('top'); Images.show('top');
}
function uploadFile(url, data) { const entries = [].map.call(items, (item) => {
return DOM.load.put(url, data); return item.webkitGetAsEntry();
} });
function uploadDir(url) { array = array.map(function(name) {
return DOM.load.put(url + '?dir'); const result = [
} '/modules/' + name,
'/lib/' + name,
'.js'
].join('');
return result;
});
})(); if (!window.Emitify)
window.Emitify = require('emitify');
if (!window.exec)
window.exec = require('execon');
const url = CloudCmd.join(array);
load.js(url, () => {
const path = Info.dirPath
.replace(/\/$/, '');
const uploader = window.philip(entries, (type, name, data, i, n, callback) => {
const prefixURL = CloudCmd.PREFIX_URL;
const FS = CloudFunc.FS;
const full = prefixURL + FS + path + name;
let upload;
switch(type) {
case 'file':
upload = uploadFile(full, data);
break;
case 'directory':
upload = uploadDir(full);
break;
}
upload.on('end', callback);
upload.on('progress', (count) => {
const current = percent(i, n);
const next = percent(i + 1, n);
const max = next - current;
const value = current + percent(count, 100, max);
setProgress(value);
});
});
uploader.on('error', (error) => {
Dialog.alert(error);
uploader.abort();
});
uploader.on('progress', setProgress);
uploader.on('end', () => {
CloudCmd.refresh();
});
});
}
function percent(i, n, per) {
if (typeof per === 'undefined')
per = 100;
return Math.round(i * per / n);
}
function setProgress(count) {
DOM.Images
.setProgress(count)
.show('top');
}
function uploadFile(url, data) {
return DOM.load.put(url, data);
}
function uploadDir(url) {
return DOM.load.put(url + '?dir');
}

File diff suppressed because it is too large Load diff

View file

@ -1,189 +1,190 @@
var CloudCmd, Util, DOM, CloudFunc, MenuIO, Format; 'use strict';
(function(CloudCmd, Util, DOM) { /* global CloudCmd, DOM, MenuIO, Format */
'use strict';
CloudCmd.EditFile = function EditFileProto(callback) { CloudCmd.EditFile = function EditFileProto(callback) {
var Info = DOM.CurrentInfo; var Info = DOM.CurrentInfo;
var Dialog = DOM.Dialog; var Dialog = DOM.Dialog;
var exec = Util.exec; var EditFile = this;
var EditFile = this; var config = CloudCmd.config;
var config = CloudCmd.config;
let Menu;
var Menu,
const exec = require('execon');
TITLE = 'Edit', const TITLE = 'Edit';
const Images = DOM.Images;
Images = DOM.Images,
MSG_CHANGED, let MSG_CHANGED;
ConfigView = { const ConfigView = {
beforeClose: function() { beforeClose: () => {
exec.ifExist(Menu, 'hide'); exec.ifExist(Menu, 'hide');
isChanged(); isChanged();
}
};
function init(callback) {
var editor;
exec.series([
CloudCmd.Edit,
function(callback) {
editor = CloudCmd.Edit.getEditor();
callback();
},
function(callback) {
authCheck(editor);
callback();
},
function(callback) {
setListeners(editor);
callback();
},
function(callback) {
EditFile.show(callback);
},
], callback);
} }
this.show = function() {
Images.show.load();
Info.getData(function(error, data) {
var path = Info.path;
var isDir = Info.isDir;
var name = Info.name;
if (isDir)
name += '.json';
if (error)
return Images.hide();
setMsgChanged(name);
CloudCmd.Edit
.getEditor()
.setValueFirst(path, data)
.setModeForPath(name)
.setOption('fontSize', 16)
.enableKey();
CloudCmd.Edit.show(ConfigView);
});
};
this.hide = function() {
CloudCmd.Edit.hide();
};
function setListeners(editor) {
var element = CloudCmd.Edit.getElement();
DOM.Events.addOnce('contextmenu', element, setMenu);
editor.on('save', function(value) {
DOM.setCurrentSize(Format.size(value));
});
}
function authCheck(spawn) {
if (!config('auth'))
return;
spawn.emit('auth', config('username'), config('password'));
spawn.on('reject', function() {
Dialog.alert(TITLE, 'Wrong credentials!');
});
}
function setMenu(event) {
var position = {
x: event.clientX,
y: event.clientY
};
event.preventDefault();
!Menu && DOM.loadRemote('menu', function(error) {
var noFocus;
var options = {
beforeShow: function(params) {
params.x -= 18;
params.y -= 27;
},
afterClick: function() {
!noFocus && editor.focus();
}
};
var editor = CloudCmd.Edit.getEditor();
var menuData = {
'Save Ctrl+S' : function() {
editor.save();
},
'Go To Line Ctrl+G' : function() {
noFocus = true;
editor.goToLine();
},
'Cut Ctrl+X' : function() {
editor.cutToClipboard();
},
'Copy Ctrl+C' : function() {
editor.copyToClipboard();
},
'Paste Ctrl+V' : function() {
editor.pasteFromClipboard();
},
'Delete Del' : function() {
editor.remove('right');
},
'Select All Ctrl+A' : function() {
editor.selectAll();
},
'Beautify Ctrl+B' : function() {
editor.beautify();
},
'Minify Ctrl+M' : function() {
editor.minify();
},
'Close Esc' : function() {
EditFile.hide();
}
};
if (error)
return Dialog.alert(TITLE, error);
if (Menu || !MenuIO)
return;
var element = CloudCmd.Edit.getElement();
Menu = new MenuIO(element, options, menuData);
Menu.show(position.x, position.y);
});
}
function setMsgChanged(name) {
MSG_CHANGED = 'Do you want to save changes to ' + name + '?';
}
function isChanged() {
var editor = CloudCmd.Edit.getEditor();
var is = editor.isChanged();
is && Dialog.confirm(TITLE, MSG_CHANGED, {cancel: false})
.then(function() {
editor.save();
});
}
init(callback);
}; };
})(CloudCmd, Util, DOM, CloudFunc); function init(callback) {
var editor;
exec.series([
CloudCmd.Edit,
function(callback) {
editor = CloudCmd.Edit.getEditor();
callback();
},
function(callback) {
authCheck(editor);
callback();
},
function(callback) {
setListeners(editor);
callback();
},
function(callback) {
EditFile.show(callback);
},
], callback);
}
this.show = function() {
Images.show.load();
Info.getData(function(error, data) {
var path = Info.path;
var isDir = Info.isDir;
var name = Info.name;
if (isDir)
name += '.json';
if (error)
return Images.hide();
setMsgChanged(name);
CloudCmd.Edit
.getEditor()
.setValueFirst(path, data)
.setModeForPath(name)
.setOption('fontSize', 16)
.enableKey();
CloudCmd.Edit.show(ConfigView);
});
};
this.hide = function() {
CloudCmd.Edit.hide();
};
function setListeners(editor) {
var element = CloudCmd.Edit.getElement();
DOM.Events.addOnce('contextmenu', element, setMenu);
editor.on('save', function(value) {
DOM.setCurrentSize(Format.size(value));
});
}
function authCheck(spawn) {
if (!config('auth'))
return;
spawn.emit('auth', config('username'), config('password'));
spawn.on('reject', function() {
Dialog.alert(TITLE, 'Wrong credentials!');
});
}
function setMenu(event) {
var position = {
x: event.clientX,
y: event.clientY
};
event.preventDefault();
!Menu && DOM.loadRemote('menu', function(error) {
var noFocus;
var options = {
beforeShow: function(params) {
params.x -= 18;
params.y -= 27;
},
afterClick: function() {
!noFocus && editor.focus();
}
};
var editor = CloudCmd.Edit.getEditor();
var menuData = {
'Save Ctrl+S' : function() {
editor.save();
},
'Go To Line Ctrl+G' : function() {
noFocus = true;
editor.goToLine();
},
'Cut Ctrl+X' : function() {
editor.cutToClipboard();
},
'Copy Ctrl+C' : function() {
editor.copyToClipboard();
},
'Paste Ctrl+V' : function() {
editor.pasteFromClipboard();
},
'Delete Del' : function() {
editor.remove('right');
},
'Select All Ctrl+A' : function() {
editor.selectAll();
},
'Beautify Ctrl+B' : function() {
editor.beautify();
},
'Minify Ctrl+M' : function() {
editor.minify();
},
'Close Esc' : function() {
EditFile.hide();
}
};
if (error)
return Dialog.alert(TITLE, error);
if (Menu || !MenuIO)
return;
var element = CloudCmd.Edit.getElement();
Menu = new MenuIO(element, options, menuData);
Menu.show(position.x, position.y);
});
}
function setMsgChanged(name) {
MSG_CHANGED = 'Do you want to save changes to ' + name + '?';
}
function isChanged() {
const editor = CloudCmd.Edit.getEditor();
const is = editor.isChanged();
if (!is)
return;
const cancel = false;
Dialog.confirm(TITLE, MSG_CHANGED, {cancel})
.then(() => {
editor.save();
});
}
init(callback);
};

View file

@ -1,219 +1,216 @@
'use strict';
/* global Promise */ /* global Promise */
/* global CloudCmd, Util, DOM, MenuIO */
var CloudCmd, Util, DOM, CloudFunc, MenuIO; CloudCmd.EditNames = function EditNamesProto(callback) {
var Info = DOM.CurrentInfo;
(function(CloudCmd, Util, DOM) { var Dialog = DOM.Dialog;
'use strict'; var exec = Util.exec;
var EditNames = this;
CloudCmd.EditNames = function EditNamesProto(callback) { var Menu;
var Info = DOM.CurrentInfo; var TITLE = 'Edit Names';
var Dialog = DOM.Dialog; var ConfigView = {
var exec = Util.exec; beforeClose: () => {
var EditNames = this; exec.ifExist(Menu, 'hide');
var Menu; isChanged();
var TITLE = 'Edit Names'; DOM.Events.remove('keydown', keyListener);
var ConfigView = {
beforeClose: function() {
exec.ifExist(Menu, 'hide');
isChanged();
DOM.Events.remove('keydown', keyListener);
}
};
function init(callback) {
var editor;
exec.series([
CloudCmd.Edit,
function(callback) {
editor = CloudCmd.Edit.getEditor();
callback();
},
function(callback) {
setListeners(editor);
callback();
},
function(callback) {
EditNames.show();
callback();
},
], callback);
} }
this.show = function() {
var names = getActiveNames().join('\n');
if (Info.name === '..' && names.length === 1)
return Dialog.alert.noFiles(TITLE);
CloudCmd.Edit
.getEditor()
.setValueFirst('edit-names', names)
.setOption('fontSize', 16)
.disableKey();
DOM.Events.addKey(keyListener);
CloudCmd.Edit.show(ConfigView);
};
function keyListener(event) {
var ctrl = event.ctrlKey;
var meta = event.metaKey;
var ctrlMeta = ctrl || meta;
var Key = CloudCmd.Key;
if (!ctrlMeta || event.keyCode !== Key.S)
return;
EditNames.hide();
}
function getActiveNames() {
return DOM.getFilenames(DOM.getActiveFiles());
}
this.hide = function() {
CloudCmd.Edit.hide();
};
function setListeners() {
var element = CloudCmd.Edit.getElement();
DOM.Events.addOnce('contextmenu', element, setMenu);
}
function applyNames() {
var dir = Info.dirPath;
var from = getActiveNames();
var nameIndex = from.indexOf(Info.name);
var editor = CloudCmd.Edit.getEditor();
var to = editor
.getValue()
.split('\n');
var reject = Promise.reject.bind(Promise);
var root = CloudCmd.config('root');
Promise.resolve(root)
.then(rename(dir, from, to))
.then(function(res) {
if (res.status === 404)
return res.text().then(reject);
CloudCmd.refresh(null, function() {
var name = to[nameIndex];
DOM.setCurrentByName(name);
});
}).catch(function(message) {
Dialog.alert(TITLE, message);
});
}
function getDir(root, dir) {
if (root === '/')
return dir;
return root + dir;
}
function rename(dir, from, to) {
return function(root) {
return fetch(CloudCmd.PREFIX + '/rename', {
method: 'put',
credentials: 'include',
body: JSON.stringify({
from: from,
to: to,
dir: getDir(root, dir)
})
});
};
}
function setMenu(event) {
var position = {
x: event.clientX,
y: event.clientY
};
event.preventDefault();
!Menu && DOM.loadRemote('menu', function(error) {
var noFocus;
var options = {
beforeShow: function(params) {
params.x -= 18;
params.y -= 27;
},
afterClick: function() {
!noFocus && editor.focus();
}
};
var editor = CloudCmd.Edit.getEditor();
var menuData = {
'Save Ctrl+S' : function() {
editor.save();
EditNames.hide();
},
'Go To Line Ctrl+G' : function() {
noFocus = true;
editor.goToLine();
},
'Cut Ctrl+X' : function() {
editor.cutToClipboard();
},
'Copy Ctrl+C' : function() {
editor.copyToClipboard();
},
'Paste Ctrl+V' : function() {
editor.pasteFromClipboard();
},
'Delete Del' : function() {
editor.remove('right');
},
'Select All Ctrl+A' : function() {
editor.selectAll();
},
'Close Esc' : function() {
EditNames.hide();
}
};
if (error)
return Dialog.alert(TITLE, error);
if (Menu || !MenuIO)
return;
var element = CloudCmd.Edit.getElement();
Menu = new MenuIO(element, options, menuData);
Menu.show(position.x, position.y);
});
}
function isChanged() {
var editor = CloudCmd.Edit.getEditor();
var msg = 'Apply new names?';
if (!editor.isChanged())
return;
Dialog.confirm(TITLE, msg)
.then(EditNames.hide)
.then(applyNames)
.catch(EditNames.hide);
}
init(callback);
}; };
})(CloudCmd, Util, DOM, CloudFunc); function init(callback) {
var editor;
exec.series([
CloudCmd.Edit,
function(callback) {
editor = CloudCmd.Edit.getEditor();
callback();
},
function(callback) {
setListeners(editor);
callback();
},
function(callback) {
EditNames.show();
callback();
},
], callback);
}
this.show = function() {
var names = getActiveNames().join('\n');
if (Info.name === '..' && names.length === 1)
return Dialog.alert.noFiles(TITLE);
CloudCmd.Edit
.getEditor()
.setValueFirst('edit-names', names)
.setOption('fontSize', 16)
.disableKey();
DOM.Events.addKey(keyListener);
CloudCmd.Edit.show(ConfigView);
};
function keyListener(event) {
var ctrl = event.ctrlKey;
var meta = event.metaKey;
var ctrlMeta = ctrl || meta;
var Key = CloudCmd.Key;
if (!ctrlMeta || event.keyCode !== Key.S)
return;
EditNames.hide();
}
function getActiveNames() {
return DOM.getFilenames(DOM.getActiveFiles());
}
this.hide = function() {
CloudCmd.Edit.hide();
};
function setListeners() {
var element = CloudCmd.Edit.getElement();
DOM.Events.addOnce('contextmenu', element, setMenu);
}
function applyNames() {
var dir = Info.dirPath;
var from = getActiveNames();
var nameIndex = from.indexOf(Info.name);
var editor = CloudCmd.Edit.getEditor();
var to = editor
.getValue()
.split('\n');
var reject = Promise.reject.bind(Promise);
var root = CloudCmd.config('root');
Promise.resolve(root)
.then(rename(dir, from, to))
.then(function(res) {
if (res.status === 404)
return res.text().then(reject);
CloudCmd.refresh(null, function() {
var name = to[nameIndex];
DOM.setCurrentByName(name);
});
}).catch(function(message) {
Dialog.alert(TITLE, message);
});
}
function getDir(root, dir) {
if (root === '/')
return dir;
return root + dir;
}
function rename(dir, from, to) {
return function(root) {
return fetch(CloudCmd.PREFIX + '/rename', {
method: 'put',
credentials: 'include',
body: JSON.stringify({
from: from,
to: to,
dir: getDir(root, dir)
})
});
};
}
function setMenu(event) {
var position = {
x: event.clientX,
y: event.clientY
};
event.preventDefault();
!Menu && DOM.loadRemote('menu', function(error) {
var noFocus;
var options = {
beforeShow: function(params) {
params.x -= 18;
params.y -= 27;
},
afterClick: function() {
!noFocus && editor.focus();
}
};
var editor = CloudCmd.Edit.getEditor();
var menuData = {
'Save Ctrl+S' : function() {
editor.save();
EditNames.hide();
},
'Go To Line Ctrl+G' : function() {
noFocus = true;
editor.goToLine();
},
'Cut Ctrl+X' : function() {
editor.cutToClipboard();
},
'Copy Ctrl+C' : function() {
editor.copyToClipboard();
},
'Paste Ctrl+V' : function() {
editor.pasteFromClipboard();
},
'Delete Del' : function() {
editor.remove('right');
},
'Select All Ctrl+A' : function() {
editor.selectAll();
},
'Close Esc' : function() {
EditNames.hide();
}
};
if (error)
return Dialog.alert(TITLE, error);
if (Menu || !MenuIO)
return;
var element = CloudCmd.Edit.getElement();
Menu = new MenuIO(element, options, menuData);
Menu.show(position.x, position.y);
});
}
function isChanged() {
var editor = CloudCmd.Edit.getEditor();
var msg = 'Apply new names?';
if (!editor.isChanged())
return;
Dialog.confirm(TITLE, msg)
.then(EditNames.hide)
.then(applyNames)
.catch(EditNames.hide);
}
init(callback);
};

View file

@ -1,136 +1,133 @@
/* global itype */ /* global CloudCmd, Util, DOM, CloudFunc */
var CloudCmd, Util, DOM, CloudFunc; 'use strict';
(function(CloudCmd, Util, DOM) { const itype = require('itype/legacy');
'use strict';
CloudCmd.Edit = EditProto;
function EditProto(callback) {
var Name = 'Edit';
var Loading = true;
var EditorName = CloudCmd.config('editor');
CloudCmd.Edit = EditProto; var exec = Util.exec;
var Element,
function EditProto(callback) { editor,
var Name = 'Edit';
var Loading = true;
var EditorName = CloudCmd.config('editor');
var exec = Util.exec; ConfigView = {
var Element, afterShow: function() {
editor, editor
.moveCursorTo(0, 0)
ConfigView = { .focus();
afterShow: function() {
editor
.moveCursorTo(0, 0)
.focus();
}
};
var Edit = function(fn) {
if (!itype.function(fn))
return;
fn();
};
function init(callback) {
var element = createElement();
exec.series([
CloudCmd.View,
function(callback) {
loadFiles(element, callback);
},
], callback);
}
function createElement() {
var element = DOM.load({
name: 'div',
style:
'width : 100%;' +
'height : 100%;' +
'font-family: "Droid Sans Mono";' +
'position : absolute;',
notAppend: true
});
Element = element;
return element;
}
function checkFn(name, fn) {
if (typeof fn !== 'function')
throw Error(name + ' should be a function!');
}
function initConfig(config, options) {
Util.copyObj(config, ConfigView);
if (!options)
return config;
if (options.afterShow) {
checkFn('options.afterShow', options.afterShow);
var afterShow = config.afterShow;
config.afterShow = function() {
afterShow();
options.afterShow();
};
} }
return config;
}
Edit.show = function(options) {
if (Loading)
return;
CloudCmd.View.show(Element, initConfig(options));
}; };
var Edit = function(fn) {
if (!itype.function(fn))
return;
Edit.getEditor = function() { fn();
return editor; };
};
function init(callback) {
var element = createElement();
Edit.getElement = function() { exec.series([
return Element; CloudCmd.View,
}; function(callback) {
loadFiles(element, callback);
Edit.hide = function() { },
CloudCmd.View.hide(); ], callback);
};
function loadFiles(element, callback) {
var prefix = CloudCmd.PREFIX;
var prefixName = prefix + '/' + EditorName;
var url = prefixName + '/' + EditorName + '.js';
Util.time(Name + ' load');
DOM.load.js(url, function() {
var word = window[EditorName];
var options = {
maxSize : CloudFunc.MAX_FILE_SIZE,
prefix : prefixName,
socketPath : prefix
};
word(element, options, function(ed) {
Util.timeEnd(Name + ' load');
editor = ed;
Loading = false;
exec(callback);
});
});
}
init(callback);
return Edit;
} }
})(CloudCmd, Util, DOM, CloudFunc); function createElement() {
var element = DOM.load({
name: 'div',
style:
'width : 100%;' +
'height : 100%;' +
'font-family: "Droid Sans Mono";' +
'position : absolute;',
notAppend: true
});
Element = element;
return element;
}
function checkFn(name, fn) {
if (typeof fn !== 'function')
throw Error(name + ' should be a function!');
}
function initConfig(config, options) {
Util.copyObj(config, ConfigView);
if (!options)
return config;
if (options.afterShow) {
checkFn('options.afterShow', options.afterShow);
var afterShow = config.afterShow;
config.afterShow = function() {
afterShow();
options.afterShow();
};
}
return config;
}
Edit.show = function(options) {
if (Loading)
return;
CloudCmd.View.show(Element, initConfig(options));
};
Edit.getEditor = function() {
return editor;
};
Edit.getElement = function() {
return Element;
};
Edit.hide = function() {
CloudCmd.View.hide();
};
function loadFiles(element, callback) {
var prefix = CloudCmd.PREFIX;
var prefixName = prefix + '/' + EditorName;
var url = prefixName + '/' + EditorName + '.js';
Util.time(Name + ' load');
DOM.load.js(url, function() {
var word = window[EditorName];
var options = {
maxSize : CloudFunc.MAX_FILE_SIZE,
prefix : prefixName,
socketPath : prefix
};
word(element, options, function(ed) {
Util.timeEnd(Name + ' load');
editor = ed;
Loading = false;
exec(callback);
});
});
}
init(callback);
return Edit;
}

View file

@ -1,337 +1,318 @@
var Util, DOM; 'use strict';
/* global itype */ const DOM = require('./dom');
const itype = require('itype/legacy');
(function(Util, DOM) { var DOMProto = Object.getPrototypeOf(DOM);
'use strict';
DOMProto.Events = new EventsProto();
function EventsProto() {
const Events = this;
var DOMProto = Object.getPrototypeOf(DOM); function parseArgs(eventName, element, listener, callback) {
var isFunc, isElement, error,
DOMProto.Events = new EventsProto(); EVENT_NAME = 0,
ELEMENT = 1,
function EventsProto() { type = itype(eventName);
var Events = this;
var Type = itype; switch(type) {
default:
isElement = type.match('element');
function parseArgs(eventName, element, listener, callback) { if (!isElement) {
var isFunc, isElement, error, error = new Error('unknown eventName: ' + type);
EVENT_NAME = 0, throw(error);
ELEMENT = 1, } else {
type = Type(eventName); eventName = arguments[ELEMENT];
element = arguments[EVENT_NAME];
switch(type) {
default:
isElement = type.match('element');
if (!isElement) { parseArgs(
error = new Error('unknown eventName: ' + type);
throw(error);
} else {
eventName = arguments[ELEMENT];
element = arguments[EVENT_NAME];
parseArgs(
eventName,
element,
listener,
callback
);
}
break;
case 'string':
isFunc = Type.function(element);
if (isFunc) {
listener = element;
element = null;
}
if (!element)
element = window;
callback(element, [
eventName, eventName,
element,
listener, listener,
false callback
]); );
break;
case 'array':
eventName.forEach(function(eventName) {
parseArgs(
eventName,
element,
listener,
callback
);
});
break;
case 'object':
Object.keys(eventName).forEach(function(name) {
var eventListener = eventName[name];
parseArgs(
name,
element,
eventListener,
callback
);
});
break;
} }
} break;
/** case 'string':
* safe add event listener isFunc = itype.function(element);
*
* @param type
* @param element {document by default}
* @param listener
*/
this.add = function(type, element, listener) {
checkType(type);
parseArgs(type, element, listener, function(element, args) { if (isFunc) {
element.addEventListener.apply(element, args); listener = element;
}); element = null;
return Events;
};
/**
* safe add event listener
*
* @param type
* @param listener
* @param element {document by default}
*/
this.addOnce = function(type, element, listener) {
var once = function (event) {
Events.remove(type, element, once);
listener(event);
};
if (!listener) {
listener = element;
element = null;
} }
this.add(type, element, once); if (!element)
element = window;
return Events; callback(element, [
}; eventName,
listener,
false
]);
break;
/** case 'array':
* safe remove event listener eventName.forEach(function(eventName) {
* parseArgs(
* @param type eventName,
* @param listener element,
* @param element {document by default} listener,
*/ callback
this.remove = function(type, element, listener) { );
checkType(type);
parseArgs(type, element, listener, function(element, args) {
element.removeEventListener.apply(element, args);
}); });
break;
return Events;
};
/** case 'object':
* safe add event keydown listener Object.keys(eventName).forEach(function(name) {
* var eventListener = eventName[name];
* @param listener
*/ parseArgs(
this.addKey = function() { name,
var name = 'keydown', element,
argsArr = [].slice.call(arguments), eventListener,
args = [name].concat(argsArr); callback
);
return this.add.apply(this, args); });
};
break;
/**
* safe remove event click listener
*
* @param listener
*/
this.rmKey = function() {
var name = 'keydown',
argsArr = [].slice.call(arguments),
args = [name].concat(argsArr);
return this.remove.apply(this, args);
};
/**
* safe add event click listener
*
* @param listener
*/
this.addClick = function() {
var name = 'click',
argsArr = [].slice.call(arguments),
args = [name].concat(argsArr);
return this.add.apply(this, args);
};
/**
* safe remove event click listener
*
* @param listener
*/
this.rmClick = function() {
var name = 'click',
argsArr = [].slice.call(arguments),
args = [name].concat(argsArr);
return this.remove.apply(this, args);
};
this.addContextMenu = function() {
var name = 'contextmenu',
argsArr = [].slice.call(arguments),
args = [name].concat(argsArr);
return this.add.apply(this, args);
};
/**
* safe add event click listener
*
* @param listener
*/
this.addError = function() {
var name = 'error',
argsArr = [].slice.call(arguments),
args = [name].concat(argsArr);
return this.add.apply(this, args);
};
/**
* safe add load click listener
*
* @param listener
*/
this.addLoad = function() {
var name = 'load',
argsArr = [].slice.call(arguments),
args = [name].concat(argsArr);
return this.add.apply(this, args);
};
/**
* crossbrowser create event
*
* @param eventName
* @param keyCode - not necessarily
*/
this.create = function(eventName, keyCode) {
var event = document.createEvent('Event');
event.initEvent(eventName, true, true);
if (keyCode)
event.keyCode = keyCode;
event.isDefaultPrevented = function() {
return this.defaultPrevented;
};
return event;
};
/**
* create keydown event
*
* @param keyCode
*/
this.createKey = function(keyCode) {
return this.create('keydown', keyCode);
};
/**
* create click event
*
* @param pKeyCode
*/
this.createClick = function() {
return this.create('click');
};
/**
* create click event
*
* @param pKeyCode
*/
this.createDblClick = function() {
return this.create('dblclick');
};
/**
* dispatch event
*
* @param event
*/
this.dispatch = function(event, element) {
var customEvent;
var isStr = Type.string(event);
if (isStr)
customEvent = Events.create(event);
else
customEvent = event;
return (element || window).dispatchEvent(customEvent);
};
/**
* dispatch keydown event
*
* @param pKeyCode
* @param element
*/
this.dispatchKey = function(keyCode, element) {
var event = this.createKey(keyCode),
ret = this.dispatch(event, element);
return ret;
};
/**
* dispatch click event
*
* @param element
*/
this.dispatchClick = function(element) {
var event = this.createClick(),
ret = this.dispatch(event, element);
return ret;
};
/**
* dispatch dblclick event
*
* @param element
*/
this.dispatchDblClick = function(element) {
var event = this.createDblClick(),
ret = this.dispatch(event, element);
return ret;
};
function checkType(type) {
if (!type)
throw Error('type could not be empty!');
} }
} }
})(Util, DOM);
/**
* safe add event listener
*
* @param type
* @param element {document by default}
* @param listener
*/
this.add = function(type, element, listener) {
checkType(type);
parseArgs(type, element, listener, function(element, args) {
element.addEventListener.apply(element, args);
});
return Events;
};
/**
* safe add event listener
*
* @param type
* @param listener
* @param element {document by default}
*/
this.addOnce = function(type, element, listener) {
var once = function (event) {
Events.remove(type, element, once);
listener(event);
};
if (!listener) {
listener = element;
element = null;
}
this.add(type, element, once);
return Events;
};
/**
* safe remove event listener
*
* @param type
* @param listener
* @param element {document by default}
*/
this.remove = function(type, element, listener) {
checkType(type);
parseArgs(type, element, listener, function(element, args) {
element.removeEventListener.apply(element, args);
});
return Events;
};
/**
* safe add event keydown listener
*
* @param listener
*/
this.addKey = function(...argsArr) {
const name = 'keydown';
const args = [name].concat(argsArr);
return this.add(...args);
};
/**
* safe remove event click listener
*
* @param listener
*/
this.rmKey = function(...argsArr) {
const name = 'keydown';
const args = [name].concat(argsArr);
return this.remove(...args);
};
/**
* safe add event click listener
*
* @param listener
*/
this.addClick = function(...argsArr) {
const name = 'click';
const args = [name].concat(argsArr);
return this.add(...args);
};
/**
* safe remove event click listener
*
* @param listener
*/
this.rmClick = function(...argsArr) {
const name = 'click';
const args = [name].concat(argsArr);
return this.remove(...args);
};
this.addContextMenu = function(...argsArr) {
const name = 'contextmenu';
const args = [name].concat(argsArr);
return this.add(...args);
};
/**
* safe add event click listener
*
* @param listener
*/
this.addError = function(...argsArr) {
const name = 'error';
const args = [name].concat(argsArr);
return this.add(...args);
};
/**
* safe add load click listener
*
* @param listener
*/
this.addLoad = function(...argsArr) {
const name = 'load';
const args = [name].concat(argsArr);
return this.add(...args);
};
/**
* crossbrowser create event
*
* @param eventName
* @param keyCode - not necessarily
*/
this.create = function(eventName, keyCode) {
var event = document.createEvent('Event');
event.initEvent(eventName, true, true);
if (keyCode)
event.keyCode = keyCode;
event.isDefaultPrevented = function() {
return this.defaultPrevented;
};
return event;
};
/**
* create keydown event
*
* @param keyCode
*/
this.createKey = function(keyCode) {
return this.create('keydown', keyCode);
};
/**
* create click event
*/
this.createClick = function() {
return this.create('click');
};
/**
* create click event
*/
this.createDblClick = function() {
return this.create('dblclick');
};
/**
* dispatch event
*
* @param event
*/
this.dispatch = function(event, element) {
var customEvent;
var isStr = itype.string(event);
if (isStr)
customEvent = Events.create(event);
else
customEvent = event;
return (element || window).dispatchEvent(customEvent);
};
/**
* dispatch keydown event
*
* @param keyCode
* @param element
*/
this.dispatchKey = function(keyCode, element) {
const event = this.createKey(keyCode);
return this.dispatch(event, element);
};
/**
* dispatch click event
*
* @param element
*/
this.dispatchClick = function(element) {
const event = this.createClick();
return this.dispatch(event, element);
};
/**
* dispatch dblclick event
*
* @param element
*/
this.dispatchDblClick = function(element) {
const event = this.createDblClick();
return this.dispatch(event, element);
};
function checkType(type) {
if (!type)
throw Error('type could not be empty!');
}
}

View file

@ -1,171 +1,171 @@
/* global Promise */ /* global Promise */
/* global itype */ /* global Util, CloudCmd */
/* global Util, DOM, CloudCmd */
(function(Util, DOM) { 'use strict';
'use strict';
const DOM = require('./dom');
var DOMProto = Object.getPrototypeOf(DOM);
DOMProto.Files = new FilesProto(Util, DOM);
const itype = require('itype/legacy');
function FilesProto(Util, DOM) {
var Promises = {},
Storage = DOM.Storage,
Files = this,
FILES_JSON = 'config|modules',
FILES_HTML = 'file|path|link|pathLink|media',
FILES_HTML_ROOT = 'view/media-tmpl|config-tmpl|upload',
funcs = [],
DIR_HTML = '/tmpl/',
DIR_HTML_FS = DIR_HTML + 'fs/',
DIR_JSON = '/json/',
timeout = getTimeoutOnce(2000);
var DOMProto = Object.getPrototypeOf(DOM); this.get = function(name, callback) {
var type = itype(name);
DOMProto.Files = new FilesProto(Util, DOM);
function FilesProto(Util, DOM) {
var Promises = {},
Storage = DOM.Storage,
Files = this,
FILES_JSON = 'config|modules',
FILES_HTML = 'file|path|link|pathLink|media',
FILES_HTML_ROOT = 'view/media-tmpl|config-tmpl|upload',
funcs = [],
DIR_HTML = '/tmpl/',
DIR_HTML_FS = DIR_HTML + 'fs/',
DIR_JSON = '/json/',
timeout = getTimeoutOnce(2000);
this.get = function(name, callback) { check(name, callback);
var type = itype(name);
check(name, callback);
switch(type) {
case 'string':
getModule(name, callback);
break;
case 'array':
funcs = name.map(function(name) {
return function(callback) {
Files.get(name, callback);
};
});
Util.exec.parallel(funcs, callback);
break;
}
return Files;
};
function check(name, callback) { switch(type) {
if (!name) case 'string':
throw Error('name could not be empty!'); getModule(name, callback);
break;
if (typeof callback !== 'function')
throw Error('callback should be a function');
}
function getModule(name, callback) { case 'array':
var path, funcs = name.map(function(name) {
return function(callback) {
regExpHTML = new RegExp(FILES_HTML + '|' + FILES_HTML_ROOT), Files.get(name, callback);
regExpJSON = new RegExp(FILES_JSON), };
isHTML = regExpHTML.test(name),
isJSON = regExpJSON.test(name);
if (!isHTML && !isJSON) {
showError(name);
} else if (name === 'config') {
getConfig(callback);
} else {
path = getPath(name, isHTML, isJSON);
getSystemFile(path, callback);
}
}
function getPath(name, isHTML, isJSON) {
var path,
regExp = new RegExp(FILES_HTML_ROOT),
isRoot = regExp.test(name);
if (isHTML) {
if (isRoot)
path = DIR_HTML + name.replace('-tmpl', '');
else
path = DIR_HTML_FS + name;
path += '.hbs';
} else if (isJSON) {
path = DIR_JSON + name + '.json';
}
return path;
}
function showError(name) {
var str = 'Wrong file name: ' + name,
error = new Error(str);
throw(error);
}
function getSystemFile(url, callback) {
var prefix = CloudCmd.PREFIX;
if (!Promises[url])
Promises[url] = new Promise(function(resolve, reject) {
DOM.load.ajax({
url : prefix + url,
success : resolve,
error : reject
});
});
Promises[url].then(function(data) {
callback(null, data);
}, function(error) {
Promises[url] = null;
callback(error);
}); });
Util.exec.parallel(funcs, callback);
break;
} }
function getConfig(callback) { return Files;
var is, };
RESTful = DOM.RESTful;
function check(name, callback) {
if (!name)
throw Error('name could not be empty!');
if (typeof callback !== 'function')
throw Error('callback should be a function');
}
function getModule(name, callback) {
var path,
if (!Promises.config) regExpHTML = new RegExp(FILES_HTML + '|' + FILES_HTML_ROOT),
Promises.config = new Promise(function(resolve, reject) { regExpJSON = new RegExp(FILES_JSON),
is = true;
RESTful.Config.read(function(error, data) {
if (error)
reject(error);
else
resolve(data);
});
});
Promises.config.then(function(data) { isHTML = regExpHTML.test(name),
is = false; isJSON = regExpJSON.test(name);
Storage.setAllowed(data.localStorage);
if (!isHTML && !isJSON) {
callback(null, data); showError(name);
} else if (name === 'config') {
timeout(function() { getConfig(callback);
if (!is) } else {
Promises.config = null; path = getPath(name, isHTML, isJSON);
getSystemFile(path, callback);
}
}
function getPath(name, isHTML, isJSON) {
var path,
regExp = new RegExp(FILES_HTML_ROOT),
isRoot = regExp.test(name);
if (isHTML) {
if (isRoot)
path = DIR_HTML + name.replace('-tmpl', '');
else
path = DIR_HTML_FS + name;
path += '.hbs';
} else if (isJSON) {
path = DIR_JSON + name + '.json';
}
return path;
}
function showError(name) {
var str = 'Wrong file name: ' + name,
error = new Error(str);
throw(error);
}
function getSystemFile(url, callback) {
var prefix = CloudCmd.PREFIX;
if (!Promises[url])
Promises[url] = new Promise(function(resolve, reject) {
DOM.load.ajax({
url : prefix + url,
success : resolve,
error : reject
}); });
}, function() { });
Promises[url].then(function(data) {
callback(null, data);
}, function(error) {
Promises[url] = null;
callback(error);
});
}
function getConfig(callback) {
var is,
RESTful = DOM.RESTful;
if (!Promises.config)
Promises.config = new Promise(function(resolve, reject) {
is = true;
RESTful.Config.read(function(error, data) {
if (error)
reject(error);
else
resolve(data);
});
});
Promises.config.then(function(data) {
is = false;
Storage.setAllowed(data.localStorage);
callback(null, data);
timeout(function() {
if (!is) if (!is)
Promises.config = null; Promises.config = null;
}); });
} }, function() {
if (!is)
function getTimeoutOnce(time) { Promises.config = null;
var is, });
fn = function(callback) {
if (!is) {
is = true;
setTimeout(function() {
is = false;
callback();
}, time);
}
};
return fn;
}
} }
})(Util, DOM);
function getTimeoutOnce(time) {
var is,
fn = function(callback) {
if (!is) {
is = true;
setTimeout(function() {
is = false;
callback();
}, time);
}
};
return fn;
}
}

View file

@ -1,33 +1,31 @@
var CloudCmd, Util, DOM; 'use strict';
(function(CloudCmd, Util, DOM) { /* global DOM, CloudCmd */
'use strict';
window.CloudCmd.Help = HelpProto;
function HelpProto() {
const Images = DOM.Images;
const Help = this;
CloudCmd.Help = HelpProto; function init() {
Images.show.load('top');
function HelpProto() { Help.show();
var Images = DOM.Images,
Help = this;
function init() {
Images.show.load('top');
Help.show();
}
this.show = function() {
CloudCmd
.Markdown
.show('/HELP.md', {
positionLoad : 'top',
relative : true
});
};
this.hide = function() {
CloudCmd.View.hide();
};
init();
} }
})(CloudCmd, Util, DOM); this.show = () => {
CloudCmd
.Markdown
.show('/HELP.md', {
positionLoad : 'top',
relative : true
});
};
this.hide = () => {
CloudCmd.View.hide();
};
init();
}

View file

@ -1,125 +1,120 @@
(function(global) { 'use strict';
'use strict';
module.exports = InputProto();
function InputProto() {
if (!(this instanceof InputProto))
return new InputProto();
if (typeof module !== 'undefined' && module.exports) this.setValue = setValue;
module.exports = InputProto(); this.getValue = getValue;
else this.convert = convert;
global.input = InputProto(); this.getName = getName;
this.getElementByName = getElementByName;
function getElementByName(selector, element) {
var el = element.querySelector('[data-name="js-' + selector + '"]');
function InputProto() { return el;
if (!(this instanceof InputProto)) }
return new InputProto();
this.setValue = setValue; function getName(element) {
this.getValue = getValue; var name = element
this.convert = convert; .getAttribute('data-name')
this.getName = getName; .replace(/^js-/, '');
this.getElementByName = getElementByName;
function getElementByName(selector, element) { return name;
var el = element.querySelector('[data-name="js-' + selector + '"]');
return el;
}
function getName(element) {
var name = element
.getAttribute('data-name')
.replace(/^js-/, '');
return name;
}
function convert(config) {
var result = clone(config),
array = Object.keys(result),
isBool = partial(isType, result, 'boolean');
array
.filter(isBool)
.forEach(function(name) {
var item = result[name];
result[name] = setState(item);
});
return result;
}
function clone(object) {
var result = {};
Object.keys(object).forEach(function(name) {
result[name] = object[name];
});
return result;
}
function partial(fn) {
var i,
bind = Function.prototype.bind,
n = arguments.length,
args = Array(n - 1);
args[0] = null;
for (i = 1; i < n; i++)
args[i] = arguments[i];
return bind.apply(fn, args);
}
function isType(object, type, name) {
var current = typeof object[name],
is = current === type;
return is;
}
function setState(state) {
var ret = '';
if (state)
ret = ' checked';
return ret;
}
function getValue(name, element) {
var data,
el = getElementByName(name, element),
type = el.type;
switch(type) {
case 'checkbox':
data = el.checked;
break;
case 'number':
data = Number(el.value);
break;
default:
data = el.value;
break;
}
return data;
}
function setValue(name, value, element) {
var el = getElementByName(name, element),
type = el.type;
switch(type) {
case 'checkbox':
el.checked = value;
break;
default:
el.value = value;
break;
}
}
} }
})(window); function convert(config) {
var result = clone(config),
array = Object.keys(result),
isBool = partial(isType, result, 'boolean');
array
.filter(isBool)
.forEach(function(name) {
var item = result[name];
result[name] = setState(item);
});
return result;
}
function clone(object) {
var result = {};
Object.keys(object).forEach(function(name) {
result[name] = object[name];
});
return result;
}
function partial(fn) {
var i,
bind = Function.prototype.bind,
n = arguments.length,
args = Array(n - 1);
args[0] = null;
for (i = 1; i < n; i++)
args[i] = arguments[i];
return bind.apply(fn, args);
}
function isType(object, type, name) {
var current = typeof object[name],
is = current === type;
return is;
}
function setState(state) {
var ret = '';
if (state)
ret = ' checked';
return ret;
}
function getValue(name, element) {
var data,
el = getElementByName(name, element),
type = el.type;
switch(type) {
case 'checkbox':
data = el.checked;
break;
case 'number':
data = Number(el.value);
break;
default:
data = el.value;
break;
}
return data;
}
function setValue(name, value, element) {
var el = getElementByName(name, element),
type = el.type;
switch(type) {
case 'checkbox':
el.checked = value;
break;
default:
el.value = value;
break;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,497 +1,495 @@
var Util, DOM, CloudFunc, CloudCmd; /* global Util, DOM, CloudFunc, CloudCmd */
(function (Util, DOM, CloudFunc, CloudCmd) { 'use strict';
'use strict';
CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd);
function ListenersProto(Util, DOM, CloudFunc, CloudCmd) {
var Info = DOM.CurrentInfo,
Storage = DOM.Storage,
Events = DOM.Events,
EventsFiles = {
'mousedown' : Util.exec.with(execIfNotUL, setCurrentFileByEvent),
'click' : onClick,
'dragstart' : Util.exec.with(execIfNotUL, onDragStart),
'dblclick' : Util.exec.with(execIfNotUL, onDblClick),
'touchstart': Util.exec.with(execIfNotUL, onTouch)
};
CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd); var EXT;
function ListenersProto(Util, DOM, CloudFunc, CloudCmd) { this.init = function () {
var Info = DOM.CurrentInfo, contextMenu();
Storage = DOM.Storage, dragndrop();
Events = DOM.Events, unload();
EventsFiles = { pop();
'mousedown' : Util.exec.with(execIfNotUL, setCurrentFileByEvent), resize();
'click' : onClick, config();
'dragstart' : Util.exec.with(execIfNotUL, onDragStart), header();
'dblclick' : Util.exec.with(execIfNotUL, onDblClick), };
'touchstart': Util.exec.with(execIfNotUL, onTouch)
}; function header() {
var fm = DOM.getFM();
var EXT; var isDataset = function(el) {
return el.dataset;
this.init = function () {
contextMenu();
dragndrop();
unload();
pop();
resize();
config();
header();
}; };
function header() { var isPanel = function(el) {
var fm = DOM.getFM(); return /^js-(left|right)$/.test(el.dataset.name);
};
var isDataset = function(el) {
return el.dataset;
};
var isPanel = function(el) {
return /^js-(left|right)$/.test(el.dataset.name);
};
Events.addClick(fm, function(event) {
var el = event.target;
var parent = el.parentElement;
if (parent.dataset.name !== 'js-fm-header')
return;
var name = (el.dataset.name || '')
.replace('js-', '');
if (!/^(name|size|date)$/.test(name))
return;
var panel = getPath(el)
.filter(isDataset)
.filter(isPanel)
.pop();
CloudCmd.sortPanel(name, panel);
});
}
function getPath(el, path) { Events.addClick(fm, function(event) {
path = path || []; var el = event.target;
if (!el)
return path;
var parent = el.parentElement; var parent = el.parentElement;
return getPath(parent, path.concat(el)); if (parent.dataset.name !== 'js-fm-header')
}
function config() {
DOM.Files.get('config', function(e, config) {
var type = config && config.packer;
EXT = DOM.getPackerExt(type);
});
}
this.initKeysPanel = function() {
var keysElement = DOM.getById('js-keyspanel');
if (!keysElement)
return; return;
Events.addClick(keysElement, function(event) { var name = (el.dataset.name || '')
var element = event.target; .replace('js-', '');
var id = element.id;
var operation = function(name) {
var Operation = CloudCmd.Operation;
var fn = Operation.show.bind(null, name);
return fn;
};
var clickFuncs = {
'f1' : CloudCmd.Help.show,
'f2' : DOM.renameCurrent,
'f3' : CloudCmd.View.show,
'f4' : CloudCmd.EditFile.show,
'f5' : operation('copy'),
'f6' : operation('move'),
'f7' : DOM.promptNewDir,
'f8' : operation('delete'),
'f9' : CloudCmd.Menu.show,
'f10' : CloudCmd.Config.show,
'~' : CloudCmd.Konsole.show,
'contact' : CloudCmd.Contact.show,
};
var func = clickFuncs[id];
if (func)
func();
});
};
this.setOnPanel = function(side) {
var panel,
filesElement,
pathElement;
if (typeof side === 'string') if (!/^(name|size|date)$/.test(name))
panel = DOM.getByDataName('js-' + side); return;
else
panel = side;
filesElement = DOM.getByDataName('js-files', panel); var panel = getPath(el)
pathElement = DOM.getByDataName('js-path', panel); .filter(isDataset)
.filter(isPanel)
.pop();
/* ставим загрузку гифа на клик*/ CloudCmd.sortPanel(name, panel);
Events.addClick(pathElement, getPathListener(panel)); });
Events.add(filesElement, EventsFiles);
};
function getPathListener(panel) {
var fn = onPathElementClick.bind(null, panel);
return fn;
}
function isNoCurrent(panel) {
var noCurrent,
infoPanel = Info.panel,
namePanel = panel.getAttribute('data-name'),
nameInfoPanel = infoPanel.getAttribute('data-name');
if (namePanel !== nameInfoPanel)
noCurrent = true;
return noCurrent;
}
function onPathElementClick(panel, event) {
var link, href, url,
noCurrent,
fs = CloudFunc.FS,
prefix = CloudCmd.PREFIX,
element = event.target,
attr = element.getAttribute('data-name');
switch (attr) {
case 'js-clear-storage':
Storage.clear();
break;
case 'js-refresh':
noCurrent = isNoCurrent(panel);
CloudCmd.refresh(panel, {
noCurrent: noCurrent
});
event.preventDefault();
break;
case 'js-path-link':
url = CloudCmd.HOST;
href = element.href;
link = href.replace(url, '');
/**
* browser doesn't replace % -> %25%
* do it for him
*/
link = link.replace('%%', '%25%');
link = decodeURI(link);
link = link.replace(RegExp('^' + prefix + fs), '') || '/';
noCurrent = isNoCurrent(panel);
CloudCmd.loadDir({
path : link,
isRefresh : false,
panel : noCurrent ? panel : Info.panel
});
event.preventDefault();
}
}
function execIfNotUL(callback, event) {
var element = event.target,
tag = element.tagName;
if (tag !== 'UL')
callback(event);
}
function onClick(event) {
var ctrl = event.ctrlKey;
if (!ctrl)
event.preventDefault();
changePanel(event.target);
}
function toggleSelect(key, files) {
var isMac = /Mac/.test(window.navigator.platform);
if (!key)
throw Error('key should not be undefined!');
if (isMac && key.meta || key.ctrl)
DOM.toggleSelectedFile(files[0]);
else if (key.shift)
files.forEach(function(current) {
if (!DOM.isSelected(current))
DOM.toggleSelectedFile(current);
});
else
DOM.unselectFiles();
}
function changePanel(element) {
var panel = Info.panel,
files = DOM.getByDataName('js-files', panel),
ul = getULElement(element);
if (ul !== files)
DOM.changePanel();
}
function onDblClick(event) {
var current = getLIElement(event.target),
isDir = DOM.isCurrentIsDir(current),
path = DOM.getCurrentPath(current);
if (isDir) {
CloudCmd.loadDir({
path: path === '/' ? '/' : path + '/'
});
event.preventDefault();
}
}
function onTouch(event) {
var isCurrent,
current = getLIElement(event.target),
isDir = DOM.isCurrentIsDir(current);
if (isDir) {
isCurrent = DOM.isCurrentFile(current);
if (isCurrent) {
CloudCmd.loadDir({
path: DOM.getCurrentPath(current)
});
event.preventDefault();
}
}
}
/*
* download file from browser to desktop
* in Chrome (HTML5)
*/
function onDragStart(event) {
var apiURL = CloudFunc.apiURL,
element = getLIElement(event.target),
isDir = Info.isDir,
link = DOM.getCurrentLink(element),
name = DOM.getCurrentName(element);
/* if it's directory - adding json extension */
if (isDir) {
name += EXT;
link = document.createElement('a');
link.textContent = name;
link.href = apiURL + '/pack' + Info.path + EXT;
}
event.dataTransfer.setData('DownloadURL',
'application/octet-stream' + ':' +
name + ':' +
link);
}
function getLIElement(element) {
if (!element)
return element;
while (element.tagName !== 'LI')
element = element.parentElement;
return element;
}
function getULElement(element) {
while (element.tagName !== 'UL')
element = element.parentElement;
return element;
}
function setCurrentFileByEvent(event) {
var fromName,
toName,
BUTTON_LEFT = 0,
files = [],
key = {
ctrl: event.ctrlKey,
meta: event.metaKey,
shift: event.shiftKey
},
element = getLIElement(event.target);
fromName = Info.name;
DOM.setCurrentFile(element);
toName = Info.name;
if (key.shift)
files = getFilesRange(fromName, toName);
else
files.push(Info.element);
if (event.button === BUTTON_LEFT)
toggleSelect(key, files);
}
function getFilesRange(from, to) {
var i = 0,
delta = 0,
result = [],
files = DOM.getFiles(),
names = DOM.getFilenames(files),
indexFrom,
indexTo;
if (names[0] === '..') {
names.shift();
delta = 1;
}
indexFrom = names.indexOf(from);
indexTo = names.indexOf(to);
if (indexFrom < indexTo)
for (i = indexFrom; i <= indexTo; i++)
result.push(files[i + delta]);
else if (indexFrom > indexTo)
for (i = indexFrom; i >= indexTo; i--)
result.push(files[i + delta]);
else
result.push(to);
return result;
}
function contextMenu() {
var fm = DOM.getFM();
Events.addOnce('contextmenu', fm, function(event) {
CloudCmd.Menu.show({
x: event.clientX,
y: event.clientY
});
});
Events.addContextMenu(fm, function(event) {
CloudCmd.Menu.ENABLED || event.preventDefault();
});
}
function dragndrop() {
var panels = DOM.getByClassAll('panel'),
forEach = Array.prototype.forEach,
select = function() {
forEach.call(panels, function(panel) {
panel.classList.add('selected-panel');
});
},
unselect = function() {
forEach.call(panels, function(panel) {
panel.classList.remove('selected-panel');
});
},
onDrop = function(event) {
var files = event.dataTransfer.files,
items = event.dataTransfer.items;
event.preventDefault();
if (items && items.length && items[0].webkitGetAsEntry) {
files = [].filter.call(items, function(item) {
return item.kind === 'file';
});
DOM.uploadDirectory(files);
} else {
DOM.uploadFiles(files);
}
},
/**
* In Mac OS Chrome dropEffect = 'none'
* so drop do not firing up when try
* to upload file from download bar
*/
onDragOver = function(event) {
var dataTransfer = event.dataTransfer,
effectAllowed = dataTransfer.effectAllowed;
if (/move|linkMove/.test(effectAllowed))
dataTransfer.dropEffect = 'move';
else
dataTransfer.dropEffect = 'copy';
event.preventDefault();
};
Events.add('dragenter', select);
Events.add(['dragleave', 'drop'], unselect);
forEach.call(panels, function(panel) {
Events.add('dragover', panel, onDragOver)
.add('drop', panel, onDrop);
});
}
function unload() {
DOM.Events.add(['unload', 'beforeunload'], function (event) {
var ret,
Key = CloudCmd.Key,
isBind = Key && Key.isBind();
if (!isBind) {
event.preventDefault();
ret = 'Please make sure that you saved all work.';
}
return ret;
});
}
function pop() {
Events.add('popstate', function(event) {
var path = event.state || '';
path = path.replace(CloudFunc.FS, '');
if (!path)
CloudCmd.route(location.hash);
else
CloudCmd.loadDir({
path : path,
history : false
});
});
}
function resize() {
Events.add('resize', function() {
var name, isLeft,
is = window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH,
panel = Info.panel;
if (panel) {
name = panel.getAttribute('data-name'),
isLeft = name === 'js-left';
}
if (is && !isLeft)
DOM.changePanel();
});
}
} }
})(Util, DOM, CloudFunc, CloudCmd); function getPath(el, path) {
path = path || [];
if (!el)
return path;
var parent = el.parentElement;
return getPath(parent, path.concat(el));
}
function config() {
DOM.Files.get('config', function(e, config) {
var type = config && config.packer;
EXT = DOM.getPackerExt(type);
});
}
this.initKeysPanel = function() {
var keysElement = DOM.getById('js-keyspanel');
if (!keysElement)
return;
Events.addClick(keysElement, function(event) {
var element = event.target;
var id = element.id;
var operation = function(name) {
var Operation = CloudCmd.Operation;
var fn = Operation.show.bind(null, name);
return fn;
};
var clickFuncs = {
'f1' : CloudCmd.Help.show,
'f2' : DOM.renameCurrent,
'f3' : CloudCmd.View.show,
'f4' : CloudCmd.EditFile.show,
'f5' : operation('copy'),
'f6' : operation('move'),
'f7' : DOM.promptNewDir,
'f8' : operation('delete'),
'f9' : CloudCmd.Menu.show,
'f10' : CloudCmd.Config.show,
'~' : CloudCmd.Konsole.show,
'contact' : CloudCmd.Contact.show,
};
var func = clickFuncs[id];
if (func)
func();
});
};
this.setOnPanel = function(side) {
var panel,
filesElement,
pathElement;
if (typeof side === 'string')
panel = DOM.getByDataName('js-' + side);
else
panel = side;
filesElement = DOM.getByDataName('js-files', panel);
pathElement = DOM.getByDataName('js-path', panel);
/* ставим загрузку гифа на клик*/
Events.addClick(pathElement, getPathListener(panel));
Events.add(filesElement, EventsFiles);
};
function getPathListener(panel) {
var fn = onPathElementClick.bind(null, panel);
return fn;
}
function isNoCurrent(panel) {
var noCurrent,
infoPanel = Info.panel,
namePanel = panel.getAttribute('data-name'),
nameInfoPanel = infoPanel.getAttribute('data-name');
if (namePanel !== nameInfoPanel)
noCurrent = true;
return noCurrent;
}
function onPathElementClick(panel, event) {
var link, href, url,
noCurrent,
fs = CloudFunc.FS,
prefix = CloudCmd.PREFIX,
element = event.target,
attr = element.getAttribute('data-name');
switch (attr) {
case 'js-clear-storage':
Storage.clear();
break;
case 'js-refresh':
noCurrent = isNoCurrent(panel);
CloudCmd.refresh(panel, {
noCurrent: noCurrent
});
event.preventDefault();
break;
case 'js-path-link':
url = CloudCmd.HOST;
href = element.href;
link = href.replace(url, '');
/**
* browser doesn't replace % -> %25%
* do it for him
*/
link = link.replace('%%', '%25%');
link = decodeURI(link);
link = link.replace(RegExp('^' + prefix + fs), '') || '/';
noCurrent = isNoCurrent(panel);
CloudCmd.loadDir({
path : link,
isRefresh : false,
panel : noCurrent ? panel : Info.panel
});
event.preventDefault();
}
}
function execIfNotUL(callback, event) {
var element = event.target,
tag = element.tagName;
if (tag !== 'UL')
callback(event);
}
function onClick(event) {
var ctrl = event.ctrlKey;
if (!ctrl)
event.preventDefault();
changePanel(event.target);
}
function toggleSelect(key, files) {
var isMac = /Mac/.test(window.navigator.platform);
if (!key)
throw Error('key should not be undefined!');
if (isMac && key.meta || key.ctrl)
DOM.toggleSelectedFile(files[0]);
else if (key.shift)
files.forEach(function(current) {
if (!DOM.isSelected(current))
DOM.toggleSelectedFile(current);
});
else
DOM.unselectFiles();
}
function changePanel(element) {
var panel = Info.panel,
files = DOM.getByDataName('js-files', panel),
ul = getULElement(element);
if (ul !== files)
DOM.changePanel();
}
function onDblClick(event) {
var current = getLIElement(event.target),
isDir = DOM.isCurrentIsDir(current),
path = DOM.getCurrentPath(current);
if (isDir) {
CloudCmd.loadDir({
path: path === '/' ? '/' : path + '/'
});
event.preventDefault();
}
}
function onTouch(event) {
var isCurrent,
current = getLIElement(event.target),
isDir = DOM.isCurrentIsDir(current);
if (isDir) {
isCurrent = DOM.isCurrentFile(current);
if (isCurrent) {
CloudCmd.loadDir({
path: DOM.getCurrentPath(current)
});
event.preventDefault();
}
}
}
/*
* download file from browser to desktop
* in Chrome (HTML5)
*/
function onDragStart(event) {
var apiURL = CloudFunc.apiURL,
element = getLIElement(event.target),
isDir = Info.isDir,
link = DOM.getCurrentLink(element),
name = DOM.getCurrentName(element);
/* if it's directory - adding json extension */
if (isDir) {
name += EXT;
link = document.createElement('a');
link.textContent = name;
link.href = apiURL + '/pack' + Info.path + EXT;
}
event.dataTransfer.setData('DownloadURL',
'application/octet-stream' + ':' +
name + ':' +
link);
}
function getLIElement(element) {
if (!element)
return element;
while (element.tagName !== 'LI')
element = element.parentElement;
return element;
}
function getULElement(element) {
while (element.tagName !== 'UL')
element = element.parentElement;
return element;
}
function setCurrentFileByEvent(event) {
var fromName,
toName,
BUTTON_LEFT = 0,
files = [],
key = {
ctrl: event.ctrlKey,
meta: event.metaKey,
shift: event.shiftKey
},
element = getLIElement(event.target);
fromName = Info.name;
DOM.setCurrentFile(element);
toName = Info.name;
if (key.shift)
files = getFilesRange(fromName, toName);
else
files.push(Info.element);
if (event.button === BUTTON_LEFT)
toggleSelect(key, files);
}
function getFilesRange(from, to) {
var i = 0,
delta = 0,
result = [],
files = DOM.getFiles(),
names = DOM.getFilenames(files),
indexFrom,
indexTo;
if (names[0] === '..') {
names.shift();
delta = 1;
}
indexFrom = names.indexOf(from);
indexTo = names.indexOf(to);
if (indexFrom < indexTo)
for (i = indexFrom; i <= indexTo; i++)
result.push(files[i + delta]);
else if (indexFrom > indexTo)
for (i = indexFrom; i >= indexTo; i--)
result.push(files[i + delta]);
else
result.push(to);
return result;
}
function contextMenu() {
var fm = DOM.getFM();
Events.addOnce('contextmenu', fm, function(event) {
CloudCmd.Menu.show({
x: event.clientX,
y: event.clientY
});
});
Events.addContextMenu(fm, function(event) {
CloudCmd.Menu.ENABLED || event.preventDefault();
});
}
function dragndrop() {
var panels = DOM.getByClassAll('panel'),
forEach = Array.prototype.forEach,
select = function() {
forEach.call(panels, function(panel) {
panel.classList.add('selected-panel');
});
},
unselect = function() {
forEach.call(panels, function(panel) {
panel.classList.remove('selected-panel');
});
},
onDrop = function(event) {
var files = event.dataTransfer.files,
items = event.dataTransfer.items;
event.preventDefault();
if (items && items.length && items[0].webkitGetAsEntry) {
files = [].filter.call(items, function(item) {
return item.kind === 'file';
});
DOM.uploadDirectory(files);
} else {
DOM.uploadFiles(files);
}
},
/**
* In Mac OS Chrome dropEffect = 'none'
* so drop do not firing up when try
* to upload file from download bar
*/
onDragOver = function(event) {
var dataTransfer = event.dataTransfer,
effectAllowed = dataTransfer.effectAllowed;
if (/move|linkMove/.test(effectAllowed))
dataTransfer.dropEffect = 'move';
else
dataTransfer.dropEffect = 'copy';
event.preventDefault();
};
Events.add('dragenter', select);
Events.add(['dragleave', 'drop'], unselect);
forEach.call(panels, function(panel) {
Events.add('dragover', panel, onDragOver)
.add('drop', panel, onDrop);
});
}
function unload() {
DOM.Events.add(['unload', 'beforeunload'], function (event) {
var ret,
Key = CloudCmd.Key,
isBind = Key && Key.isBind();
if (!isBind) {
event.preventDefault();
ret = 'Please make sure that you saved all work.';
}
return ret;
});
}
function pop() {
Events.add('popstate', function(event) {
var path = event.state || '';
path = path.replace(CloudFunc.FS, '');
if (!path)
CloudCmd.route(location.hash);
else
CloudCmd.loadDir({
path : path,
history : false
});
});
}
function resize() {
Events.add('resize', function() {
var name, isLeft,
is = window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH,
panel = Info.panel;
if (panel) {
name = panel.getAttribute('data-name'),
isLeft = name === 'js-left';
}
if (is && !isLeft)
DOM.changePanel();
});
}
}

View file

@ -1,371 +1,381 @@
'use strict';
/* global Util */ /* global Util */
/* global DOM */ /* global DOM */
/* global Emitify */
/* global itype */
(function (Util, DOM) { const DOMProto = Object.getPrototypeOf(DOM);
'use strict'; const rendy = require('rendy');
const itype = require('itype/legacy');
/* global rendy */ const Emitify = require('emitify');
var DOMProto = Object.getPrototypeOf(DOM); DOMProto.load = new LoaderProto(Util, DOM.Images, DOM.Events);
DOMProto.load = new LoaderProto(Util, DOM.Images, DOM.Events); function LoaderProto(Util, Images, Events) {
/**
function LoaderProto(Util, Images, Events) { * Функция создаёт элемент и загружает файл с src.
/** *
* Функция создаёт элемент и загружает файл с src. * @param pParams_o = {
* * name, - название тэга
* @param pParams_o = { * src', - путь к файлу
* name, - название тэга * func, - обьект, содержаий одну из функций
* src', - путь к файлу * или сразу две onload и onerror
* func, - обьект, содержаий одну из функций * {onload: function() {}, onerror: function();}
* или сразу две onload и onerror * style,
* {onload: function() {}, onerror: function();} * id,
* style, * element,
* id, * async, - true by default
* element, * inner: 'id{color:red, },
* async, - true by default * class,
* inner: 'id{color:red, }, * notAppend - false by default
* class, *
* notAppend - false by default */
* function load(params) {
*/ var element, type,
function load(params) { p = params,
var element, type, func = p.func,
p = params, name = p.name,
func = p.func, parent = p.parent || document.body,
name = p.name,
parent = p.parent || document.body,
/*
* if passed arguments function
* then it's onload by default
*
* if object - then onload and onerror
*/
funcLoad = function() {
var callback = func && func.onload || func;
Events.remove('error', element, funcError);
Util.exec(callback);
},
funcError = function() {
var callback,
template = 'file {{ src }} could not be loaded',
msg = rendy(template, {
src: p.src
}),
error = new Error(msg);
if (func)
callback = func.onerror || func.onload || func;
parent.removeChild(element);
Images.show.error(msg);
Util.exec(callback, error);
};
/* убираем путь к файлу, оставляя только название файла */ /*
if (!p.id && p.src) * if passed arguments function
p.id = load.getIdBySrc(p.src); * then it's onload by default
*
element = document.getElementById(p.id); * if object - then onload and onerror
*/
funcLoad = function() {
var callback = func && func.onload || func;
Events.remove('error', element, funcError);
Util.exec(callback);
},
if (element) { funcError = function() {
Util.exec(func); var callback,
} else { template = 'file {{ src }} could not be loaded',
element = document.createElement(name); msg = rendy(template, {
src: p.src
if (name === 'script' || name === 'link') }),
Events.addOnce('load', element, funcLoad)
.addError(element, funcError);
if (p.id)
element.id = p.id;
if (p.className)
element.className = p.className;
if (p.src) {
/* if work with css use href */
if (name === 'link') {
element.href = p.src;
element.rel = 'stylesheet';
} else
element.src = p.src;
}
if (p.attribute) {
type = itype(p.attribute);
switch(type) { error = new Error(msg);
case 'string':
element.setAttribute(p.attribute, '');
break;
case 'object':
Object.keys(p.attribute).forEach(function(name) {
element.setAttribute(name, p.attribute[name]);
});
break;
}
}
if (p.style) if (func)
element.style.cssText = p.style; callback = func.onerror || func.onload || func;
if (p.async && name === 'script' || p.async === undefined) parent.removeChild(element);
element.async = true;
if (!p.notAppend) Images.show.error(msg);
parent.appendChild(element);
if (p.inner) Util.exec(callback, error);
element.innerHTML = p.inner; };
/* убираем путь к файлу, оставляя только название файла */
if (!p.id && p.src)
p.id = load.getIdBySrc(p.src);
element = document.getElementById(p.id);
if (element) {
Util.exec(func);
} else {
element = document.createElement(name);
if (name === 'script' || name === 'link')
Events.addOnce('load', element, funcLoad)
.addError(element, funcError);
if (p.id)
element.id = p.id;
if (p.className)
element.className = p.className;
if (p.src) {
/* if work with css use href */
if (name === 'link') {
element.href = p.src;
element.rel = 'stylesheet';
} else
element.src = p.src;
} }
return element; if (p.attribute) {
type = itype(p.attribute);
switch(type) {
case 'string':
element.setAttribute(p.attribute, '');
break;
case 'object':
Object.keys(p.attribute).forEach(function(name) {
element.setAttribute(name, p.attribute[name]);
});
break;
}
}
if (p.style)
element.style.cssText = p.style;
if (p.async && name === 'script' || p.async === undefined)
element.async = true;
if (!p.notAppend)
parent.appendChild(element);
if (p.inner)
element.innerHTML = p.inner;
} }
/** return element;
* Function gets id by src }
* @param pSrc
* /**
* Example: http://domain.com/1.js -> 1_js * Function gets id by src
*/ * @param pSrc
load.getIdBySrc = function(src) { *
var num, sub, id, * Example: http://domain.com/1.js -> 1_js
isStr = itype.string(src); */
load.getIdBySrc = function(src) {
if (isStr) { var num, sub, id,
if (~src.indexOf(':')) isStr = itype.string(src);
src += '-join';
num = src.lastIndexOf('/') + 1,
sub = src.substr(src, num),
id = src.replace(sub, '');
/* убираем точки */
id = id.replace(/\./g, '-');
}
return id;
};
/** if (isStr) {
* load file countent via ajax if (~src.indexOf(':'))
* src += '-join';
* @param pParams
*/
load.ajax = function(params) {
var data,
p = params,
isObject = itype.object(p.data),
isArray = itype.array(p.data),
isArrayBuf = itype(p.data) === 'arraybuffer',
type = p.type || p.method || 'GET',
headers = p.headers || {},
xhr = new XMLHttpRequest();
xhr.open(type, p.url, true); num = src.lastIndexOf('/') + 1,
sub = src.substr(src, num),
id = src.replace(sub, '');
Object.keys(headers).forEach(function(name) { /* убираем точки */
var value = headers[name]; id = id.replace(/\./g, '-');
xhr.setRequestHeader(name, value); }
});
return id;
};
/**
* load file countent via ajax
*
* @param pParams
*/
load.ajax = function(params) {
var data,
p = params,
isObject = itype.object(p.data),
isArray = itype.array(p.data),
isArrayBuf = itype(p.data) === 'arraybuffer',
type = p.type || p.method || 'GET',
headers = p.headers || {},
xhr = new XMLHttpRequest();
xhr.open(type, p.url, true);
Object.keys(headers).forEach(function(name) {
var value = headers[name];
xhr.setRequestHeader(name, value);
});
if (p.responseType)
xhr.responseType = p.responseType;
if (!isArrayBuf && isObject || isArray)
data = Util.json.stringify(p.data);
else
data = p.data;
xhr.onreadystatechange = function(event) {
var TYPE_JSON, type, data, isContain, notText,
xhr = event.target,
OK = 200;
if (p.responseType) if (xhr.readyState === xhr.DONE) {
xhr.responseType = p.responseType; Images.clearProgress();
TYPE_JSON = 'application/json';
if (!isArrayBuf && isObject || isArray) type = xhr.getResponseHeader('content-type');
data = Util.json.stringify(p.data);
else
data = p.data;
xhr.onreadystatechange = function(event) {
var TYPE_JSON, type, data, isContain, notText,
xhr = event.target,
OK = 200;
if (xhr.readyState === xhr.DONE) { if (xhr.status !== OK) {
Images.clearProgress(); Util.exec(p.error, xhr);
TYPE_JSON = 'application/json'; } else {
type = xhr.getResponseHeader('content-type'); data = xhr.response;
notText = p.dataType !== 'text',
isContain = ~type.indexOf(TYPE_JSON);
if (xhr.status !== OK) { if (type && isContain && notText)
Util.exec(p.error, xhr); data = Util.json.parse(xhr.response) || xhr.response;
} else {
data = xhr.response;
notText = p.dataType !== 'text',
isContain = ~type.indexOf(TYPE_JSON);
if (type && isContain && notText) Util.exec(p.success, data, xhr.statusText, xhr);
data = Util.json.parse(xhr.response) || xhr.response;
Util.exec(p.success, data, xhr.statusText, xhr);
}
} }
}; }
xhr.send(data);
}; };
load.put = function(url, body) { xhr.send(data);
var emitter = Emitify(), };
xhr = new XMLHttpRequest();
load.put = function(url, body) {
var emitter = Emitify(),
xhr = new XMLHttpRequest();
url = encodeURI(url);
url = url.replace('#', '%23');
xhr.open('put', url, true);
xhr.upload.onprogress = function(event) {
var percent, count;
url = encodeURI(url); if (event.lengthComputable) {
url = url.replace('#', '%23'); percent = (event.loaded / event.total) * 100;
count = Math.round(percent);
xhr.open('put', url, true);
xhr.upload.onprogress = function(event) {
var percent, count;
if (event.lengthComputable) { emitter.emit('progress', count);
percent = (event.loaded / event.total) * 100; }
count = Math.round(percent);
};
emitter.emit('progress', count);
xhr.onreadystatechange = function() {
var error,
over = xhr.readyState === xhr.DONE,
OK = 200;
if (over)
if (xhr.status === OK) {
emitter.emit('end');
} else {
error = Error(xhr.responseText);
emitter.emit('error', error);
} }
};
xhr.onreadystatechange = function() {
var error,
over = xhr.readyState === xhr.DONE,
OK = 200;
if (over)
if (xhr.status === OK) {
emitter.emit('end');
} else {
error = Error(xhr.responseText);
emitter.emit('error', error);
}
};
xhr.send(body);
return emitter;
}; };
load.ext = function(src, func) { xhr.send(body);
var element,
ext = Util.getExt(src);
switch (ext) {
case '.js':
element = load.js(src, func);
break;
case '.css':
element = load.css(src, func);
break;
default:
element = load({
src : src,
func : func
});
}
return element;
};
/** return emitter;
* create elements and load them to DOM-tree };
* one-by-one
* load.ext = function(src, func) {
* @param params var element,
* @param callback ext = Util.getExt(src);
*/
load.series = function(params, callback) {
var funcs = [];
if (params) {
funcs = params.map(function(url) {
return load.ext.bind(null, url);
})
.concat(callback);
Util.exec.series(funcs);
}
return load;
};
/** switch (ext) {
* improve callback of funcs so case '.js':
* we pop number of function and element = load.js(src, func);
* if it's last we call pCallBack break;
*
* @param params
* @param callback - onload function
*/
load.parallel = function(params, callback) {
var funcs = [];
if (params) {
funcs = params.map(function(url) {
return load.ext.bind(null, url);
});
Util.exec.parallel(funcs, callback);
}
return load;
};
/** case '.css':
* Функция загружает js-файл element = load.css(src, func);
* break;
* @param pSrc
* @param pFunc
*/
load.js = function(src, func) {
var element = load({
name : 'script',
src : src,
func : func
});
return element;
},
load.css = function(src, callback) { default:
var element = load({ element = load({
name : 'link',
src : src, src : src,
parent : document.head, func : func
func : callback
}); });
}
return element;
};
/** return element;
* Функция создаёт елемент style и записывает туда стили };
* @param pParams_o - структура параметров, заполняеться таким
* образом: {src: ' ',func: '', id: '', element: '', inner: ''} /**
* все параметры опциональны * create elements and load them to DOM-tree
*/ * one-by-one
load.style = function(params) { *
if (!params.name) * @param params
params.name = 'style'; * @param callback
*/
load.series = function(params, callback) {
var funcs = [];
if (params) {
funcs = params.map(function(url) {
return load.ext.bind(null, url);
})
.concat(callback);
if (!params.parent) Util.exec.series(funcs);
params.parent = document.head; }
return load(params);
};
return load; return load;
} };
})(Util, DOM);
/**
* improve callback of funcs so
* we pop number of function and
* if it's last we call pCallBack
*
* @param params
* @param callback - onload function
*/
load.parallel = function(params, callback) {
var funcs = [];
if (params) {
funcs = params.map(function(url) {
return load.ext.bind(null, url);
});
Util.exec.parallel(funcs, callback);
}
return load;
};
/**
* Функция загружает js-файл
*
* @param src
* @param func
*/
load.js = (src, func) => {
const name = 'script';
return load({
name,
src,
func,
});
},
load.css = (src, func) => {
const name = 'link';
const {head:parent} = document;
return load({
name,
src,
parent,
func
});
};
/**
* Функция создаёт елемент style и записывает туда стили
* @param params - структура параметров, заполняеться таким
* образом: {src: ' ',func: '', id: '', element: '', inner: ''}
* все параметры опциональны
*/
load.style = (params) => {
const {
id,
src,
name = 'style',
func,
inner,
parent = document.head,
element,
} = params;
return load({
id,
src,
func,
name,
inner,
parent,
element,
});
};
return load;
}

View file

@ -1,58 +1,56 @@
var CloudCmd, Util, DOM; 'use strict';
(function(CloudCmd, Util, DOM) { /*global CloudCmd, Util, DOM */
'use strict';
window.CloudCmd.Markdown = MarkdownProto;
CloudCmd.Markdown = MarkdownProto;
function MarkdownProto(nameParam, optionsParam) {
var Images = DOM.Images,
RESTful = DOM.RESTful,
Markdown = RESTful.Markdown,
MD = this;
function MarkdownProto(nameParam, optionsParam) { function init() {
var Images = DOM.Images, Images.show.load('top');
RESTful = DOM.RESTful,
Markdown = RESTful.Markdown,
MD = this;
function init() {
Images.show.load('top');
Util.exec.series([
CloudCmd.View,
Util.exec.with(MD.show, null, null),
]);
}
this.show = function(name, options) { Util.exec.series([
var o = options || optionsParam || {}, CloudCmd.View,
relativeQuery = '?relative'; Util.exec.with(MD.show, null, null),
]);
if (!name)
name = nameParam;
Images.show.load(o.positionLoad);
if (o.relative)
name += relativeQuery;
Markdown.read(name, function(error, result) {
var div = DOM.load({
name : 'div',
className : 'help',
inner : result
});
Images.hide();
CloudCmd.View.show(div);
nameParam =
optionsParam = null;
});
};
this.hide = function() {
CloudCmd.View.hide();
};
init();
} }
})(CloudCmd, Util, DOM); this.show = function(name, options) {
var o = options || optionsParam || {},
relativeQuery = '?relative';
if (!name)
name = nameParam;
Images.show.load(o.positionLoad);
if (o.relative)
name += relativeQuery;
Markdown.read(name, function(error, result) {
var div = DOM.load({
name : 'div',
className : 'help',
inner : result
});
Images.hide();
CloudCmd.View.show(div);
nameParam =
optionsParam = null;
});
};
this.hide = function() {
CloudCmd.View.hide();
};
init();
}

View file

@ -1,357 +1,351 @@
var CloudCmd, Util, DOM, CloudFunc, MenuIO; /* global CloudCmd, Util, DOM, CloudFunc */
(function(CloudCmd, Util, DOM, CloudFunc) { 'use strict';
'use strict';
CloudCmd.Menu = MenuProto;
function MenuProto(position) {
const config = CloudCmd.config;
const Buffer = DOM.Buffer;
const Info = DOM.CurrentInfo;
CloudCmd.Menu = MenuProto; let Loading = true,
Key = CloudCmd.Key,
Events = DOM.Events,
Dialog = DOM.Dialog,
Images = DOM.Images,
Menu = this,
TITLE = 'Menu',
function MenuProto(position) { MenuShowedName,
var config = CloudCmd.config; MenuContext,
var Buffer = DOM.Buffer, MenuContextFile;
Info = DOM.CurrentInfo,
Loading = true, this.ENABLED = false;
Key = CloudCmd.Key,
Events = DOM.Events, function init() {
Dialog = DOM.Dialog, Loading = true;
Images = DOM.Images, Menu.show();
Menu = this,
TITLE = 'Menu',
MenuShowedName,
MenuContext,
MenuContextFile;
this.ENABLED = false; Events.addKey(listener);
function init() {
Loading = true;
Menu.show();
Events.addKey(listener);
}
this.hide = function() {
MenuContext.hide();
MenuContextFile.hide();
};
this.show = function(position) {
var x, y,
showFunc;
if (position) {
x = position.x;
y = position.y;
}
showFunc = function() {
show(x, y);
Images.hide();
};
Util.exec.if(MenuIO, showFunc, function() {
DOM.loadMenu(function(error) {
if (error)
Dialog.alert(TITLE, error);
else
showFunc();
});
});
};
function show(x, y) {
var pos;
if (!x || !y) {
if (position) {
x = position.x;
y = position.y;
} else {
pos = getCurrentPosition();
x = pos.x;
y = pos.y;
}
}
if (!Loading) {
MenuContext.show(x, y);
MenuContextFile.show(x, y);
} else {
loadFileMenuData(function(isAuth, menuDataFile) {
var is, menu,
NOT_FILE = true,
fm = DOM.getFM(),
menuData = getMenuData(isAuth),
options = getOptions(NOT_FILE),
optionsFile = getOptions();
MenuContext = new MenuIO(fm, options, menuData);
MenuContextFile = new MenuIO(fm, optionsFile, menuDataFile);
is = DOM.getCurrentByPosition({
x: x,
y: y
});
if (is)
menu = MenuContextFile;
else
menu = MenuContext;
menu.show(x, y);
Loading = false;
position = null;
});
}
}
function getOptions(notFile) {
var name, func, options;
if (notFile) {
name = 'context';
func = Key.unsetBind;
} else {
name = 'contextFile';
}
options = {
icon : true,
beforeClose : Key.setBind,
beforeShow : Util.exec.with(beforeShow, func),
beforeClick : beforeClick,
name : name,
};
return options;
}
function getMenuData(isAuth) {
var menu = {
'Paste' : Buffer.paste,
'New' : {
'File' : DOM.promptNewFile,
'Directory' : DOM.promptNewDir
},
'Upload' : function() {
CloudCmd.Upload.show();
},
'Upload From Cloud': uploadFromCloud,
'(Un)Select All': DOM.toggleAllSelectedFiles
};
if (isAuth)
menu['Log Out'] = CloudCmd.logOut;
return menu;
}
function curry(fn) {
var args = [].slice.call(arguments, 1);
return function() {
fn.apply(null, args.concat(arguments));
};
}
function loadFileMenuData(callback) {
var is = CloudCmd.config('auth');
var show = function(name) {
CloudCmd[name].show();
},
Dialog = DOM.Dialog,
menuData = getMenuData(is),
menu = {
'View' : curry(show, 'View'),
'Edit' : curry(show, 'Edit'),
'Rename' : function() {
setTimeout(DOM.renameCurrent, 100);
},
'Delete' : function() {
CloudCmd.Operation.show('delete');
},
'Pack' : function() {
CloudCmd.Operation.show('pack');
},
'Extract' : function() {
CloudCmd.Operation.show('extract');
},
'Download' : preDownload,
'Upload To Cloud': curry(uploadTo, 'Cloud'),
'Cut' : function() {
isCurrent(Buffer.cut, function() {
Dialog.alert.noFiles(TITLE);
});
},
'Copy' : function() {
isCurrent(Buffer.copy, function() {
Dialog.alert.noFiles(TITLE);
});
},
};
Util.copyObj(menu, menuData);
callback(is, menu);
}
function isCurrent(yesFn, noFn) {
if (Info.name !== '..')
yesFn();
else
noFn();
}
function isPath(x, y) {
var el, elements, is,
panel = Info.panel;
if (panel) {
el = document.elementFromPoint(x, y),
elements = panel.querySelectorAll('[data-name="js-path"] *'),
is = ~[].indexOf.call(elements, el);
}
return is;
}
function beforeShow(callback, params) {
var name = params.name,
notShow = DOM.getCurrentByPosition({
x: params.x,
y: params.y
});
if (params.name === 'contextFile') {
notShow = !notShow;
}
if (!notShow)
MenuShowedName = name;
Util.exec(callback);
if (!notShow)
notShow = isPath(params.x, params.y);
return notShow;
}
function beforeClick(name) {
var notCall;
if (MenuShowedName !== name)
notCall = true;
return notCall;
}
function uploadTo(nameModule) {
Info.getData(function(error, data) {
var name = Info.name,
execFrom = CloudCmd.execFromModule;
execFrom(nameModule, 'uploadFile', name, data);
});
CloudCmd.log('Uploading to ' + name + '...');
}
function uploadFromCloud() {
Images.show.load('top');
CloudCmd.execFromModule('Cloud', 'saveFile', function(name, data) {
var path = DOM.getCurrentDirPath() + name;
DOM.RESTful.write(path, data, function(error) {
!error && CloudCmd.refresh();
});
});
}
function preDownload() {
download(config('packer'));
}
function download(type) {
var TIME = 30 * 1000,
prefixUr = CloudCmd.PREFIX_URL,
FS = CloudFunc.FS,
PACK = '/pack',
date = Date.now(),
files = DOM.getActiveFiles();
if (!files.length)
DOM.Dialog.alert.noFiles(TITLE);
else
files.forEach(function(file) {
var element,
selected = DOM.isSelected(file),
path = DOM.getCurrentPath(file),
id = DOM.load.getIdBySrc(path),
isDir = DOM.isCurrentIsDir(file);
CloudCmd.log('downloading file ' + path + '...');
/*
* if we send ajax request -
* no need in hash so we escape #
* and all other characters, like "%"
*/
path = path.replace(/#/g, '%23');
path = encodeURI(path);
if (isDir)
path = prefixUr + PACK + path + DOM.getPackerExt(type);
else
path = prefixUr + FS + path + '?download';
element = DOM.load({
id : id + '-' + date,
name : 'iframe',
async : false,
className : 'hidden',
src : path
});
setTimeout(function() {
document.body.removeChild(element);
}, TIME);
if (selected)
DOM.toggleSelectedFile(file);
});
}
function getCurrentPosition() {
var current = Info.element,
rect = current.getBoundingClientRect();
position = {
x: rect.left + rect.width / 3,
y: rect.top
};
return position;
}
function listener(event) {
var position,
F9 = Key.F9,
ESC = Key.ESC,
key = event.keyCode,
isBind = Key.isBind();
if (isBind && key === F9) {
position = getCurrentPosition();
MenuContext.show(position.x, position.y);
event.preventDefault();
} else if (key === ESC) {
Menu.hide();
}
}
init();
} }
})(CloudCmd, Util, DOM, CloudFunc);
this.hide = function() {
MenuContext.hide();
MenuContextFile.hide();
};
this.show = function(position) {
var x, y,
showFunc;
if (position) {
x = position.x;
y = position.y;
}
showFunc = function() {
show(x, y);
Images.hide();
};
Util.exec.if(window.MenuIO, showFunc, () => {
DOM.loadMenu((error) => {
if (error)
return Dialog.alert(TITLE, error);
showFunc();
});
});
};
function show(x, y) {
var pos;
if (!x || !y) {
if (position) {
x = position.x;
y = position.y;
} else {
pos = getCurrentPosition();
x = pos.x;
y = pos.y;
}
}
if (!Loading) {
MenuContext.show(x, y);
MenuContextFile.show(x, y);
return;
}
loadFileMenuData((isAuth, menuDataFile) => {
const NOT_FILE = true;
const fm = DOM.getFM();
const menuData = getMenuData(isAuth);
const options = getOptions(NOT_FILE);
const optionsFile = getOptions();
const MenuIO = window.MenuIO;
MenuContext = new MenuIO(fm, options, menuData);
MenuContextFile = new MenuIO(fm, optionsFile, menuDataFile);
const is = DOM.getCurrentByPosition({x, y});
const menu = is ? MenuContextFile : MenuContext;
menu.show(x, y);
Loading = false;
position = null;
});
}
function getOptions(notFile) {
var name, func, options;
if (notFile) {
name = 'context';
func = Key.unsetBind;
} else {
name = 'contextFile';
}
options = {
icon : true,
beforeClose : Key.setBind,
beforeShow : Util.exec.with(beforeShow, func),
beforeClick : beforeClick,
name : name,
};
return options;
}
function getMenuData(isAuth) {
var menu = {
'Paste' : Buffer.paste,
'New' : {
'File' : DOM.promptNewFile,
'Directory' : DOM.promptNewDir
},
'Upload' : function() {
CloudCmd.Upload.show();
},
'Upload From Cloud': uploadFromCloud,
'(Un)Select All': DOM.toggleAllSelectedFiles
};
if (isAuth)
menu['Log Out'] = CloudCmd.logOut;
return menu;
}
function curry(fn) {
var args = [].slice.call(arguments, 1);
return function() {
fn.apply(null, args.concat(arguments));
};
}
function loadFileMenuData(callback) {
var is = CloudCmd.config('auth');
var show = function(name) {
CloudCmd[name].show();
},
Dialog = DOM.Dialog,
menuData = getMenuData(is),
menu = {
'View' : curry(show, 'View'),
'Edit' : curry(show, 'Edit'),
'Rename' : function() {
setTimeout(DOM.renameCurrent, 100);
},
'Delete' : function() {
CloudCmd.Operation.show('delete');
},
'Pack' : function() {
CloudCmd.Operation.show('pack');
},
'Extract' : function() {
CloudCmd.Operation.show('extract');
},
'Download' : preDownload,
'Upload To Cloud': curry(uploadTo, 'Cloud'),
'Cut' : function() {
isCurrent(Buffer.cut, function() {
Dialog.alert.noFiles(TITLE);
});
},
'Copy' : function() {
isCurrent(Buffer.copy, function() {
Dialog.alert.noFiles(TITLE);
});
},
};
Util.copyObj(menu, menuData);
callback(is, menu);
}
function isCurrent(yesFn, noFn) {
if (Info.name !== '..')
yesFn();
else
noFn();
}
function isPath(x, y) {
var el, elements, is,
panel = Info.panel;
if (panel) {
el = document.elementFromPoint(x, y),
elements = panel.querySelectorAll('[data-name="js-path"] *'),
is = ~[].indexOf.call(elements, el);
}
return is;
}
function beforeShow(callback, params) {
var name = params.name,
notShow = DOM.getCurrentByPosition({
x: params.x,
y: params.y
});
if (params.name === 'contextFile') {
notShow = !notShow;
}
if (!notShow)
MenuShowedName = name;
Util.exec(callback);
if (!notShow)
notShow = isPath(params.x, params.y);
return notShow;
}
function beforeClick(name) {
var notCall;
if (MenuShowedName !== name)
notCall = true;
return notCall;
}
function uploadTo(nameModule) {
Info.getData(function(error, data) {
var name = Info.name,
execFrom = CloudCmd.execFromModule;
execFrom(nameModule, 'uploadFile', name, data);
});
CloudCmd.log('Uploading to ' + name + '...');
}
function uploadFromCloud() {
Images.show.load('top');
CloudCmd.execFromModule('Cloud', 'saveFile', function(name, data) {
var path = DOM.getCurrentDirPath() + name;
DOM.RESTful.write(path, data, function(error) {
!error && CloudCmd.refresh();
});
});
}
function preDownload() {
download(config('packer'));
}
function download(type) {
var TIME = 30 * 1000,
prefixUr = CloudCmd.PREFIX_URL,
FS = CloudFunc.FS,
PACK = '/pack',
date = Date.now(),
files = DOM.getActiveFiles();
if (!files.length)
DOM.Dialog.alert.noFiles(TITLE);
else
files.forEach(function(file) {
var element,
selected = DOM.isSelected(file),
path = DOM.getCurrentPath(file),
id = DOM.load.getIdBySrc(path),
isDir = DOM.isCurrentIsDir(file);
CloudCmd.log('downloading file ' + path + '...');
/*
* if we send ajax request -
* no need in hash so we escape #
* and all other characters, like "%"
*/
path = path.replace(/#/g, '%23');
path = encodeURI(path);
if (isDir)
path = prefixUr + PACK + path + DOM.getPackerExt(type);
else
path = prefixUr + FS + path + '?download';
element = DOM.load({
id : id + '-' + date,
name : 'iframe',
async : false,
className : 'hidden',
src : path
});
setTimeout(function() {
document.body.removeChild(element);
}, TIME);
if (selected)
DOM.toggleSelectedFile(file);
});
}
function getCurrentPosition() {
var current = Info.element,
rect = current.getBoundingClientRect();
position = {
x: rect.left + rect.width / 3,
y: rect.top
};
return position;
}
function listener(event) {
var position,
F9 = Key.F9,
ESC = Key.ESC,
key = event.keyCode,
isBind = Key.isBind();
if (isBind && key === F9) {
position = getCurrentPosition();
MenuContext.show(position.x, position.y);
event.preventDefault();
} else if (key === ESC) {
Menu.hide();
}
}
init();
}

View file

@ -1,63 +1,56 @@
/* global Util */
/* global DOM */
/* global CloudCmd */ /* global CloudCmd */
var Util, DOM;
(function(Util, DOM) { 'use strict';
'use strict';
const Notify = Util.extendProto(NotifyProto);
const DOMProto = Object.getPrototypeOf(DOM);
Util.extend(DOMProto, {
Notify
});
function NotifyProto() {
var Events = DOM.Events,
Show,
Notify = this,
Notification = window.Notification;
var config = CloudCmd.config; Events.add({
var Notify = Util.extendProto(NotifyProto); 'blur': () => {
var DOMProto = Object.getPrototypeOf(DOM); Show = true;
},
Util.extend(DOMProto, { 'focus': () => {
Notify: Notify Show = false;
}
}); });
function NotifyProto() { this.send = (msg) => {
var Events = DOM.Events, const notifications = CloudCmd.config('notifications');
Show, const focus = window.focus.bind(window);
Notify = this, const granted = Notify.check();
Notification = window.Notification;
Events.add({ if (notifications && granted && Show) {
'blur': function() { const notify = new Notification(msg, {
Show = true; icon: '/img/favicon/favicon-notify.png'
}, });
'focus': function() {
Show = false; Events.addClick(notify, focus);
} }
}); };
this.check = () => {
const Not = Notification;
const perm = Not && Not.permission;
this.send = function(msg) { if (perm === 'granted')
var notify, return true;
notifications = config('notifications'), };
focus = window.focus.bind(window),
granted = Notify.check(); this.request = () => {
if (Notification)
if (notifications && granted && Show) { Notification.requestPermission();
notify = new Notification(msg, { };
icon: '/img/favicon/favicon-notify.png' }
});
Events.addClick(notify, focus);
}
};
this.check = function () {
var ret,
Not = Notification,
perm = Not && Not.permission;
if (perm === 'granted')
ret = true;
return ret;
};
this.request = function () {
var Not = Notification;
if (Not)
Not.requestPermission();
};
}
})(Util, DOM);

File diff suppressed because it is too large Load diff

View file

@ -1,201 +1,197 @@
/* global itype */ 'use strict';
var Util, DOM, jQuery; /* global Util, DOM, $ */
(function(window, document, Util, DOM, $) { const type = require('itype/legacy');
'use strict';
if (!window.XMLHttpRequest || !document.head)
var type = itype; DOM.load.ajax = $.ajax;
if (!window.XMLHttpRequest || !document.head) /* setting head ie6 - ie8 */
DOM.load.ajax = $.ajax; if (!document.head)
document.head = $('head')[0];
if (!Function.bind)
Function.prototype.bind = function (context) {
var aArgs = [].slice.call(arguments, 1),
fToBind = this,
NOP = function () {},
fBound = function () {
var arr = [].slice.call(arguments),
args = aArgs.concat(arr);
return fToBind.apply(context, args);
};
/* setting head ie6 - ie8 */ NOP.prototype = this.prototype;
if (!document.head) fBound.prototype = new NOP();
document.head = $('head')[0];
if (!Function.bind)
Function.prototype.bind = function (context) {
var aArgs = [].slice.call(arguments, 1),
fToBind = this,
NOP = function () {},
fBound = function () {
var arr = [].slice.call(arguments),
args = aArgs.concat(arr);
return fToBind.apply(context, args);
};
NOP.prototype = this.prototype;
fBound.prototype = new NOP();
return fBound;
};
if (!Array.isArray)
Array.isArray = function(arr) {
return type(arr) === 'array';
};
if (!document.addEventListener)
/**
* safe add event listener on ie
* @param pType
* @param pListener
*/
DOM.Events.add = function(pType, pElement, pListener) {
var lRet;
if (!pElement)
pElement = window;
lRet = $(pElement).bind(pType, null, pListener);
return lRet;
};
if (!document.removeEventListener) {
DOM.Events.remove = function(pType, pElement, pListener) {
if (!pElement)
pElement = window;
$(pElement).unbind(pType, pListener);
};
}
if (!document.getElementsByClassName) {
DOM.getByClassAll = function(pClass, pElement) {
var lClass = '.' + pClass,
lResult;
if (pElement)
lResult = $(pElement).find(lClass);
else
lResult = $.find(lClass);
return lResult;
};
}
/* function polyfill webkit standart function
* https://gist.github.com/2581101
*/
DOM.scrollIntoViewIfNeeded = function(element, centerIfNeeded) {
var parent,
topWidth,
leftWidth,
parentComputedStyle,
parentBorderTopWidth,
parentBorderLeftWidth,
overTop,
overBottom,
overLeft,
overRight,
alignWithTop;
if (window.getComputedStyle) { return fBound;
if (arguments.length === 1)
centerIfNeeded = false;
parent = element.parentNode;
parentComputedStyle = window.getComputedStyle(parent, null);
topWidth = parentComputedStyle.getPropertyValue('border-top-width');
leftWidth = parentComputedStyle.getPropertyValue('border-left-width');
parentBorderTopWidth = parseInt(topWidth, 10);
parentBorderLeftWidth = parseInt(leftWidth, 10);
overTop = element.offsetTop - parent.offsetTop < parent.scrollTop,
overBottom =
(element.offsetTop -
parent.offsetTop +
element.clientHeight -
parentBorderTopWidth) >
(parent.scrollTop + parent.clientHeight),
overLeft = element.offsetLeft -
parent.offsetLeft < parent.scrollLeft,
overRight =
(element.offsetLeft -
parent.offsetLeft +
element.clientWidth -
parentBorderLeftWidth) >
(parent.scrollLeft + parent.clientWidth),
alignWithTop = overTop && !overBottom;
if ((overTop || overBottom) && centerIfNeeded)
parent.scrollTop =
element.offsetTop -
parent.offsetTop -
parent.clientHeight / 2 -
parentBorderTopWidth +
element.clientHeight / 2;
if ((overLeft || overRight) && centerIfNeeded)
parent.scrollLeft =
element.offsetLeft -
parent.offsetLeft -
parent.clientWidth / 2 -
parentBorderLeftWidth +
element.clientWidth / 2;
if ((overTop || overBottom || overLeft || overRight) && !centerIfNeeded)
element.scrollIntoView(alignWithTop);
}
}; };
if (!window.JSON) { if (!Array.isArray)
Util.json.parse = $.parseJSON; Array.isArray = function(arr) {
return type(arr) === 'array';
};
if (!document.addEventListener)
/**
* safe add event listener on ie
* @param pType
* @param pListener
*/
DOM.Events.add = function(pType, pElement, pListener) {
var lRet;
/* https://gist.github.com/754454 */ if (!pElement)
Util.json.stringify = function(obj) { pElement = window;
var n, v, has,
ret = '', lRet = $(pElement).bind(pType, null, pListener);
value = '',
json = [], return lRet;
isStr = type.string(obj), };
isObj = type.object(obj),
isArray = type.array(obj); if (!document.removeEventListener) {
DOM.Events.remove = function(pType, pElement, pListener) {
if (!pElement)
pElement = window;
$(pElement).unbind(pType, pListener);
};
}
if (!document.getElementsByClassName) {
DOM.getByClassAll = function(pClass, pElement) {
var lClass = '.' + pClass,
lResult;
if (pElement)
lResult = $(pElement).find(lClass);
else
lResult = $.find(lClass);
return lResult;
};
}
/* function polyfill webkit standart function
* https://gist.github.com/2581101
*/
DOM.scrollIntoViewIfNeeded = function(element, centerIfNeeded) {
var parent,
topWidth,
leftWidth,
parentComputedStyle,
parentBorderTopWidth,
parentBorderLeftWidth,
overTop,
overBottom,
overLeft,
overRight,
alignWithTop;
if (window.getComputedStyle) {
if (arguments.length === 1)
centerIfNeeded = false;
parent = element.parentNode;
parentComputedStyle = window.getComputedStyle(parent, null);
topWidth = parentComputedStyle.getPropertyValue('border-top-width');
leftWidth = parentComputedStyle.getPropertyValue('border-left-width');
parentBorderTopWidth = parseInt(topWidth, 10);
parentBorderLeftWidth = parseInt(leftWidth, 10);
if (!isObj || obj === null) { overTop = element.offsetTop - parent.offsetTop < parent.scrollTop,
// simple data type overBottom =
if (isStr) (element.offsetTop -
obj = '"' + obj + '"'; parent.offsetTop +
element.clientHeight -
parentBorderTopWidth) >
(parent.scrollTop + parent.clientHeight),
overLeft = element.offsetLeft -
parent.offsetLeft < parent.scrollLeft,
overRight =
(element.offsetLeft -
parent.offsetLeft +
element.clientWidth -
parentBorderLeftWidth) >
(parent.scrollLeft + parent.clientWidth),
alignWithTop = overTop && !overBottom;
if ((overTop || overBottom) && centerIfNeeded)
parent.scrollTop =
element.offsetTop -
parent.offsetTop -
parent.clientHeight / 2 -
parentBorderTopWidth +
element.clientHeight / 2;
if ((overLeft || overRight) && centerIfNeeded)
parent.scrollLeft =
element.offsetLeft -
parent.offsetLeft -
parent.clientWidth / 2 -
parentBorderLeftWidth +
element.clientWidth / 2;
if ((overTop || overBottom || overLeft || overRight) && !centerIfNeeded)
element.scrollIntoView(alignWithTop);
}
};
if (!window.JSON) {
Util.json.parse = $.parseJSON;
/* https://gist.github.com/754454 */
Util.json.stringify = function(obj) {
var n, v, has,
ret = '',
value = '',
json = [],
isStr = type.string(obj),
isObj = type.object(obj),
isArray = type.array(obj);
if (!isObj || obj === null) {
// simple data type
if (isStr)
obj = '"' + obj + '"';
ret += obj;
} else {
// recurse array or object
for (n in obj) {
v = obj[n];
has = obj.hasOwnProperty(n);
ret += obj; if (has) {
} else { isStr = type.string(v);
// recurse array or object isObj = type.object(v);
for (n in obj) {
v = obj[n];
has = obj.hasOwnProperty(n);
if (has) { if (isStr)
isStr = type.string(v); v = '"' + v + '"';
isObj = type.object(v); else if (v && isObj)
v = Util.json.stringify(v);
if (isStr)
v = '"' + v + '"'; if (!isArray)
else if (v && isObj) value = '"' + n + '":';
v = Util.json.stringify(v);
json.push(value + v);
if (!isArray)
value = '"' + n + '":';
json.push(value + v);
}
} }
if (isArray)
ret = '[' + json + ']';
else
ret = '{' + json + '}';
} }
return ret; if (isArray)
}; ret = '[' + json + ']';
} else
ret = '{' + json + '}';
})(window, document, Util, DOM, jQuery); }
return ret;
};
}

View file

@ -1,215 +1,213 @@
/* global itype */ 'use strict';
var Util, DOM, CloudFunc, CloudCmd; const itype = require('itype/legacy');
(function(Util, DOM, CloudFunc) { /* global Util, DOM, CloudFunc, CloudCmd */
'use strict';
const RESTful= Util.extendProto(RESTfulProto);
const DOMProto = Object.getPrototypeOf(DOM);
Util.extend(DOMProto, {
RESTful
});
function RESTfulProto() {
const Images = DOM.Images;
var RESTful = Util.extendProto(RESTfulProto), this.delete = (url, data, callback) => {
DOMProto = Object.getPrototypeOf(DOM); var isFunc = itype.function(data);
Util.extend(DOMProto, {
RESTful: RESTful
});
function RESTfulProto() {
var Images = DOM.Images;
this.delete = function(url, data, callback) { if (!callback && isFunc) {
var isFunc = itype.function(data); callback = data;
data = null;
if (!callback && isFunc) { }
callback = data;
data = null; sendRequest({
} method : 'DELETE',
url : CloudFunc.FS + url,
data,
callback,
imgPosition : { top: !!data }
});
};
this.patch = function(url, data, callback) {
var isFunc = itype.function(data);
if (!callback && isFunc) {
callback = data;
data = null;
}
sendRequest({
method : 'PATCH',
url : CloudFunc.FS + url,
data : data,
callback : callback,
imgPosition : { top: true }
});
};
this.write = function(url, data, callback) {
var isFunc = itype.function(data);
if (!callback && isFunc) {
callback = data;
data = null;
}
sendRequest({
method : 'PUT',
url : CloudFunc.FS + url,
data : data,
callback : callback,
imgPosition : { top: true }
});
};
this.read = function(url, dataType, callback) {
var isQuery = /\?/.test(url);
var isBeautify = /\?beautify$/.test(url);
var isMinify = /\?minify$/.test(url);
var notLog = !isQuery || isBeautify || isMinify;
var isFunc = itype.function(dataType);
if (!callback && isFunc) {
callback = dataType;
dataType = 'text';
}
sendRequest({
method: 'GET',
url: CloudFunc.FS + url,
callback: callback,
notLog: notLog,
dataType: dataType
});
};
this.cp = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/cp',
data : data,
callback : callback,
imgPosition : { top: true }
});
};
this.pack = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/pack',
data : data,
callback : callback
});
};
this.extract = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/extract',
data : data,
callback : callback
});
};
this.mv = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/mv',
data : data,
callback : callback,
imgPosition : { top: true }
});
};
this.Config = {
read: function(callback) {
sendRequest({ sendRequest({
method : 'DELETE', method : 'GET',
url : CloudFunc.FS + url, url : '/config',
data : data,
callback : callback, callback : callback,
imgPosition : { top: !!data } imgPosition : { top: true },
notLog : true
}); });
}; },
this.patch = function(url, data, callback) { write: function(data, callback) {
var isFunc = itype.function(data);
if (!callback && isFunc) {
callback = data;
data = null;
}
sendRequest({ sendRequest({
method : 'PATCH', method : 'PATCH',
url : CloudFunc.FS + url, url : '/config',
data : data, data : data,
callback : callback, callback : callback,
imgPosition : { top: true } imgPosition : { top: true }
}); });
};
this.write = function(url, data, callback) {
var isFunc = itype.function(data);
if (!callback && isFunc) {
callback = data;
data = null;
}
sendRequest({
method : 'PUT',
url : CloudFunc.FS + url,
data : data,
callback : callback,
imgPosition : { top: true }
});
};
this.read = function(url, dataType, callback) {
var isQuery = /\?/.test(url);
var isBeautify = /\?beautify$/.test(url);
var isMinify = /\?minify$/.test(url);
var notLog = !isQuery || isBeautify || isMinify;
var isFunc = itype.function(dataType);
if (!callback && isFunc) {
callback = dataType;
dataType = 'text';
}
sendRequest({
method: 'GET',
url: CloudFunc.FS + url,
callback: callback,
notLog: notLog,
dataType: dataType
});
};
this.cp = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/cp',
data : data,
callback : callback,
imgPosition : { top: true }
});
};
this.pack = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/pack',
data : data,
callback : callback
});
};
this.extract = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/extract',
data : data,
callback : callback
});
};
this.mv = function(data, callback) {
sendRequest({
method : 'PUT',
url : '/mv',
data : data,
callback : callback,
imgPosition : { top: true }
});
};
this.Config = {
read: function(callback) {
sendRequest({
method : 'GET',
url : '/config',
callback : callback,
imgPosition : { top: true },
notLog : true
});
},
write: function(data, callback) {
sendRequest({
method : 'PATCH',
url : '/config',
data : data,
callback : callback,
imgPosition : { top: true }
});
}
};
this.Markdown = {
read : function(url, callback) {
sendRequest({
method : 'GET',
url : '/markdown' + url,
callback : callback,
imgPosition : { top: true },
notLog : true
});
},
render : function(data, callback) {
sendRequest({
method : 'PUT',
url : '/markdown',
data : data,
callback : callback,
imgPosition : { top: true },
notLog : true
});
}
};
function sendRequest(params) {
var p = params,
prefixUrl = CloudCmd.PREFIX_URL;
p.url = prefixUrl + p.url;
p.url = encodeURI(p.url);
/*
* if we send ajax request -
* no need in hash so we escape #
*/
p.url = p.url.replace('#', '%23');
DOM.load.ajax({
method : p.method,
url : p.url,
data : p.data,
dataType : p.dataType,
error : function(jqXHR) {
var response = jqXHR.responseText,
statusText = jqXHR.statusText,
status = jqXHR.status,
text = status === 404 ? response : statusText;
Images.show.error(text);
setTimeout(function() {
DOM.Dialog.alert(CloudCmd.TITLE, text);
}, 100);
p.callback(Error(text));
},
success : function(data) {
Images.hide();
if (!p.notLog)
CloudCmd.log(data);
p.callback(null, data);
}
});
} }
};
this.Markdown = {
read : function(url, callback) {
sendRequest({
method : 'GET',
url : '/markdown' + url,
callback : callback,
imgPosition : { top: true },
notLog : true
});
},
render : function(data, callback) {
sendRequest({
method : 'PUT',
url : '/markdown',
data : data,
callback : callback,
imgPosition : { top: true },
notLog : true
});
}
};
function sendRequest(params) {
var p = params,
prefixUrl = CloudCmd.PREFIX_URL;
p.url = prefixUrl + p.url;
p.url = encodeURI(p.url);
/*
* if we send ajax request -
* no need in hash so we escape #
*/
p.url = p.url.replace('#', '%23');
DOM.load.ajax({
method : p.method,
url : p.url,
data : p.data,
dataType : p.dataType,
error : function(jqXHR) {
var response = jqXHR.responseText,
statusText = jqXHR.statusText,
status = jqXHR.status,
text = status === 404 ? response : statusText;
Images.show.error(text);
setTimeout(function() {
DOM.Dialog.alert(CloudCmd.TITLE, text);
}, 100);
p.callback(Error(text));
},
success : function(data) {
Images.hide();
if (!p.notLog)
CloudCmd.log(data);
p.callback(null, data);
}
});
} }
})(Util, DOM, CloudFunc); }

View file

@ -1,38 +1,35 @@
'use strict';
/* global CloudCmd */ /* global CloudCmd */
/* global DOM */ const DOM = require('./dom');
(function() { var Info = DOM.CurrentInfo;
'use strict'; var sort = CloudCmd.sort;
var order = CloudCmd.order;
var position = DOM.getPanelPosition();
var sortPrevious = sort[position];
CloudCmd.sortPanel = function(name, panel) {
panel = panel || DOM.getPanel();
var Info = DOM.CurrentInfo; var position = panel
var sort = CloudCmd.sort; .dataset
var order = CloudCmd.order; .name
var position = DOM.getPanelPosition(); .replace('js-', '');
var sortPrevious = sort[position];
CloudCmd.sortPanel = function(name, panel) { if (name !== sortPrevious) {
panel = panel || DOM.getPanel(); order[position] = 'asc';
} else {
var position = panel if (order[position] === 'asc')
.dataset order[position] = 'desc';
.name else
.replace('js-', '');
if (name !== sortPrevious) {
order[position] = 'asc'; order[position] = 'asc';
} else { }
if (order[position] === 'asc')
order[position] = 'desc'; sortPrevious =
else sort[position] = name;
order[position] = 'asc';
} CloudCmd.refresh(panel, {
noCurrent: position !== Info.panelPosition
sortPrevious = });
sort[position] = name; };
CloudCmd.refresh(panel, {
noCurrent: position !== Info.panelPosition
});
};
})();

View file

@ -1,103 +1,103 @@
/* global Util */ 'use strict';
/* global DOM */
/* global itype */
(function(Util, DOM, localStorage, exec, json, itype) { const itype = require('itype/legacy');
'use strict'; const Util = require('../common/util');
const DOM = require('./dom');
const jonny = require('jonny');
const exec = require('execon');
const Storage = Util.extendProto(StorageProto);
const DOMProto = Object.getPrototypeOf(DOM);
Util.extend(DOMProto, {
Storage
});
function StorageProto() {
/* приватный переключатель возможности работы с кэшем */
var Allowed;
var Storage = Util.extendProto(StorageProto), /* функция проверяет возможно ли работать с кэшем каким-либо образом */
DOMProto = Object.getPrototypeOf(DOM); this.isAllowed = () => {
return Allowed && !!localStorage;
};
Util.extend(DOMProto, { /**
Storage: Storage * allow Storage usage
}); */
this.setAllowed = (isAllowed) => {
function StorageProto() { Allowed = isAllowed;
/* приватный переключатель возможности работы с кэшем */ };
var Allowed;
/** remove element */
this.remove = (item, callback) => {
var ret = Allowed;
/* функция проверяет возможно ли работать с кэшем каким-либо образом */ if (ret)
this.isAllowed = function() { localStorage.removeItem(item);
var ret = Allowed && !!localStorage;
return ret;
};
/** exec(callback, null, ret);
* allow Storage usage
*/
this.setAllowed = function(isAllowed) {
Allowed = isAllowed;
};
/** remove element */ return this;
this.remove = function(item, callback) { };
var ret = Allowed;
this.removeMatch = (string, callback) => {
var reg = RegExp('^' + string + '.*$');
Object.keys(localStorage).forEach(function(name) {
var is = reg.test(name);
if (ret) if (is)
localStorage.removeItem(item); localStorage.removeItem(name);
});
exec(callback, null, ret);
return this;
};
this.removeMatch = function(string, callback) { exec(callback);
var reg = RegExp('^' + string + '.*$');
return this;
Object.keys(localStorage).forEach(function(name) { };
var is = reg.test(name);
/** если доступен localStorage и
if (is) * в нём есть нужная нам директория -
localStorage.removeItem(name); * записываем данные в него
*/
this.set = (name, data, callback) => {
var str, error;
if (itype.object(data))
str = jonny.stringify(data);
if (Allowed && name)
error = exec.try(() => {
localStorage.setItem(name, str || data);
}); });
exec(callback);
return this;
};
/** если доступен localStorage и exec(callback, error);
* в нём есть нужная нам директория -
* записываем данные в него
*/
this.set = function(name, data, callback) {
var str, error;
if (itype.object(data))
str = json.stringify(data);
if (Allowed && name)
error = exec.try(function() {
localStorage.setItem(name, str || data);
});
exec(callback, error);
return this;
},
/** Если доступен Storage принимаем из него данные*/ return this;
this.get = function(name, callback) { },
var ret;
/** Если доступен Storage принимаем из него данные*/
if (Allowed) this.get = function(name, callback) {
ret = localStorage.getItem(name); var ret;
exec(callback, null, ret);
return this;
},
/** функция чистит весь кэш для всех каталогов*/ if (Allowed)
this.clear = function(callback) { ret = localStorage.getItem(name);
var ret = Allowed;
exec(callback, null, ret);
if (ret) return this;
localStorage.clear(); },
exec(callback, null, ret); /** функция чистит весь кэш для всех каталогов*/
this.clear = function(callback) {
return this; var ret = Allowed;
};
} if (ret)
})(Util, DOM, localStorage, Util.exec, Util.json, itype); localStorage.clear();
exec(callback, null, ret);
return this;
};
}

View file

@ -1,66 +1,63 @@
var CloudCmd, Util, DOM; /* global CloudCmd, Util, DOM */
(function(CloudCmd, Util, DOM) { 'use strict';
'use strict';
CloudCmd.Upload = UploadProto;
function UploadProto() {
var Images = DOM.Images,
Files = DOM.Files,
Upload = this;
CloudCmd.Upload = UploadProto; function init() {
Images.show.load('top');
function UploadProto() {
var Images = DOM.Images,
Files = DOM.Files,
Upload = this;
function init() { Util.exec.series([
Images.show.load('top'); CloudCmd.View,
Upload.show
Util.exec.series([ ]);
CloudCmd.View,
Upload.show
]);
}
this.show = function() {
Images.show.load('top');
Files.get('upload', function(error, data) {
CloudCmd.View.show(data, {
autoSize : true,
afterShow : afterShow
});
});
DOM.load.style({
id : 'upload-css',
inner : '[data-name=js-upload-file-button] {' +
'font-family: "Droid Sans Mono", "Ubuntu Mono", "Consolas", monospace;' +
'font-size: 20px;' +
'width: 97%' +
'}'
});
};
this.hide = function() {
CloudCmd.View.hide();
};
function afterShow() {
var button = DOM.getByDataName('js-upload-file-button');
Images.hide();
DOM.Events.add('change', button, function(event) {
var files = event.target.files;
Upload.hide();
DOM.uploadFiles(files);
});
}
init();
} }
})(CloudCmd, Util, DOM); this.show = function() {
Images.show.load('top');
Files.get('upload', function(error, data) {
CloudCmd.View.show(data, {
autoSize : true,
afterShow : afterShow
});
});
DOM.load.style({
id : 'upload-css',
inner : '[data-name=js-upload-file-button] {' +
'font-family: "Droid Sans Mono", "Ubuntu Mono", "Consolas", monospace;' +
'font-size: 20px;' +
'width: 97%' +
'}'
});
};
this.hide = function() {
CloudCmd.View.hide();
};
function afterShow() {
var button = DOM.getByDataName('js-upload-file-button');
Images.hide();
DOM.Events.add('change', button, (event) => {
const files = event.target.files;
Upload.hide();
DOM.uploadFiles(files);
});
}
init();
}

View file

@ -1,408 +1,407 @@
/* global itype */ 'use strict';
var CloudCmd, Util, DOM, CloudFunc, $, exec; /* global CloudCmd, Util, DOM, CloudFunc, $ */
(function(CloudCmd, Util, DOM, CloudFunc) { const itype = require('itype/legacy');
'use strict'; const rendy = require('rendy');
const exec = require('execon');
CloudCmd.View = ViewProto;
function ViewProto(CallBack) {
var Name = 'View',
Loading = false,
Events = DOM.Events,
Info = DOM.CurrentInfo,
Key = CloudCmd.Key,
Images = DOM.Images,
View = exec.bind(Util),
Element, TemplateAudio, Overlay;
/* global rendy */ const Config = {
beforeShow: (callback) => {
Images.hide();
Key.unsetBind();
showOverlay();
exec(callback);
},
beforeClose: (callback) => {
Key.setBind();
exec(callback);
hideOverlay();
},
afterShow: (callback) => {
Element.focus();
exec(callback);
},
afterClose: (callback) => {
exec(callback);
},
fitToView : true,
loop : false,
openEffect : 'none',
closeEffect : 'none',
autoSize : false,
height : '100%',
width : '100%',
minWidth : 0,
minHeight : 0,
padding : 0,
preload : 0,
keys : null,
mouseWheel : false,
arrows : false,
helpers : {
overlay : null,
title : null
}
};
CloudCmd.View = ViewProto; View.show = show;
View.hide = hide;
function ViewProto(CallBack) { function init() {
var Name = 'View', var func = CallBack || exec.with(show, null);
Loading = false,
Events = DOM.Events,
Info = DOM.CurrentInfo,
Key = CloudCmd.Key,
Images = DOM.Images,
View = exec.bind(Util),
Element, TemplateAudio, Overlay,
Config = {
beforeShow : function(callback) {
Images.hide();
Key.unsetBind();
showOverlay();
exec(callback);
},
beforeClose : function(callback) {
Key.setBind();
exec(callback);
hideOverlay();
},
afterShow : function(callback) {
Element.focus();
exec(callback);
},
afterClose : function(callback) {
exec(callback);
},
fitToView : true,
loop : false,
openEffect : 'none',
closeEffect : 'none',
autoSize : false,
height : '100%',
width : '100%',
minWidth : 0,
minHeight : 0,
padding : 0,
preload : 0,
keys : null,
mouseWheel : false,
arrows : false,
helpers : {
overlay : null,
title : null
}
};
View.show = show; Loading = true;
View.hide = hide;
function init() { exec.series([
var func = CallBack || exec.with(show, null); DOM.loadJquery,
load,
Loading = true; function(callback) {
Loading = false;
exec.series([ exec(callback);
DOM.loadJquery,
load,
function(callback) {
Loading = false;
exec(callback);
}
], func);
Config.parent = Overlay = DOM.load({
id : 'js-view',
name : 'div',
className : 'fancybox-overlay fancybox-overlay-fixed'
});
['click', 'contextmenu'].forEach(function(name) {
Events.add(name, Overlay, onOverLayClick);
});
Events.addKey(listener);
}
/**
* function shows FancyBox
*/
function show(data, options) {
var path, element, type;
var prefixUrl = CloudCmd.PREFIX_URL + CloudFunc.FS;
if (Loading)
return;
Element = $('<div class="view" tabindex=0>');
if (data) {
element = $(Element).append(data);
var config = initConfig(Config, options);
$.fancybox(element, config);
} else {
Images.show.load();
path = prefixUrl + Info.path;
type = getType(path);
switch(type) {
default:
Info.getData(function(error, data) {
if (error)
return Images.hide();
var element = document.createTextNode(data);
/* add margin only for view text documents */
Element.css('margin', '2%');
$.fancybox(Element.append(element), Config);
});
break;
case 'image':
showImage(path, prefixUrl);
break;
case 'media':
getMediaElement(path, function(element) {
var media = DOM.getByDataName('js-media', element);
var onKey = exec.with(onMediaKey, media);
$.fancybox.open(element, {
parent : Overlay,
beforeShow : function() {
Config.beforeShow();
Events.addKey(onKey);
},
beforeClose : function() {
Config.beforeClose();
Events.rmKey(onKey);
},
afterShow: function() {
element
.querySelector('audio, video')
.focus();
},
helpers: {
overlay : null,
title : null
}
});
});
break;
}
} }
} ], func);
function initConfig(Config, options) { Config.parent = Overlay = DOM.load({
var config = {}; id : 'js-view',
name : 'div',
Util.copyObj(config, Config); className : 'fancybox-overlay fancybox-overlay-fixed'
});
if (!options)
return config;
Object.keys(options).forEach(function(name) {
var isConfig = !!config[name];
var item = options[name];
var isFunc = itype.function(item);
if (!isFunc || !isConfig) {
config[name] = options[name];
} else {
var func = config[name];
config[name] = function() {
exec.series([func, item]);
};
}
});
return config;
}
function hide() { ['click', 'contextmenu'].forEach(function(name) {
$.fancybox.close(); Events.add(name, Overlay, onOverLayClick);
} });
function showImage(path, prefixUrl) { Events.addKey(listener);
var config,
current = Info.name,
files = [].slice.call(Info.files),
names = files
.filter(function(file) {
var name = DOM.getCurrentName(file);
return isImage(name);
})
.filter(function(file) {
var name = DOM.getCurrentName(file);
return name !== current;
}).map(function(file) {
var path = DOM.getCurrentPath(file),
name = DOM.getCurrentName(file);
return {
href: prefixUrl + path,
title: name
};
});
names.unshift({
href: path,
title: current
});
config = Util.copyObj({
}, Config);
config = Util.copyObj(config, {
autoSize : true,
type : 'image',
prevEffect : 'none',
nextEffect : 'none',
arrows : true,
keys : true,
helpers : {
overlay : null,
title : {}
}
});
$.fancybox.open(names, config);
}
function isImage(name) {
var isMatch;
isMatch = [
'jp(e|g|eg)',
'gif',
'png',
'bmp',
'webp',
'svg',
'ico'
].some(function(ext) {
var reg = RegExp('\\.' + ext + '$', 'i');
return reg.test(name);
});
return isMatch;
}
function isMedia(name) {
var isMatch;
isMatch = isAudio(name) || isVideo(name);
return isMatch;
}
function isAudio(name) {
return /\.(mp3|ogg|m4a)$/i.test(name);
}
function isVideo(name) {
return /\.(mp4|avi)$/i.test(name);
}
function getType(name) {
var type;
if (isImage(name))
type = 'image';
else if (isMedia(name))
type = 'media';
return type;
}
function getMediaElement(src, callback) {
check(src, callback);
DOM.Files.get('view/media-tmpl', function(error, template) {
var rendered, element, type, is,
name = Info.name;
if (error) {
alert(error);
} else {
if (!TemplateAudio)
TemplateAudio = template;
is = isAudio(name);
type = is ? 'audio' : 'video';
rendered = rendy(TemplateAudio, {
src : src,
type: type,
name: Info.name
});
element = $(rendered)[0];
callback(element);
}
});
}
function check(src, callback) {
if (typeof src !== 'string')
throw Error('src should be a string!');
if (typeof callback !== 'function')
throw Error('callback should be a function');
}
function onMediaKey(media, event) {
var key = event.keyCode;
if (key === Key.SPACE) {
if (media.paused)
media.play();
else
media.pause();
}
}
/**
* function loads css and js of FancyBox
* @callback - executes, when everything loaded
*/
function load(callback) {
Util.time(Name + ' load');
DOM.loadRemote('fancybox', function() {
var prefix = CloudCmd.PREFIX;
DOM.load.css(prefix + '/css/view.css', callback);
DOM.load.style({
id : 'view-inlince-css',
inner : [
'.fancybox-title-float-wrap .child {',
'-webkit-border-radius: 0;',
'-moz-border-radius: 0;',
'border-radius: 0;',
'}'
].join('')
});
});
}
function onOverLayClick(event) {
var isCurrent, isFiles, isFilesPassive,
files = Info.files,
filesPassive = Info.filesPassive,
element = event.target,
isOverlay = element === Overlay,
position = {
x: event.clientX,
y: event.clientY
};
if (isOverlay) {
hideOverlay();
element = DOM.getCurrentByPosition(position);
if (element) {
isFiles = ~files.indexOf(element);
isFilesPassive = ~filesPassive.indexOf(element);
if (isFiles || isFilesPassive) {
isCurrent = DOM.isCurrentFile(element);
if (!isCurrent)
DOM.setCurrentFile(element);
}
}
View.hide();
}
}
function hideOverlay() {
Overlay.classList.remove('view-overlay');
}
function showOverlay() {
Overlay.classList.add('view-overlay');
}
function listener(event) {
var keyCode = event.keyCode,
ESC = Key.ESC;
if (keyCode === ESC)
hide();
}
init();
return View;
} }
/**
* function shows FancyBox
*/
function show(data, options) {
var path, element, type;
var prefixUrl = CloudCmd.PREFIX_URL + CloudFunc.FS;
if (Loading)
return;
Element = $('<div class="view" tabindex=0>');
if (data) {
element = $(Element).append(data);
var config = initConfig(Config, options);
$.fancybox(element, config);
} else {
Images.show.load();
path = prefixUrl + Info.path;
type = getType(path);
switch(type) {
default:
Info.getData(function(error, data) {
if (error)
return Images.hide();
var element = document.createTextNode(data);
/* add margin only for view text documents */
Element.css('margin', '2%');
$.fancybox(Element.append(element), Config);
});
break;
case 'image':
showImage(path, prefixUrl);
break;
case 'media':
getMediaElement(path, function(element) {
var media = DOM.getByDataName('js-media', element);
var onKey = exec.with(onMediaKey, media);
$.fancybox.open(element, {
parent : Overlay,
beforeShow : function() {
Config.beforeShow();
Events.addKey(onKey);
},
beforeClose : function() {
Config.beforeClose();
Events.rmKey(onKey);
},
afterShow: function() {
element
.querySelector('audio, video')
.focus();
},
helpers: {
overlay : null,
title : null
}
});
});
break;
}
}
}
function initConfig(Config, options) {
var config = {};
Util.copyObj(config, Config);
if (!options)
return config;
Object.keys(options).forEach(function(name) {
var isConfig = !!config[name];
var item = options[name];
var isFunc = itype.function(item);
if (!isFunc || !isConfig) {
config[name] = options[name];
} else {
var func = config[name];
config[name] = function() {
exec.series([func, item]);
};
}
});
return config;
}
function hide() {
$.fancybox.close();
}
function showImage(path, prefixUrl) {
var config,
current = Info.name,
files = [].slice.call(Info.files),
names = files
.filter(function(file) {
var name = DOM.getCurrentName(file);
return isImage(name);
})
.filter(function(file) {
var name = DOM.getCurrentName(file);
return name !== current;
}).map(function(file) {
var path = DOM.getCurrentPath(file),
name = DOM.getCurrentName(file);
return {
href: prefixUrl + path,
title: name
};
});
names.unshift({
href: path,
title: current
});
config = Util.copyObj({
}, Config);
config = Util.copyObj(config, {
autoSize : true,
type : 'image',
prevEffect : 'none',
nextEffect : 'none',
arrows : true,
keys : true,
helpers : {
overlay : null,
title : {}
}
});
$.fancybox.open(names, config);
}
function isImage(name) {
var isMatch;
isMatch = [
'jp(e|g|eg)',
'gif',
'png',
'bmp',
'webp',
'svg',
'ico'
].some(function(ext) {
var reg = RegExp('\\.' + ext + '$', 'i');
return reg.test(name);
});
return isMatch;
}
function isMedia(name) {
var isMatch;
isMatch = isAudio(name) || isVideo(name);
return isMatch;
}
function isAudio(name) {
return /\.(mp3|ogg|m4a)$/i.test(name);
}
function isVideo(name) {
return /\.(mp4|avi)$/i.test(name);
}
function getType(name) {
var type;
if (isImage(name))
type = 'image';
else if (isMedia(name))
type = 'media';
return type;
}
function getMediaElement(src, callback) {
check(src, callback);
DOM.Files.get('view/media-tmpl', function(error, template) {
var rendered, element, type, is,
name = Info.name;
if (error) {
alert(error);
} else {
if (!TemplateAudio)
TemplateAudio = template;
is = isAudio(name);
type = is ? 'audio' : 'video';
rendered = rendy(TemplateAudio, {
src : src,
type: type,
name: Info.name
});
element = $(rendered)[0];
callback(element);
}
});
}
function check(src, callback) {
if (typeof src !== 'string')
throw Error('src should be a string!');
if (typeof callback !== 'function')
throw Error('callback should be a function');
}
function onMediaKey(media, event) {
var key = event.keyCode;
if (key === Key.SPACE) {
if (media.paused)
media.play();
else
media.pause();
}
}
/**
* function loads css and js of FancyBox
* @callback - executes, when everything loaded
*/
function load(callback) {
Util.time(Name + ' load');
DOM.loadRemote('fancybox', function() {
var prefix = CloudCmd.PREFIX;
DOM.load.css(prefix + '/css/view.css', callback);
DOM.load.style({
id : 'view-inlince-css',
inner : [
'.fancybox-title-float-wrap .child {',
'-webkit-border-radius: 0;',
'-moz-border-radius: 0;',
'border-radius: 0;',
'}'
].join('')
});
});
}
function onOverLayClick(event) {
var isCurrent, isFiles, isFilesPassive,
files = Info.files,
filesPassive = Info.filesPassive,
element = event.target,
isOverlay = element === Overlay,
position = {
x: event.clientX,
y: event.clientY
};
if (isOverlay) {
hideOverlay();
element = DOM.getCurrentByPosition(position);
if (element) {
isFiles = ~files.indexOf(element);
isFilesPassive = ~filesPassive.indexOf(element);
if (isFiles || isFilesPassive) {
isCurrent = DOM.isCurrentFile(element);
if (!isCurrent)
DOM.setCurrentFile(element);
}
}
View.hide();
}
}
function hideOverlay() {
Overlay.classList.remove('view-overlay');
}
function showOverlay() {
Overlay.classList.add('view-overlay');
}
function listener(event) {
var keyCode = event.keyCode,
ESC = Key.ESC;
if (keyCode === ESC)
hide();
}
init();
return View;
}
})(CloudCmd, Util, DOM, CloudFunc);

View file

@ -1,252 +1,239 @@
(function(scope) { 'use strict';
'use strict';
const exec = require('execon');
const rendy = require('rendy');
const jonny = require('jonny');
module.exports = new UtilProto(exec);
function UtilProto(exec) {
const Util = this;
const Scope = global || window;
var exec; this.getStrBigFirst = getStrBigFirst;
var rendy; this.kebabToCamelCase = kebabToCamelCase;
var jonny;
var Scope = scope.window ? window : global;
if (typeof module === 'object' && module.exports) { /**
exec = require('execon'); * Copy properties from from to to
rendy = require('rendy'); *
jonny = require('jonny'); * @param from
module.exports = new UtilProto(exec); * @param to
} else if (!Scope.Util) { */
exec = window.exec; this.copyObj = function(to, from) {
rendy = window.rendy; if (!from) {
jonny = window.jonny; from = to;
Scope.Util = new UtilProto(exec); to = {};
}
function UtilProto(exec) {
var Util = this;
this.getStrBigFirst = getStrBigFirst;
this.kebabToCamelCase = kebabToCamelCase;
/**
* Copy properties from from to to
*
* @param from
* @param to
*/
this.copyObj = function(to, from) {
if (!from) {
from = to;
to = {};
}
if (to)
Object.keys(from).forEach(function(name) {
to[name] = from[name];
});
return to;
};
/**
* copy objFrom properties to target
*
* @target
* @objFrom
*/
this.extend = function(target, objFrom) {
var obj;
var keys;
var proto;
var isFunc = typeof objFrom === 'function';
var isArray = Array.isArray(objFrom);
var isObj = typeof target === 'object';
var ret = isObj ? target : {};
if (isArray)
objFrom.forEach(function(item) {
ret = Util.extend(target, item);
});
else if (objFrom) {
obj = isFunc ? new objFrom() : objFrom;
keys = Object.keys(obj);
if (!keys.length) {
proto = Object.getPrototypeOf(objFrom);
keys = Object.keys(proto);
}
keys.forEach(function(name) {
ret[name] = obj[name];
});
}
return ret;
};
/**
* extend proto
*
* @obj
*/
this.extendProto = function(obj) {
var ret, F = function() {};
F.prototype = Util.extend({}, obj);
ret = new F();
return ret;
};
this.json = jonny;
this.escapeRegExp = function(str) {
var isStr = typeof str === 'string';
if (isStr)
str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
return str;
};
/**
* get regexp from wild card
*/
this.getRegExp = function(wildcard) {
var regExp;
if (!wildcard)
wildcard = '*';
wildcard = '^' + wildcard /* search from start of line */
.replace('.', '\\.')
.replace('*', '.*')
.replace('?', '.?');
wildcard += '$'; /* search to end of line */
regExp = new RegExp(wildcard);
return regExp;
};
this.exec = exec;
/**
* function gets file extension
*
* @param pFileName
* @return Ext
*/
this.getExt = function(name) {
var ret = '';
var dot;
var isStr = typeof name === 'string'
if (isStr) {
dot = name.lastIndexOf('.');
if (~dot)
ret = name.substr(dot);
}
return ret;
};
/**
* get values from Object Array name properties
* or
* @pObj
*/
this.getNamesFromObjArray = function(arr) {
var ret = [];
if (!Array.isArray(arr))
throw Error('arr should be array!');
ret = arr.map(function(item) {
return item.name;
});
return ret;
};
/**
* find object by name in arrray
*
* @param array
* @param name
*/
this.findObjByNameInArr = function(array, name) {
var ret;
if (!Array.isArray(array))
throw Error('array should be array!');
if (typeof name !== 'string')
throw Error('name should be string!');
array.some(function(item) {
var is = item.name === name,
isArray = Array.isArray(item);
if (is)
ret = item;
else if (isArray)
item.some(function(item) {
is = item.name === name;
if (is)
ret = item.data;
return is;
});
return is;
});
return ret;
};
/**
* start timer
* @param name
*/
this.time = function(name) {
var console = Scope.console;
Util.exec.ifExist(console, 'time', [name]);
return this;
};
/**
* stop timer
* @param name
*/
this.timeEnd = function(name) {
var console = Scope.console;
Util.exec.ifExist(console, 'timeEnd', [name]);
return this;
};
function getStrBigFirst(str) {
if (!str)
throw Error('str could not be empty!');
var first = str[0].toUpperCase();
return first + str.slice(1);
} }
function kebabToCamelCase(str) { if (to)
if (!str) Object.keys(from).forEach(function(name) {
throw Error('str could not be empty!'); to[name] = from[name];
});
return to;
};
/**
* copy objFrom properties to target
*
* @target
* @objFrom
*/
this.extend = function(target, objFrom) {
var obj;
var keys;
var proto;
var isFunc = typeof objFrom === 'function';
var isArray = Array.isArray(objFrom);
var isObj = typeof target === 'object';
var ret = isObj ? target : {};
if (isArray)
objFrom.forEach(function(item) {
ret = Util.extend(target, item);
});
else if (objFrom) {
obj = isFunc ? new objFrom() : objFrom;
keys = Object.keys(obj);
return str if (!keys.length) {
.split('-') proto = Object.getPrototypeOf(objFrom);
.map(getStrBigFirst) keys = Object.keys(proto);
.join('') }
.replace(/.js$/, '');
keys.forEach(function(name) {
ret[name] = obj[name];
});
} }
return ret;
};
/**
* extend proto
*
* @obj
*/
this.extendProto = function(obj) {
var ret, F = function() {};
F.prototype = Util.extend({}, obj);
ret = new F();
return ret;
};
this.json = jonny;
this.escapeRegExp = function(str) {
var isStr = typeof str === 'string';
if (isStr)
str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
return str;
};
/**
* get regexp from wild card
*/
this.getRegExp = function(wildcard) {
var regExp;
if (!wildcard)
wildcard = '*';
wildcard = '^' + wildcard /* search from start of line */
.replace('.', '\\.')
.replace('*', '.*')
.replace('?', '.?');
wildcard += '$'; /* search to end of line */
regExp = new RegExp(wildcard);
return regExp;
};
this.exec = exec;
/**
* function gets file extension
*
* @param pFileName
* @return Ext
*/
this.getExt = function(name) {
var ret = '';
var dot;
var isStr = typeof name === 'string'
if (isStr) {
dot = name.lastIndexOf('.');
if (~dot)
ret = name.substr(dot);
}
return ret;
};
/**
* get values from Object Array name properties
* or
* @pObj
*/
this.getNamesFromObjArray = function(arr) {
var ret = [];
if (!Array.isArray(arr))
throw Error('arr should be array!');
ret = arr.map(function(item) {
return item.name;
});
return ret;
};
/**
* find object by name in arrray
*
* @param array
* @param name
*/
this.findObjByNameInArr = function(array, name) {
var ret;
if (!Array.isArray(array))
throw Error('array should be array!');
if (typeof name !== 'string')
throw Error('name should be string!');
array.some(function(item) {
var is = item.name === name,
isArray = Array.isArray(item);
if (is)
ret = item;
else if (isArray)
item.some(function(item) {
is = item.name === name;
if (is)
ret = item.data;
return is;
});
return is;
});
return ret;
};
/**
* start timer
* @param name
*/
this.time = function(name) {
const console = Scope.console;
Util.exec.ifExist(console, 'time', [name]);
return this;
};
/**
* stop timer
* @param name
*/
this.timeEnd = function(name) {
var console = Scope.console;
Util.exec.ifExist(console, 'timeEnd', [name]);
return this;
};
function getStrBigFirst(str) {
if (!str)
throw Error('str could not be empty!');
var first = str[0].toUpperCase();
return first + str.slice(1);
} }
})(this); function kebabToCamelCase(str) {
if (!str)
throw Error('str could not be empty!');
return str
.split('-')
.map(getStrBigFirst)
.join('')
.replace(/.js$/, '');
}
}

View file

@ -1,32 +0,0 @@
{
"name": "currify",
"description": "translate the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single or more arguments",
"homepage": "https://github.com/coderaiser/currify",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"main": "lib/currify.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"curry",
"functional"
],
"license": "MIT",
"ignore": [
"**/.*",
"test"
],
"version": "2.0.3",
"_release": "2.0.3",
"_resolution": {
"type": "version",
"tag": "v2.0.3",
"commit": "be9ab0b0f7b8e685da89321df384ac902fa3c587"
},
"_source": "https://github.com/coderaiser/currify.git",
"_target": "2.0.3",
"_originalSource": "currify"
}

View file

@ -1,34 +0,0 @@
2016.12.05, v2.0.3
fix:
- (currify) bundle: empty currify in dist
2016.11.23, v2.0.2
fix:
- (currify) when to much function.length use default
2016.11.23, v2.0.1
fix:
- (currify) add support of 4 and 5 arguments
2016.11.23, v2.0.0
feature:
- (travis) node_js: v6, v7
- (currify) fn.length in curried functions
- (package) scripts: coverage
- (gitignore) *.swp
- (currify) es2015-ify
- (package) redrun v5.0.0
- (package) redrun v4.0.0
- (package) npm-run-all -> redrun
- (package) jscs v3.0.3
- (license) add
- (gitignore) npm-debug.log -> npm-debug.log*
- (package) browserify v13.0.0

View file

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

View file

@ -1,48 +0,0 @@
# Currify [![License][LicenseIMGURL]][LicenseURL] [![NPM version][NPMIMGURL]][NPMURL] [![Dependency Status][DependencyStatusIMGURL]][DependencyStatusURL] [![Build Status][BuildStatusIMGURL]][BuildStatusURL]
Translate the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single or more arguments.
## Install
```
npm i currify --save
```
## How to use?
```js
const currify = require('currify');
const mean = (a, b, c) => (a + b) / c;
const mean1 = currify(mean, 1);
const mean2 = mean1(2);
mean2(2);
// returns
1.5
```
## Environments
In old `node.js` environments that not fully supports `es2015`, `currify` could be used with:
```js
var currify = require('currify/legacy');
```
## Related
- [zames](https://github.com/coderaiser/zames "zames") - converts callback-based functions to Promises and apply currying to arguments
## License
MIT
[NPMIMGURL]: https://img.shields.io/npm/v/currify.svg?style=flat
[BuildStatusIMGURL]: https://img.shields.io/travis/coderaiser/currify/master.svg?style=flat
[DependencyStatusIMGURL]: https://img.shields.io/gemnasium/coderaiser/currify.svg?style=flat
[LicenseIMGURL]: https://img.shields.io/badge/license-MIT-317BF9.svg?style=flat
[NPMURL]: https://npmjs.org/package/currify "npm"
[BuildStatusURL]: https://travis-ci.org/coderaiser/currify "Build Status"
[DependencyStatusURL]: https://gemnasium.com/coderaiser/currify "Dependency Status"
[LicenseURL]: https://tldrlegal.com/license/mit-license "MIT License"

View file

@ -1,22 +0,0 @@
{
"name": "currify",
"description": "translate the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single or more arguments",
"homepage": "https://github.com/coderaiser/currify",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"main": "lib/currify.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"curry",
"functional"
],
"license": "MIT",
"ignore": [
"**/.*",
"test"
]
}

View file

@ -1 +0,0 @@
!function(r){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=r();else if("function"==typeof define&&define.amd)define([],r);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.currify=r()}}(function(){return function r(n,e,t){function o(f,u){if(!e[f]){if(!n[f]){var c="function"==typeof require&&require;if(!u&&c)return c(f,!0);if(i)return i(f,!0);var l=new Error("Cannot find module '"+f+"'");throw l.code="MODULE_NOT_FOUND",l}var p=e[f]={exports:{}};n[f][0].call(p.exports,function(r){var e=n[f][1][r];return o(e?e:r)},p,p.exports,r,n,e,t)}return e[f].exports}for(var i="function"==typeof require&&require,f=0;f<t.length;f++)o(t[f]);return o}({currify:[function(r,n,e){"use strict";function t(r){if(Array.isArray(r)){for(var n=0,e=Array(r.length);n<r.length;n++)e[n]=r[n];return e}return Array.from(r)}function o(r){if("function"!=typeof r)throw Error("fn should be function!")}var i=function(r){return[].slice.call(r,1)},f=function(r){return[function(n){return r.apply(void 0,arguments)},function(n,e){return r.apply(void 0,arguments)},function(n,e,t){return r.apply(void 0,arguments)},function(n,e,t,o){return r.apply(void 0,arguments)},function(n,e,t,o,i){return r.apply(void 0,arguments)}]};n.exports=function r(n){o(n);var e=i(arguments);if(e.length>=n.length)return n.apply(void 0,t(e));var u=function(){return r.apply(void 0,[n].concat(t(e),Array.prototype.slice.call(arguments)))},c=n.length-arguments.length,l=f(u)[c];return l||u}},{}]},{},["currify"])("currify")});

View file

@ -1,44 +0,0 @@
'use strict';
const tail = list => [].slice.call(list, 1);
const f = (fn) => [
function(a) {
return fn(...arguments);
},
function(a, b) {
return fn(...arguments);
},
function(a, b, c) {
return fn(...arguments);
},
function(a, b, c, d) {
return fn(...arguments);
},
function(a, b, c, d, e) {
return fn(...arguments);
}
];
module.exports = function currify(fn) {
check(fn);
const args = tail(arguments);
if (args.length >= fn.length)
return fn(...args);
const again = function() {
return currify(...[fn, ...args, ...arguments]);
};
const count = fn.length - arguments.length;
const func = f(again)[count];
return func || again;
}
function check(fn) {
if (typeof fn !== 'function')
throw Error('fn should be function!');
}

View file

@ -1,53 +0,0 @@
{
"name": "currify",
"version": "2.0.3",
"description": "translate the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single or more arguments",
"main": "lib/currify.js",
"scripts": {
"test": "tape test/*.js",
"coverage": "nyc npm test",
"lint": "eslint lib test",
"build": "redrun clean 6to5 legacy:* bundle bundle minify",
"minify": "minify dist/currify.js > dist/currify.min.js",
"6to5": "babel -d legacy/lib lib",
"wisdom": "npm run build",
"clean": "rimraf dist/* legacy/*",
"bundle:base": "browserify -s currify --ng false",
"bundle": "npm run bundle:base -- -r ./legacy/lib/currify.js:currify ./legacy/lib/currify.js -o dist/currify.js",
"watcher": "nodemon -w test -w lib --exec",
"watch:test": "npm run watcher -- npm test",
"watch:lint": "npm run watcher -- 'npm run lint'",
"watch:tape": "nodemon -w test -w lib --exec tape",
"watch:coverage:base": "npm run watcher -- nyc npm test",
"watch:coverage:tape": "npm run watcher -- nyc tape",
"watch:coverage": "bin/redrun.js watch:coverage:base",
"legacy:index": "echo \"module.exports = require('./lib/currify');\" > legacy/index.js"
},
"repository": {
"type": "git",
"url": "git://github.com/coderaiser/currify.git"
},
"keywords": [
"currify",
"partial",
"functional"
],
"author": "coderaiser <mnemonic.enemy@gmail.com> (http://coderaiser.github.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/coderaiser/currify/issues"
},
"homepage": "https://github.com/coderaiser/currify",
"devDependencies": {
"babel-cli": "^6.1.1",
"babel-preset-es2015": "^6.0.15",
"browserify": "^13.0.0",
"eslint": "^3.10.2",
"minify": "^2.0.13",
"nodemon": "^1.11.0",
"nyc": "^10.0.0",
"redrun": "^5.0.1",
"rimraf": "^2.4.3",
"tape": "^4.2.0"
}
}

View file

@ -1,34 +0,0 @@
{
"name": "execon",
"version": "1.2.9",
"homepage": "https://github.com/coderaiser/execon",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "Patterns of function calls",
"main": "lib/exec.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"exec"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"_release": "1.2.9",
"_resolution": {
"type": "version",
"tag": "v1.2.9",
"commit": "b71d2c60651f957486301e10462aab80a0f62ee1"
},
"_source": "git://github.com/coderaiser/execon.git",
"_target": "~1.2.8",
"_originalSource": "execon"
}

View file

@ -1,86 +0,0 @@
2015.10.23, v1.2.9
fix:
- (exec) parallel throw: add " "
2015.10.21, v1.2.8
fix:
- (exec) with do not return value
feature:
- (travis) add
- (gitignore) add
2015.10.01, v1.2.7
fix:
- (exec) with: concat arguments
2015.10.01, v1.2.6
feature:
- (exec) with: bind.apply -> function apply
2015.07.21, v1.2.5
fix:
- (exec) eachSeries
2015.07.21, v1.2.4
fix:
- (exec) each, eachSeries
2015.07.21, v1.2.3
fix:
- (exec) each, eachSeries: call callback when !listeners.length
2015.06.05, v1.2.2
feature:
- (exec) with: callback.bind -> bind.apply
2015.06.05, v1.2.1
feature:
- (exec) exec.with: arguments[0] -> slice.call(arguments)
2015.06.03, v1.2.0
feature:
- (exec) add each, eachSeries
- (exec) series: rm getType call
2015.01.28, v1.1.1
feature:
- (exec) scope -> global
- (bower) add
- (package) node-execon -> execon
- (package) v1.1.0
- (execon) series: add callback
2015.01.15, v1.1.0
feature:
- (execon) series: add callback
2014.11.24, v1.0.1
fix:
- (package) check -> exec

View file

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

View file

@ -1,154 +0,0 @@
# Execon [![License][LicenseIMGURL]][LicenseURL] [![NPM version][NPMIMGURL]][NPMURL] [![Dependency Status][DependencyStatusIMGURL]][DependencyStatusURL] [![BuildStatusIMGURL]][BuildStatusURL]
Patterns of function calls.
## Install
![NPM_INFO][NPM_INFO_IMG]
```
npm i execon --save
# or
bower i execon --save
```
## Api
```js
var exec = require('execon');
```
### exec
Check is parameter is function, if it's - executes it with given parameters
Was:
```js
function(callback, p1, p2, pN) {
if (typeof callback === 'function')
callback(p1, p2, pN);
}
```
Now
```js
function(callback, p1, p2, pN) {
exec(callback, p1, p2, pN);
}
```
or just
```js
exec.ret(callback, p1, p2, pN);
```
### exec.if
Conditional execution one of two functions
Preconditions:
```js
function one() {
console.log(1);
}
function two(callback) {
setTimeout(callback, 1000);
}
```
Before:
```js
if (2 > 3)
one();
else
two(one);
```
After:
```js
exec.if(2 > 3, one, two);
```
### exec.parallel
if a you need a couple async operation do same work, and then call callback, this function for you.
**Node.js example**.
```js
var fs = require('fs'),
Util = require('execon');
exec.parallel([
function(callback) {
fs.readFile('file1', callback);
},
function(callback) {
fs.readFile('file2', callback);
}
], function(error, data1, data2) {
if (error)
console.log(error)
else
console.log(data1, data2);
});
```
**Vanilla js example.**
```js
var ONE_SECOND = 1000,
TWO_SECONDS = 2000,
func = function(time, str, callback) {
setTimeout(function() {
console.log(str);
callback(null, str);
}, time);
},
func1 = func.bind(null, TWO_SECONDS, 'first'),
func2 = func.bind(null, ONE_SECOND, 'second');
exec.parallel([func1, func2], function(error, str1, str2) {
console.log(str1, str2);
});
```
### exec.series
executes functions one-by-one
```js
function one(callback){
setTimeout(function() {
console.log(1)
callback();
}, 1000);
}
function two(callback) {
console.log(2);
callback();
}
exec.series([one, two], function(error) {
console.log(error || 'done');
});
```
## License
MIT
[NPM_INFO_IMG]: https://nodei.co/npm/execon.png?downloads=true&&stars&&downloadRank "npm install rendy"
[NPMIMGURL]: https://img.shields.io/npm/v/execon.svg?style=flat
[DependencyStatusIMGURL]: https://img.shields.io/gemnasium/coderaiser/execon.svg?style=flat
[LicenseIMGURL]: https://img.shields.io/badge/license-MIT-317BF9.svg?style=flat
[NPMURL]: https://npmjs.org/package/execon "npm"
[BuildStatusURL]: https://travis-ci.org/coderaiser/execon "Build Status"
[DependencyStatusURL]: https://gemnasium.com/coderaiser/execon "Dependency Status"
[LicenseURL]: https://tldrlegal.com/license/mit-license "MIT License"
[BuildStatusIMGURL]: https://img.shields.io/travis/coderaiser/execon/master.svg?style=flat
[BuildStatusURL]: https://travis-ci.org/coderaiser/execon "Build Status"

View file

@ -1,25 +0,0 @@
{
"name": "execon",
"version": "1.2.9",
"homepage": "https://github.com/coderaiser/execon",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "Patterns of function calls",
"main": "lib/exec.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"exec"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}

View file

@ -1,244 +0,0 @@
(function(global) {
'use strict';
if (typeof module === 'object' && module.exports)
module.exports = new ExecProto();
else
global.exec = new ExecProto();
function ExecProto() {
var slice = Array.prototype.slice,
/**
* function do save exec of function
* @param callback
* @param arg1
* ...
* @param argN
*/
exec = function(callback) {
var ret,
isFunc = typeof callback === 'function',
args = slice.call(arguments, 1);
if (isFunc)
ret = callback.apply(null, args);
return ret;
};
/*
* return function that calls callback with arguments
*/
exec.with = function(callback) {
var slice = Array.prototype.slice,
args = slice.call(arguments, 1);
return function() {
var array = slice.call(arguments),
all = args.concat(array);
return callback.apply(null, all);
};
};
/**
* return save exec function
* @param callback
*/
exec.ret = function() {
var result,
args = slice.call(arguments);
args.unshift(exec);
result = exec.with.apply(null, args);
return result;
};
/**
* function do conditional save exec of function
* @param condition
* @param callback
* @param func
*/
exec.if = function(condition, callback, func) {
var ret;
if (condition)
exec(callback);
else
exec(func, callback);
return ret;
};
/**
* exec function if it exist in object
*
* @param obj
* @param name
* @param arg
*/
exec.ifExist = function(obj, name, arg) {
var ret,
func = obj && obj[name];
if (func)
func = func.apply(obj, arg);
return ret;
};
exec.parallel = function(funcs, callback) {
var ERROR = 'could not be empty!',
keys = [],
callbackWas = false,
arr = [],
obj = {},
count = 0,
countFuncs = 0,
type = getType(funcs);
if (!funcs)
throw Error('funcs ' + ERROR);
if (!callback)
throw Error('callback ' + ERROR);
switch(type) {
case 'array':
countFuncs = funcs.length;
funcs.forEach(function(func, num) {
exec(func, function() {
checkFunc(num, arguments);
});
});
break;
case 'object':
keys = Object.keys(funcs);
countFuncs = keys.length;
keys.forEach(function(name) {
var func = funcs[name];
exec(func, function() {
checkFunc(name, arguments, obj);
});
});
break;
}
function checkFunc(num, data) {
var args = slice.call(data, 1),
isLast = false,
error = data[0],
length = args.length;
++count;
isLast = count === countFuncs;
if (!error)
if (length >= 2)
arr[num] = args;
else
arr[num] = args[0];
if (!callbackWas && (error || isLast)) {
callbackWas = true;
if (type === 'array')
callback.apply(null, [error].concat(arr));
else
callback(error, arr);
}
}
};
/**
* load functions thrue callbacks one-by-one
* @param funcs {Array} - array of functions
*/
exec.series = function(funcs, callback) {
var fn,
i = funcs.length,
check = function(error) {
var done;
--i;
if (!i || error) {
done = true;
exec(callback, error);
}
return done;
};
if (!Array.isArray(funcs))
throw Error('funcs should be array!');
fn = funcs.shift();
exec(fn, function(error) {
if (!check(error))
exec.series(funcs, callback);
});
};
exec.each = function(array, iterator, callback) {
var listeners = array.map(function(item) {
return iterator.bind(null, item);
});
if (!listeners.length)
callback();
else
exec.parallel(listeners, callback);
};
exec.eachSeries = function(array, iterator, callback) {
var listeners = array.map(function(item) {
return iterator.bind(null, item);
});
if (typeof callback !== 'function')
throw Error('callback should be function');
if (!listeners.length)
callback();
else
exec.series(listeners, callback);
};
/**
* function execute param function in
* try...catch block
*
* @param callback
*/
exec.try = function(callback) {
var ret;
try {
ret = callback();
} catch(error) {
ret = error;
}
return ret;
};
function getType(variable) {
var regExp = new RegExp('\\s([a-zA-Z]+)'),
str = {}.toString.call(variable),
typeBig = str.match(regExp)[1],
result = typeBig.toLowerCase();
return result;
}
return exec;
}
})(this);

View file

@ -1,23 +0,0 @@
{
"name": "execon",
"version": "1.2.9",
"author": "coderaiser <mnemonic.enemy@gmail.com> (https://github.com/coderaiser)",
"description": "Patterns of function calls",
"homepage": "http://github.com/coderaiser/execon",
"scripts": {
"test": "tape test/*.js"
},
"repository": {
"type": "git",
"url": "git://github.com/coderaiser/execon.git"
},
"dependencies": {},
"license": "MIT",
"engines": {
"node": ">=0.8"
},
"main": "lib/exec.js",
"devDependencies": {
"tape": "~4.2.1"
}
}

View file

@ -1,36 +0,0 @@
{
"name": "format-io",
"version": "0.9.6",
"homepage": "https://github.com/coderaiser/format-io",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "Format size, permissions, etc",
"main": "lib/format.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"format",
"size",
"permissions"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"_release": "0.9.6",
"_resolution": {
"type": "version",
"tag": "v0.9.6",
"commit": "3381e500de22cc60a25a4049589c377198f8cc57"
},
"_source": "git://github.com/coderaiser/format-io.git",
"_target": "~0.9.6",
"_originalSource": "format-io"
}

View file

@ -1,6 +0,0 @@
2015.02.18, v0.9.6
feature:
- (bower) add
- (format) scope -> global

View file

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

View file

@ -1,49 +0,0 @@
# Format
Library for format size, permissions, etc.
# How to use?
Format could be used in browser or node.
In browser:
```js
<script src='lib/format.js'></script>
```
In node:
```js
var Format = require('format-io');
```
# API
## size
```js
var size = 1024 * 1024 * 5,
sizeStr = Format.size(size);
//'5.00mb'
```
## permissions.symbolic
```js
var perm = '00777',
permStr = Format.permissions.symbolic(perm);
//'rwx rwx rwx
```
## permissions.numeric
```js
var perm = 'rwx rwx rwx',
permNum = Format.permissions.numeric(perm);
//'00777'
```
# License
MIT

View file

@ -1,27 +0,0 @@
{
"name": "format-io",
"version": "0.9.6",
"homepage": "https://github.com/coderaiser/format-io",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "Format size, permissions, etc",
"main": "lib/format.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"format",
"size",
"permissions"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}

View file

@ -1,163 +0,0 @@
(function(global) {
'use strict';
if (typeof module === 'object' && module.exports)
module.exports = new FormatProto();
else
global.Format = new FormatProto();
function FormatProto() {
this.addSlashToEnd = function(path) {
var length, isSlash;
if (path) {
length = path.length - 1;
isSlash = path[length] === '/';
if (!isSlash)
path += '/';
}
return path;
};
/** Функция получает короткие размеры
* конвертируя байт в килобайты, мегабойты,
* гигайбайты и терабайты
* @pSize - размер в байтах
*/
this.size = function(size) {
var isNumber = typeof size === 'number',
l1KB = 1024,
l1MB = l1KB * l1KB,
l1GB = l1MB * l1KB,
l1TB = l1GB * l1KB,
l1PB = l1TB * l1KB;
if (isNumber) {
if (size < l1KB) size = size + 'b';
else if (size < l1MB) size = (size / l1KB).toFixed(2) + 'kb';
else if (size < l1GB) size = (size / l1MB).toFixed(2) + 'mb';
else if (size < l1TB) size = (size / l1GB).toFixed(2) + 'gb';
else if (size < l1PB) size = (size / l1TB).toFixed(2) + 'tb';
else size = (size / l1PB).toFixed(2) + 'pb';
}
return size;
};
/**
* Функция переводит права из цыфрового вида в символьный
* @param perms - строка с правами доступа
* к файлу в 8-миричной системе
*/
this.permissions = {
symbolic: function(perms) {
var type, owner, group, all,
is = typeof perms !== undefined,
permsStr = '',
permissions = '';
/*
S_IRUSR 0000400 protection: readable by owner
S_IWUSR 0000200 writable by owner
S_IXUSR 0000100 executable by owner
S_IRGRP 0000040 readable by group
S_IWGRP 0000020 writable by group
S_IXGRP 0000010 executable by group
S_IROTH 0000004 readable by all
S_IWOTH 0000002 writable by all
S_IXOTH 0000001 executable by all
*/
if (is) {
permsStr = perms.toString();
/* тип файла */
type = permsStr.charAt(0);
switch (type - 0) {
case 1: /* обычный файл */
type = '-';
break;
case 2: /* байт-ориентированное (символьное) устройство*/
type = 'c';
break;
case 4: /* каталог */
type = 'd';
break;
default:
type = '-';
}
/* оставляем последние 3 символа*/
if (permsStr.length > 5)
permsStr = permsStr.substr(3);
else
permsStr = permsStr.substr(2);
/* Рекомендации гугла советуют вместо string[3]
* использовать string.charAt(3)
*/
/*
http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Standards_features#Standards_features
Always preferred over non-standards featuresFor
maximum portability and compatibility, always
prefer standards features over non-standards
features (e.g., string.charAt(3) over string[3]
and element access with DOM functions instead
of using an application-specific shorthand).
*/
/* Переводим в двоичную систему */
owner = (permsStr[0] - 0).toString(2),
group = (permsStr[1] - 0).toString(2),
all = (permsStr[2] - 0).toString(2),
/* переводим в символьную систему*/
permissions =
(owner[0] - 0 > 0 ? 'r' : '-') +
(owner[1] - 0 > 0 ? 'w' : '-') +
(owner[2] - 0 > 0 ? 'x' : '-') +
' ' +
(group[0] - 0 > 0 ? 'r' : '-') +
(group[1] - 0 > 0 ? 'w' : '-') +
(group[2] - 0 > 0 ? 'x' : '-') +
' ' +
(all[0] - 0 > 0 ? 'r' : '-') +
(all[1] - 0 > 0 ? 'w' : '-') +
(all[2] - 0 > 0 ? 'x' : '-');
}
return permissions;
},
/**
* Функция конвертирует права доступа к файлам из символьного вида
* в цыфровой
*/
numeric: function(perms) {
var owner, group, all,
length = perms && perms.length === 11;
if (length) {
owner = (perms[0] === 'r' ? 4 : 0) +
(perms[1] === 'w' ? 2 : 0) +
(perms[2] === 'x' ? 1 : 0),
group = (perms[4] === 'r' ? 4 : 0) +
(perms[5] === 'w' ? 2 : 0) +
(perms[6] === 'x' ? 1 : 0),
all = (perms[8] === 'r' ? 4 : 0) +
(perms[9] === 'w' ? 2 : 0) +
(perms[10] === 'x' ? 1 : 0);
/* добавляем 2 цифры до 5 */
perms = '00' + owner + group + all;
}
return perms;
}
};
}
})(this);

View file

@ -1,22 +0,0 @@
{
"name": "format-io",
"version": "0.9.6",
"author": "coderaiser <mnemonic.enemy@gmail.com> (https://github.com/coderaiser)",
"description": "Format size, permissions, etc",
"homepage": "http://github.com/coderaiser/format-io",
"repository": {
"type": "git",
"url": "git://github.com/coderaiser/format-io.git"
},
"keywords": [
"format",
"size",
"permissions"
],
"dependencies": {},
"license": "MIT",
"engines": {
"node": ">=0.4.x"
},
"main": "lib/format.js"
}

View file

@ -1,35 +0,0 @@
{
"name": "itype",
"description": "Improved type check",
"main": "dist/itype.js",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com> (https://github.com/coderaiser)"
],
"license": "MIT",
"keywords": [
"type",
"string",
"array",
"object",
"boolean",
"null",
"undefined",
"check"
],
"homepage": "https://github.com/coderaiser/itype",
"ignore": [
".*",
"test",
"lib"
],
"version": "2.0.3",
"_release": "2.0.3",
"_resolution": {
"type": "version",
"tag": "v2.0.3",
"commit": "ec7f35bfdc6f9078d4e4792dd347bf98dd2f8ccc"
},
"_source": "https://github.com/coderaiser/itype.git",
"_target": "2.0.3",
"_originalSource": "itype"
}

View file

@ -1,35 +0,0 @@
2016.12.28, v2.0.3
fix:
- (bower) main
2016.12.28, v2.0.2
feature:
- (bower) ignore: add ".*"
2016.12.28, v2.0.1
feature:
- (bower) add
2016.12.28, v2.0.0
feature:
- (itype) add browser support
2015.01.30, v1.0.2
feature:
- (type) change format of regexp
2014.12.22, v1.0.1
feature:
- (itype) add null

View file

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

View file

@ -1,52 +0,0 @@
# iType [![License][LicenseIMGURL]][LicenseURL] [![NPM version][NPMIMGURL]][NPMURL] [![Dependency Status][DependencyStatusIMGURL]][DependencyStatusURL] [![Build Status][BuildStatusIMGURL]][BuildStatusURL] [![Coverage Status][CoverageIMGURL]][CoverageURL]
Improved type check.
## Install
```
npm i itype --save
```
## How to use?
```js
var itype = require('itype');
console.og(itype.string('hello'))
// returns
true
console.log(itype('world'));
// returns
'string'
console.log(itype.array([1, 2]));
// returns
true
```
## Environments
In old `node.js` environments that not fully supports `es2015`, `itype` could be used with:
```js
var itype = require('itype/legacy');
```
## License
MIT
[NPMIMGURL]: https://img.shields.io/npm/v/itype.svg?style=flat
[BuildStatusIMGURL]: https://img.shields.io/travis/coderaiser/itype/master.svg?style=flat
[DependencyStatusIMGURL]: https://img.shields.io/gemnasium/coderaiser/itype.svg?style=flat
[LicenseIMGURL]: https://img.shields.io/badge/license-MIT-317BF9.svg?style=flat
[NPMURL]: https://npmjs.org/package/itype "npm"
[BuildStatusURL]: https://travis-ci.org/coderaiser/itype "Build Status"
[DependencyStatusURL]: https://gemnasium.com/coderaiser/itype "Dependency Status"
[LicenseURL]: https://tldrlegal.com/license/mit-license "MIT License"
[CoverageURL]: https://coveralls.io/github/coderaiser/itype?branch=master
[CoverageIMGURL]: https://coveralls.io/repos/coderaiser/itype/badge.svg?branch=master&service=github

View file

@ -1,25 +0,0 @@
{
"name": "itype",
"description": "Improved type check",
"main": "dist/itype.js",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com> (https://github.com/coderaiser)"
],
"license": "MIT",
"keywords": [
"type",
"string",
"array",
"object",
"boolean",
"null",
"undefined",
"check"
],
"homepage": "https://github.com/coderaiser/itype",
"ignore": [
".*",
"test",
"lib"
]
}

View file

@ -1,49 +0,0 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.itype = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"itype":[function(require,module,exports){
'use strict';
module.exports = new TypeProto();
function TypeProto() {
/**
* get type of variable
*
* @param variable
*/
function type(variable) {
var regExp = /\s([a-zA-Z]+)/;
var str = {}.toString.call(variable);
var typeBig = str.match(regExp)[1];
var result = typeBig.toLowerCase();
return result;
}
/**
* functions check is variable is type of name
*
* @param variable
*/
function typeOf(name, variable) {
return type(variable) === name;
}
function typeOfSimple(name, variable) {
return typeof variable === name;
}
['arrayBuffer', 'file', 'array', 'object']
.forEach(function (name) {
type[name] = typeOf.bind(null, name);
});
['null', 'string', 'undefined', 'boolean', 'number', 'function']
.forEach(function (name) {
type[name] = typeOfSimple.bind(null, name);
});
return type;
}
},{}]},{},["itype"])("itype")
});

View file

@ -1 +0,0 @@
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.itype=e()}}(function(){return function e(n,r,t){function o(i,u){if(!r[i]){if(!n[i]){var c="function"==typeof require&&require;if(!u&&c)return c(i,!0);if(f)return f(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var a=r[i]={exports:{}};n[i][0].call(a.exports,function(e){var r=n[i][1][e];return o(r?r:e)},a,a.exports,e,n,r,t)}return r[i].exports}for(var f="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({itype:[function(e,n,r){"use strict";function t(){function e(e){var n=/\s([a-zA-Z]+)/,r={}.toString.call(e),t=r.match(n)[1],o=t.toLowerCase();return o}function n(n,r){return e(r)===n}function r(e,n){return typeof n===e}return["arrayBuffer","file","array","object"].forEach(function(r){e[r]=n.bind(null,r)}),["null","string","undefined","boolean","number","function"].forEach(function(n){e[n]=r.bind(null,n)}),e}n.exports=new t},{}]},{},["itype"])("itype")});

View file

@ -1,53 +0,0 @@
{
"name": "itype",
"version": "2.0.3",
"author": "coderaiser <mnemonic.enemy@gmail.com> (https://github.com/coderaiser)",
"description": "Improved type check",
"main": "lib/itype.js",
"repository": {
"type": "git",
"url": "git://github.com/coderaiser/itype.git"
},
"keywords": [
"type",
"string",
"array",
"object",
"boolean",
"null",
"undefined",
"check"
],
"scripts": {
"test": "tape test/*.js",
"watcher": "nodemon -w test -w lib --exec",
"watch:test": "npm run watcher -- npm test",
"watch:coverage": "npm run watcher -- npm run coverage",
"lint": "eslint lib test",
"build": "redrun clean init 6to5 legacy:* bundle minify",
"init": "mkdirp dist legacy",
"minify": "minify dist/itype.js > dist/itype.min.js",
"wisdom": "npm run build",
"clean": "rimraf legacy dist",
"bundle:base": "browserify -s itype --ng false",
"bundle": "npm run bundle:base -- -r ./legacy/lib/itype.js:itype ./legacy/lib/itype.js -o dist/itype.js",
"coverage": "nyc npm test",
"report": "nyc report --reporter=text-lcov | coveralls",
"6to5": "buble lib -o legacy/lib",
"legacy:index": "echo \"module.exports = require('./lib/itype');\" > legacy/index.js"
},
"dependencies": {},
"license": "MIT",
"devDependencies": {
"browserify": "^13.0.0",
"buble": "^0.15.1",
"coveralls": "^2.11.9",
"eslint": "^3.10.2",
"minify": "^2.0.5",
"mkdirp": "^0.5.1",
"nodemon": "^1.11.0",
"nyc": "^10.0.0",
"redrun": "^5.0.1",
"tape": "^4.5.1"
}
}

View file

@ -1,34 +0,0 @@
{
"name": "jonny",
"version": "1.0.1",
"homepage": "https://github.com/coderaiser/jonny",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "work with json without exaptions",
"main": "lib/jonny.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"json",
"try"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"modules"
],
"dependencies": {},
"_release": "1.0.1",
"_resolution": {
"type": "version",
"tag": "v1.0.1",
"commit": "b8909d33db868af9797c95881891c5d432209f1a"
},
"_source": "https://github.com/coderaiser/jonny.git",
"_target": "1.0.1",
"_originalSource": "jonny"
}

View file

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

View file

@ -1,26 +0,0 @@
# Jonny
Work with json without exeptions.
## Install
```
npm i jonny --save
```
## How to use?
```js
var jonny = require('jonny'),
obj = jonny.parse('{ "hello": "world" }');
console.log(jonny.stringify(obj, 0, 4));
// results
// "{
// "hello": "world"
// }"
```
## License
MIT

View file

@ -1,26 +0,0 @@
{
"name": "jonny",
"version": "1.0.0",
"homepage": "https://github.com/coderaiser/jonny",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "work with json without exaptions",
"main": "lib/jonny.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"json",
"try"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"modules"
],
"dependencies": {
}
}

View file

@ -1,45 +0,0 @@
(function(global) {
'use strict';
if (typeof module !== 'undefined' && module.exports)
module.exports = new Jonny();
else
global.jonny = new Jonny();
function Jonny() {
this.parse = function() {
var ret,
args = arguments;
tryCatch(function() {
ret = JSON.parse.apply(JSON, args);
});
return ret;
};
this.stringify = function() {
var ret,
args = arguments;
tryCatch(function() {
ret = JSON.stringify.apply(JSON, args);
});
return ret;
};
function tryCatch(fn) {
var error;
try {
fn();
} catch(e) {
error = e;
}
return error;
}
}
})(this);

View file

@ -1,27 +0,0 @@
{
"name": "jonny",
"version": "1.0.0",
"description": "work with json without exaptions",
"main": "lib/jonny.js",
"dependencies": {
"diff-match-patch": "~1.0.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git://github.com/coderaiser/jonny.git"
},
"keywords": [
"json",
"try"
],
"author": "coderaiser <mnemonic.enemy@gmail.com> (http://coderaiser.github.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/coderaiser/jonny/issues"
},
"homepage": "https://github.com/coderaiser/jonny"
}

View file

@ -1,35 +0,0 @@
{
"name": "rendy",
"version": "1.1.0",
"homepage": "https://github.com/coderaiser/rendy",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "simple template engine",
"main": "lib/rendy.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"template",
"engine",
"rendy"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"test"
],
"_release": "1.1.0",
"_resolution": {
"type": "version",
"tag": "v1.1.0",
"commit": "4ad810d131db34863df83977afea92b6fb2f1127"
},
"_source": "git://github.com/coderaiser/rendy.git",
"_target": "~1.1.0",
"_originalSource": "rendy",
"_direct": true
}

View file

@ -1,59 +0,0 @@
2015.05.21, v1.1.0
feature:
- (rendy) 5 times spead up
- (package) should v6.0.1
- (travis) add iojs, rm global gulp
- (package) scripts: test
- (test) greedy
- (package) should v5.2
- (package) scripts: gulp
2015.03.13, v1.0.6
fix:
- (rendy) clean up regexp: lazy -> greedy
2015.03.13, v1.0.5
feature:
- (rendy) put vars in forEach
- (package) should v5.0.0
- (bower) add
2015.01.26, v1.0.4
feature:
- (rendy) improve speed
2015.01.26, v1.0.3
feature:
- (rendy) speed up in 10 times: rm greedy quantifier
- (package) should v4.6
- (package) should v4.4.1
2014.12.12, v1.0.2
fix:
- (util) render: do not remove empty blocks "{{", "}}"
- (rendy) indexOf -> ~indexOf
feature:
- (package) v1.0.1
- (rendy) add expr
2014.12.12, v1.0.1
fix:
- (rendy) indexOf -> ~indexOf
feature:
- (rendy) add expr

View file

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

View file

@ -1,52 +0,0 @@
# Rendy [![License][LicenseIMGURL]][LicenseURL] [![NPM version][NPMIMGURL]][NPMURL] [![Dependency Status][DependencyStatusIMGURL]][DependencyStatusURL] [![Build Status][BuildStatusIMGURL]][BuildStatusURL]
Simple template engine compatible with [handlebars](http://handlebarsjs.com "Handlebars") and [mustache](https://mustache.github.io "Mustache").
## Install
![NPM_INFO][NPM_INFO_IMG]
`npm i rendy --save`
## How to use?
Rendy could be used in browser or node.
Browser version:
```html
<script src="rendy.js"></script>
<script>
var Tmpl = 'hello {{ where }}';
result = rendy(Tmpl, {
where: 'in browser'
});
// returns
'hello in browser'
</script>
```
Node version:
```js
var rendy = require('rendy'),
Tmpl = 'hello {{ who }}';
result = rendy(Tmpl, {
who: 'world'
});
// returns
'hello world'
```
## License
MIT
[NPM_INFO_IMG]: https://nodei.co/npm/rendy.png?downloads&&stars&&downloadRank "npm install rendy"
[NPMIMGURL]: https://img.shields.io/npm/v/rendy.svg?style=flat
[BuildStatusIMGURL]: https://img.shields.io/travis/coderaiser/rendy/master.svg?style=flat
[DependencyStatusIMGURL]: https://img.shields.io/gemnasium/coderaiser/rendy.svg?style=flat
[LicenseIMGURL]: https://img.shields.io/badge/license-MIT-317BF9.svg?style=flat
[NPMURL]: https://npmjs.org/package/rendy "npm"
[BuildStatusURL]: https://travis-ci.org/coderaiser/rendy "Build Status"
[DependencyStatusURL]: https://gemnasium.com/coderaiser/rendy "Dependency Status"
[LicenseURL]: https://tldrlegal.com/license/mit-license "MIT License"

View file

@ -1,25 +0,0 @@
{
"name": "rendy",
"version": "1.1.0",
"homepage": "https://github.com/coderaiser/rendy",
"authors": [
"coderaiser <mnemonic.enemy@gmail.com>"
],
"description": "simple template engine",
"main": "lib/rendy.js",
"moduleType": [
"globals",
"node"
],
"keywords": [
"template",
"engine",
"rendy"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"test"
]
}

View file

@ -1,18 +0,0 @@
(function() {
'use strict';
var gulp = require('gulp'),
mocha = require('gulp-mocha');
gulp.task('test', function() {
gulp.src('test/test.js')
.pipe(mocha({reporter: 'min'}))
.on('error', onError);
});
gulp.task('default', ['test']);
function onError(error) {
console.log(error.message);
}
})();

View file

@ -1,43 +0,0 @@
(function(global) {
'use strict';
if (typeof module === 'object' && module.exports)
module.exports = rendy;
else
global.rendy = rendy;
/**
* render template with data
*
* @param templ
* @param data
*/
function rendy(templ, data) {
var result = templ;
check(templ, data);
Object
.keys(data)
.forEach(function(param) {
var name = '{{ ' + param + ' }}',
str = data[param];
while(~result.indexOf(name))
result = result.replace(name, str);
});
if (~result.indexOf('{{'))
result = result.replace(/{{.*?}}/g, '');
return result;
}
function check(templ, data) {
if (typeof templ !== 'string')
throw(Error('template should be string!'));
if (typeof data !== 'object')
throw(Error('data should be object!'));
}
})(this);

View file

@ -1,28 +0,0 @@
{
"name": "rendy",
"version": "1.1.0",
"description": "simplest template engine",
"main": "lib/rendy.js",
"scripts": {
"test": "gulp test"
},
"repository": {
"type": "git",
"url": "git://github.com/coderaiser/rendy.git"
},
"keywords": [
"template",
"engine"
],
"author": "coderaiser <mnemonic.enemy@gmail.com> (http://coderaiser.github.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/coderaiser/rendy/issues"
},
"homepage": "https://github.com/coderaiser/rendy",
"devDependencies": {
"gulp": "~3.8.10",
"gulp-mocha": "~2.0.0",
"should": "~6.0.1"
}
}

View file

@ -44,6 +44,7 @@
}, },
"scripts": { "scripts": {
"start": "node bin/cloudcmd.js", "start": "node bin/cloudcmd.js",
"start:debug": "NODE_ENV=debug node bin/cloudcmd.js",
"start:dev": "nodemon bin/cloudcmd.js", "start:dev": "nodemon bin/cloudcmd.js",
"security": "nsp check", "security": "nsp check",
"codestyle": "redrun lint spell", "codestyle": "redrun lint spell",
@ -54,11 +55,11 @@
"lint:js:es5": "redrun es5:*", "lint:js:es5": "redrun es5:*",
"eslint:bin": "eslint --rule 'no-console:0' bin test server", "eslint:bin": "eslint --rule 'no-console:0' bin test server",
"fix:eslint:bin": "redrun eslint:bin -- --fix", "fix:eslint:bin": "redrun eslint:bin -- --fix",
"jshint": "jshint bin/release.js", "jshint": "jshint bin client server",
"jscs": "jscs --esnext $npm_package_config_dirs", "jscs": "jscs --esnext $npm_package_config_dirs",
"es5:jshint": "jshint --config .es5/.jshintrc $npm_package_config_dirs_dirs_legacy --exclude bin/release.js", "jshint:client": "jshint --config .es5/.jshintrc $npm_package_config_dirs_dirs_legacy --exclude bin/release.js",
"es5:eslint": "eslint -c .es5/.eslintrc --rule 'no-console:0' $npm_package_config_dirs_legacy --ignore-path bin/release.js", "eslint:client": "eslint --rule 'no-console:0' --env browser client",
"fix:es5:eslint": "redrun es5:eslint -- --fix", "fix:eslint": "redrun eslint:client -- --fix",
"test": "tape 'test/**/*.js'", "test": "tape 'test/**/*.js'",
"watch:test": "nodemon -w server -w test -w common -x \"npm run test\"", "watch:test": "nodemon -w server -w test -w common -x \"npm run test\"",
"spell": "yaspeller .", "spell": "yaspeller .",
@ -83,6 +84,9 @@
"report": "nyc report --reporter=text-lcov | coveralls", "report": "nyc report --reporter=text-lcov | coveralls",
"6to5:bin": "babel bin -d legacy/bin", "6to5:bin": "babel bin -d legacy/bin",
"6to5:server": "babel server -d server_", "6to5:server": "babel server -d server_",
"6to5:client": "webpack",
"6to5:client:debug": "NODE_ENV=debug webpack",
"watch:client": "NODE_ENV=debug webpack --watch",
"build": "redrun rm:* 6to5:* mkdir:* legacy:*", "build": "redrun rm:* 6to5:* mkdir:* legacy:*",
"legacy:package": "echo \"module.exports = require('../package');\" > legacy/package.js", "legacy:package": "echo \"module.exports = require('../package');\" > legacy/package.js",
"mkdir:server": "mkdirp legacy/server", "mkdir:server": "mkdirp legacy/server",
@ -144,8 +148,10 @@
}, },
"devDependencies": { "devDependencies": {
"babel-cli": "^6.18.0", "babel-cli": "^6.18.0",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.18.0", "babel-preset-es2015": "^6.18.0",
"coveralls": "^2.11.6", "coveralls": "^2.11.6",
"emitify": "^2.1.1",
"es6-promisify": "^5.0.0", "es6-promisify": "^5.0.0",
"eslint": "^3.1.1", "eslint": "^3.1.1",
"gunzip-maybe": "^1.3.1", "gunzip-maybe": "^1.3.1",
@ -170,6 +176,7 @@
"tape": "^4.4.0", "tape": "^4.4.0",
"tar-stream": "^1.5.2", "tar-stream": "^1.5.2",
"version-io": "^1.2.5", "version-io": "^1.2.5",
"webpack": "^2.2.1",
"yaspeller": "^3.0.0" "yaspeller": "^3.0.0"
}, },
"engines": { "engines": {

View file

@ -35,6 +35,8 @@ const root = () => config('root');
const emptyFunc = (req, res, next) => next(); const emptyFunc = (req, res, next) => next();
emptyFunc.middle = () => emptyFunc; emptyFunc.middle = () => emptyFunc;
const isDebug = process.env.NODE_ENV === 'debug';
function getPrefix(prefix) { function getPrefix(prefix) {
if (typeof prefix === 'function') if (typeof prefix === 'function')
return prefix() || ''; return prefix() || '';
@ -297,8 +299,11 @@ function setUrl(pref) {
req.url = req.url.replace(prefix, '') || '/'; req.url = req.url.replace(prefix, '') || '/';
if (req.url === '/cloudcmd.js') if (/^\/cloudcmd\.js(\.map)?$/.test(req.url))
req.url = '/client/cloudcmd.js'; req.url = `/dist${req.url}`;
if (isDebug)
req.url = req.url.replace(/^\/dist\//, '/dist-debug/');
next(); next();
}; };

55
webpack.config.js Normal file
View file

@ -0,0 +1,55 @@
const path = require('path');
const webpack = require('webpack');
const {optimize} = webpack
const {UglifyJsPlugin} = optimize;
const dir = './client';
const {env} = process;
const isDebug = env.NODE_ENV === 'debug';
const dist = path.resolve(__dirname, 'dist');
const distDebug = path.resolve(__dirname, 'dist-debug');
const devtool = isDebug ? 'eval' : 'source-map';
module.exports = {
devtool,
entry: {
cloudcmd: `${dir}/cloudcmd.js`,
edit: `${dir}/edit.js`,
'edit-file': `${dir}/edit-file.js`,
'edit-names': `${dir}/edit-names.js`,
menu: `${dir}/menu.js`,
view: `${dir}/view.js`,
help: `${dir}/help.js`,
markdown: `${dir}/markdown.js`,
config: `${dir}/config.js`,
contact: `${dir}/contact.js`,
upload: `${dir}/upload.js`,
operation: `${dir}/operation.js`,
konsole: `${dir}/konsole.js`,
cloud: `${dir}/cloud.js`
},
output: {
filename: '[name].js',
path: isDebug ? distDebug : dist,
libraryTarget: 'umd'
},
plugins: [
new UglifyJsPlugin({
sourceMap: true
}),
],
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_)?modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
};