beautify_js

This commit is contained in:
Ilya Kantor 2015-03-09 18:48:58 +03:00
parent 0febe4f5fd
commit 5c2f32e184
208 changed files with 3891 additions and 1474 deletions

View file

@ -9,93 +9,93 @@ var uploads = {};
function onUpload(req, res) {
var fileId = req.headers['x-file-id'];
if (!fileId) {
res.writeHead(400, "No file id");
res.end();
}
var fileId = req.headers['x-file-id'];
if (!fileId) {
res.writeHead(400, "No file id");
res.end();
}
// инициализация новой загрузки
var upload = uploads[fileId];
if (!upload) {
res.writeHead(400, "No such upload");
res.end();
return;
}
// инициализация новой загрузки
var upload = uploads[fileId];
if (!upload) {
res.writeHead(400, "No such upload");
res.end();
return;
}
upload.bytesWritten = 0;
upload.bytesWritten = 0;
var filePath = '/dev/null'; //path.join("/tmp", fileId);
var filePath = '/dev/null'; //path.join("/tmp", fileId);
// будем сохранять в файл с именем fileId
var fileStream = fs.createWriteStream(filePath);
// будем сохранять в файл с именем fileId
var fileStream = fs.createWriteStream(filePath);
// отправить тело запроса в файл
req.pipe(fileStream);
// отправить тело запроса в файл
req.pipe(fileStream);
// при записи очередного фрагмента событие progress
fileStream.on('drain', function() {
upload.bytesWritten = fileStream.bytesWritten;
upload.emit("progress");
});
// при записи очередного фрагмента событие progress
fileStream.on('drain', function() {
upload.bytesWritten = fileStream.bytesWritten;
upload.emit("progress");
});
// в конце -- событие end
fileStream.on('close', function() {
upload.finished = true;
upload.emit("end");
});
// в конце -- событие end
fileStream.on('close', function() {
upload.finished = true;
upload.emit("end");
});
// при ошибках - завершение запроса
fileStream.on('error', function (err) {
res.writeHead(500, "File error");
res.end('error');
});
// при ошибках - завершение запроса
fileStream.on('error', function(err) {
res.writeHead(500, "File error");
res.end('error');
});
// в конце запроса - очистка
req.on('end', function() {
res.end();
delete uploads[fileId];
// в конце запроса - очистка
req.on('end', function() {
res.end();
delete uploads[fileId];
// здесь обработка успешной загрузки
});
// здесь обработка успешной загрузки
});
}
function onStatusStream(req, res) {
var fileId = req.headers['x-file-id'];
var upload = uploads[fileId];
var fileId = req.headers['x-file-id'];
var upload = uploads[fileId];
if (!upload) {
upload = uploads[fileId] = new EventEmitter();
upload.bytesWritten = 0;
}
if (!upload) {
upload = uploads[fileId] = new EventEmitter();
upload.bytesWritten = 0;
}
console.log("upload bytesWritten", upload.bytesWritten);
console.log("upload bytesWritten", upload.bytesWritten);
// сразу же пишем текущий прогресс
res.write(upload.bytesWritten + '-');
// сразу же пишем текущий прогресс
res.write(upload.bytesWritten + '-');
// и по мере загрузки дописываем
upload.on('progress', function() {
res.write(upload.bytesWritten + '-');
});
// и по мере загрузки дописываем
upload.on('progress', function() {
res.write(upload.bytesWritten + '-');
});
upload.on('end', function() {
res.end();
});
upload.on('end', function() {
res.end();
});
}
function accept(req, res) {
if (req.url == '/status-stream') {
onStatusStream(req, res);
} else if (req.url == '/upload' && req.method == 'POST') {
onUpload(req, res);
} else {
fileServer.serve(req, res);
}
if (req.url == '/status-stream') {
onStatusStream(req, res);
} else if (req.url == '/upload' && req.method == 'POST') {
onUpload(req, res);
} else {
fileServer.serve(req, res);
}
}
@ -107,5 +107,4 @@ if (!module.parent) {
console.log('Сервер запущен на порту 8080');
} else {
exports.accept = accept;
}
}

View file

@ -1,5 +1,5 @@
function Uploader(file, onSuccess, onError, onProgress) {
// идентификатор загрузки, чтобы стыковать два потока
var fileId = file.name + '-' + file.size + '-' + +file.lastModifiedDate;
fileId = hashCode(fileId);
@ -16,27 +16,27 @@ function Uploader(file, onSuccess, onError, onProgress) {
if (this.status != 200) {
onError("Upload error " + this.statusText);
} else {
onSuccess();
onSuccess();
}
};
xhrUpload.open("POST", "upload", true);
xhrUpload.open("POST", "upload", true);
xhrUpload.setRequestHeader('X-File-Id', fileId);
xhrUpload.send(file.slice(startByte));
}
// *!* Получать статус: поток С сервера */!*
function upload() {
xhrStatus = new XMLHttpRequest();
xhrStatus = new XMLHttpRequest();
xhrStatus.onreadystatechange = function(e) {
console.log(this);
}
xhrStatus.onprogress = function() {
var lastByte = getLastProgress(xhrStatus.responseText);
console.log("lastByte", lastByte);
if (!xhrUpload) {
runUpload(lastByte+1);
runUpload(lastByte + 1);
}
onProgress(lastByte, file.size);
}
@ -46,7 +46,7 @@ function Uploader(file, onSuccess, onError, onProgress) {
xhrUpload.abort();
}
xhrStatus.open("POST", "status-stream", true);
xhrStatus.open("POST", "status-stream", true);
xhrStatus.setRequestHeader('X-File-Id', fileId);
xhrStatus.send();
}
@ -58,7 +58,7 @@ function Uploader(file, onSuccess, onError, onProgress) {
if (lastDelimiter < 0) return 0;
var prevDelimiter = response.lastIndexOf('-', lastDelimiter - 1);
return response.slice(prevDelimiter+1, lastDelimiter);
return response.slice(prevDelimiter + 1, lastDelimiter);
}
// внешний интерфейс
@ -72,12 +72,13 @@ function Uploader(file, onSuccess, onError, onProgress) {
function hashCode(str) {
if (str.length == 0) return 0;
var hash = 0, i, chr, len;
var hash = 0,
i, chr, len;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
};

View file

@ -3,7 +3,7 @@
* yearFrom {number} начальный год в селекторе
* yearTo {number} конечный год в селекторе
* value {Date} текущая выбранная дата
*/
*/
function DateSelector(options) {
var self = this;
@ -15,14 +15,14 @@ function DateSelector(options) {
var yearSelect, monthSelect, daySelect;
function render() {
var tmpl = _.template( options.template );
var tmpl = _.template(options.template);
elem = $('<div class="date-selector"/>').html(tmpl({
yearFrom: options.yearFrom,
yearTo: options.yearTo,
dayTo: getLastDayOfMonth(value.getFullYear(), value.getMonth()),
monthNames: monthNames
}));
yearSelect = elem.find('.year');
monthSelect = elem.find('.month');
daySelect = elem.find('.day');
@ -44,7 +44,7 @@ function DateSelector(options) {
if (!quiet) {
$(self).triggerHandler({
type: "select",
type: "select",
value: value
});
}
@ -56,7 +56,7 @@ function DateSelector(options) {
};
function onChange(e) {
var selectType = e.target.className;
if (selectType == "month" || selectType == "year") {
@ -65,25 +65,25 @@ function DateSelector(options) {
}
readValue(); // для простоты -- получим значения из всех селектов
$(self).triggerHandler({
type: "select",
type: "select",
value: value
});
}
function readValue() {
// если я сделаю сначала value.setMonth(),
// то может получится некорректная дата типа 31 марта -> 31 февраля,
// которая автоскорректируется в 2 марта, т.е месяц не поставится.
// поэтому сначала именно setDate, и так далее.
value.setDate(daySelect.val());
value.setMonth(monthSelect.val());
value.setFullYear(yearSelect.val());
// если я сделаю сначала value.setMonth(),
// то может получится некорректная дата типа 31 марта -> 31 февраля,
// которая автоскорректируется в 2 марта, т.е месяц не поставится.
// поэтому сначала именно setDate, и так далее.
value.setDate(daySelect.val());
value.setMonth(monthSelect.val());
value.setFullYear(yearSelect.val());
}
function getLastDayOfMonth(year, month) {
var date = new Date(year, month+1, 0);
var date = new Date(year, month + 1, 0);
return date.getDate();
}
@ -96,9 +96,9 @@ function DateSelector(options) {
}).remove();
// добавить дни, если новый месяц дольше
for(var i = +daySelect.last().val(); i <= maxDay; i++) {
for (var i = +daySelect.last().val(); i <= maxDay; i++) {
daySelect.append(new Option(i, i));
}
}
}
}

View file

@ -3,10 +3,10 @@
* yearFrom {number} начальный год в селекторе
* yearTo {number} конечный год в селекторе
* value {Date} текущая выбранная дата
*/
*/
function DateSelector(options) {
var self = this;
/* ваш код */
}
}

View file

@ -9,7 +9,7 @@ function DraggableWindow(options) {
var self = this;
var title = options.title;
var template = typeof options.template == 'function' ? // компиляция, если строка
var template = typeof options.template == 'function' ? // компиляция, если строка
options.template : _.template(options.template);
var elem, contentElem;
@ -28,8 +28,8 @@ function DraggableWindow(options) {
titleElem = elem.find('.window-title');
titleElem.on('selectstart dragstart', false);
titleElem.on('mousedown', onTitleMouseDown);
titleElem.on('selectstart dragstart', false);
titleElem.on('mousedown', onTitleMouseDown);
contentElem = elem.find('.window-content'); // = children[1]
}
@ -39,16 +39,16 @@ function DraggableWindow(options) {
return elem;
}
function onTitleMouseDown(e) {
startDrag(e.pageX, e.pageY);
function onTitleMouseDown(e) {
startDrag(e.pageX, e.pageY);
return false;
};
function startDrag(mouseDownX, mouseDownY) {
// запомнить координаты нажатия
var coords = elem.offset();
mouseDownShift = {
x: mouseDownX - coords.left,
mouseDownShift = {
x: mouseDownX - coords.left,
y: mouseDownY - coords.top
};
@ -115,12 +115,13 @@ function DraggableWindow(options) {
function submit(message) {
// добавить
var newMessageElem = $('<div>', {text: message }).appendTo(contentElem);
var newMessageElem = $('<div>', {
text: message
}).appendTo(contentElem);
// прокрутить к новому сообщению
contentElem.prop('scrollTop', 999999999);
}
}
}

View file

@ -9,7 +9,7 @@ function DraggableWindow(options) {
var self = this;
var title = options.title;
var template = typeof options.template == 'function' ? // компиляция, если строка
var template = typeof options.template == 'function' ? // компиляция, если строка
options.template : _.template(options.template);
var elem, contentElem;
@ -25,8 +25,8 @@ function DraggableWindow(options) {
titleElem = elem.find('.window-title');
titleElem.on('selectstart dragstart', false);
titleElem.on('mousedown', onTitleMouseDown);
titleElem.on('selectstart dragstart', false);
titleElem.on('mousedown', onTitleMouseDown);
contentElem = elem.find('.window-content'); // = children[1]
elem.on('focusin', onFocus);
@ -38,11 +38,13 @@ function DraggableWindow(options) {
}
function onFocus() {
$(self).triggerHandler({ type: 'focus' });
$(self).triggerHandler({
type: 'focus'
});
}
function onTitleMouseDown(e) {
startDrag(e.pageX, e.pageY);
function onTitleMouseDown(e) {
startDrag(e.pageX, e.pageY);
setTimeout(onFocus, 0);
return false; // returning false prevents onfocus
@ -51,8 +53,8 @@ function DraggableWindow(options) {
function startDrag(mouseDownX, mouseDownY) {
// запомнить координаты нажатия
var coords = elem.offset();
mouseDownShift = {
x: mouseDownX - coords.left,
mouseDownShift = {
x: mouseDownX - coords.left,
y: mouseDownY - coords.top
};
@ -119,7 +121,9 @@ function DraggableWindow(options) {
function submit(message) {
// добавить
var newMessageElem = $('<div>', {text: message }).appendTo(contentElem);
var newMessageElem = $('<div>', {
text: message
}).appendTo(contentElem);
// прокрутить к новому сообщению
contentElem.prop('scrollTop', 999999999);
@ -138,5 +142,4 @@ function DraggableWindow(options) {
return "[Window " + options.title + " " + elem.css('z-index') + "]";
}
}
}

View file

@ -3,7 +3,7 @@ var WindowManager = new function() {
var windows = [];
var activeWindow;
var template;
var template;
this.setTemplate = function(newTemplate) {
template = _.template(newTemplate);
@ -43,10 +43,10 @@ var WindowManager = new function() {
if (activeWindow == b) return -1; // активное окно больше всех
return a.getZIndex() - b.getZIndex(); // порядок среди остальных - оставляем "как есть"
});
for(var i=0; i<windows.length; i++) {
windows[i].setZIndex(i+1);
for (var i = 0; i < windows.length; i++) {
windows[i].setZIndex(i + 1);
}
}
}
}

View file

@ -2,7 +2,7 @@
* options:
* value Date или объект {year,month,day}} -- дата, для которой показывать календарь
* если в объекте указаны только {year,month}, то день не выбран
*/
*/
function Calendar(options) {
var self = this;
@ -55,7 +55,7 @@ function Calendar(options) {
if (!quiet) {
$(self).triggerHandler({
type: "select",
type: "select",
value: new Date(year, month, day)
});
}
@ -69,16 +69,16 @@ function Calendar(options) {
function render() {
if (!elem) {
elem = $('<div class="calendar"/>')
.on('click', '.date-cell', onDateCellClick);
.on('click', '.date-cell', onDateCellClick);
}
if (showYear != year || showMonth != month) {
if (showYear != year || showMonth != month) {
elem.html(renderCalendarTable(year, month));
elem.find('caption').html(monthNames[month]+' '+year);
elem.find('caption').html(monthNames[month] + ' ' + year);
showYear = year;
showMonth = month;
}
if (day) {
var num = getCellByDate(new Date(year, month, day));
elem.find('td').eq(num).addClass("selected");
@ -91,9 +91,13 @@ function Calendar(options) {
}
function onDateCellClick(e) {
function onDateCellClick(e) {
day = $(e.target).html();
self.setValue({year: year, month: month, day: day});
self.setValue({
year: year,
month: month,
day: day
});
}
@ -101,7 +105,7 @@ function Calendar(options) {
* Возвращает по дате номер TD в таблице
* Использование:
* var td = table.getElementsByTagName('td')[getCellByDate(date)]
*/
*/
function getCellByDate(date) {
var dateDayOne = new Date(date.getFullYear(), date.getMonth(), 1);
@ -127,24 +131,24 @@ function Calendar(options) {
var table = ['<table class="calendar-table"><caption></caption><tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th>сб</th><th>вс</th></tr><tr>'];
for (var i=0; i<getDay(d); i++) {
for (var i = 0; i < getDay(d); i++) {
table.push('<td></td>');
}
// ячейки календаря с датами
while(d.getMonth() == month) {
table.push('<td class="date-cell">'+d.getDate()+'</td>');
while (d.getMonth() == month) {
table.push('<td class="date-cell">' + d.getDate() + '</td>');
if (getDay(d) % 7 == 6) { // вс, последний день - перевод строки
table.push('</tr><tr>');
}
d.setDate(d.getDate()+1);
d.setDate(d.getDate() + 1);
}
// добить таблицу пустыми ячейками, если нужно
if (getDay(d) != 0) {
for (var i=getDay(d); i<7; i++) {
for (var i = getDay(d); i < 7; i++) {
table.push('<td></td>');
}
}
@ -154,5 +158,4 @@ function Calendar(options) {
return table.join('\n')
}
}
}

View file

@ -2,8 +2,8 @@
* options:
* value Date или объект {year,month,day}} -- дата, для которой показывать календарь
* если в объекте указаны только {year,month}, то день не выбран
*/
function DatePicker(options) {
*/
function DatePicker(options) {
var elem;
var calendarLeft;
var calendarRight;
@ -50,7 +50,10 @@ function DatePicker(options) {
if (!calendarCache[key]) {
calendar = calendarCache[key] = new Calendar({
value: {year: year, month: month}
value: {
year: year,
month: month
}
});
$(calendar).on("select", onCalendarSelect);
} else {
@ -78,7 +81,7 @@ function DatePicker(options) {
}
$(self).triggerHandler({
type: "select",
type: "select",
value: e.target.getValue()
});
}
@ -127,4 +130,4 @@ function DatePicker(options) {
return false;
}
}
}

View file

@ -2,7 +2,7 @@
* options:
* value Date или объект {year,month,day}} -- дата, для которой показывать календарь
* если в объекте указаны только {year,month}, то день не выбран
*/
*/
function Calendar(options) {
var self = this;
@ -55,7 +55,7 @@ function Calendar(options) {
if (!quiet) {
$(self).triggerHandler({
type: "select",
type: "select",
value: new Date(year, month, day)
});
}
@ -69,16 +69,16 @@ function Calendar(options) {
function render() {
if (!elem) {
elem = $('<div class="calendar"/>')
.on('click', '.date-cell', onDateCellClick);
.on('click', '.date-cell', onDateCellClick);
}
if (showYear != year || showMonth != month) {
if (showYear != year || showMonth != month) {
elem.html(renderCalendarTable(year, month));
elem.find('caption').html(monthNames[month]+' '+year);
elem.find('caption').html(monthNames[month] + ' ' + year);
showYear = year;
showMonth = month;
}
if (day) {
var num = getCellByDate(new Date(year, month, day));
elem.find('td').eq(num).addClass("selected");
@ -91,9 +91,13 @@ function Calendar(options) {
}
function onDateCellClick(e) {
function onDateCellClick(e) {
day = $(e.target).html();
self.setValue({year: year, month: month, day: day});
self.setValue({
year: year,
month: month,
day: day
});
}
@ -101,7 +105,7 @@ function Calendar(options) {
* Возвращает по дате номер TD в таблице
* Использование:
* var td = table.getElementsByTagName('td')[getCellByDate(date)]
*/
*/
function getCellByDate(date) {
var dateDayOne = new Date(date.getFullYear(), date.getMonth(), 1);
@ -127,24 +131,24 @@ function Calendar(options) {
var table = ['<table class="calendar-table"><caption></caption><tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th>сб</th><th>вс</th></tr><tr>'];
for (var i=0; i<getDay(d); i++) {
for (var i = 0; i < getDay(d); i++) {
table.push('<td></td>');
}
// ячейки календаря с датами
while(d.getMonth() == month) {
table.push('<td class="date-cell">'+d.getDate()+'</td>');
while (d.getMonth() == month) {
table.push('<td class="date-cell">' + d.getDate() + '</td>');
if (getDay(d) % 7 == 6) { // вс, последний день - перевод строки
table.push('</tr><tr>');
}
d.setDate(d.getDate()+1);
d.setDate(d.getDate() + 1);
}
// добить таблицу пустыми ячейками, если нужно
if (getDay(d) != 0) {
for (var i=getDay(d); i<7; i++) {
for (var i = getDay(d); i < 7; i++) {
table.push('<td></td>');
}
}
@ -154,5 +158,4 @@ function Calendar(options) {
return table.join('\n')
}
}
}

View file

@ -2,7 +2,7 @@
* options:
* value Date или объект {year,month,day}} -- дата, для которой показывать календарь
* если в объекте указаны только {year,month}, то день не выбран
*/
function DatePicker(options) {
*/
function DatePicker(options) {
/* ваш код */
}
}

View file

@ -1,5 +1,7 @@
var result = {
0: { children: [] }
0: {
children: []
}
};
$('div[id^="region"]').each(function() {
@ -17,7 +19,7 @@ $('div[id^="region"]').each(function() {
} else {
pid = 0;
}
result[pid].children.push(+id);
});

File diff suppressed because one or more lines are too long

View file

@ -1,4 +1,3 @@
function Tree(options) {
var self = this;
@ -7,15 +6,15 @@ function Tree(options) {
var data = options.data;
this.getElement = function() {
if (!this.elem) render();
return this.elem;
if (!this.elem) render();
return this.elem;
}
function onTogglerClick(e) {
self.toggle( $(e.currentTarget.parentNode) );
function onTogglerClick(e) {
self.toggle($(e.currentTarget.parentNode));
}
function onCheckboxChange(e) {
function onCheckboxChange(e) {
var checked = e.target.checked;
var id = e.target.value;
var node = $(e.currentTarget.parentNode);
@ -27,9 +26,9 @@ function Tree(options) {
node.find('input').prop('checked', checked);
}
this.toggle = function(node) {
ensureChildrenRendered(node);
node.toggleClass("tree-open tree-closed");
this.toggle = function(node) {
ensureChildrenRendered(node);
node.toggleClass("tree-open tree-closed");
};
this.open = function(node) {
@ -45,30 +44,30 @@ function Tree(options) {
function ensureChildrenRendered(node) {
var ul = node.children('ul');
if (!ul.length) {
renderChildren( node.data('id') ).appendTo(node);
if (!ul.length) {
renderChildren(node.data('id')).appendTo(node);
if (node.children('input').is(':checked')) {
node.find('input').prop('checked', true);
}
}
}
}
function renderChildren(id) {
return $(template({
children: data[id].children,
data: data
}));
return $(template({
children: data[id].children,
data: data
}));
}
function render() {
self.elem = renderChildren(0)
.addClass('tree');
self.elem.on('click', '.tree-toggler', onTogglerClick);
self.elem = renderChildren(0)
.addClass('tree');
self.elem.on('click', '.tree-toggler', onTogglerClick);
self.elem.on('change', 'input', onCheckboxChange);
}
}
}

View file

@ -2,7 +2,7 @@
* options:
* value Date или объект {year,month,day}} -- дата, для которой показывать календарь
* если в объекте указаны только {year,month}, то день не выбран
*/
*/
function Calendar(options) {
var self = this;
@ -55,7 +55,7 @@ function Calendar(options) {
if (!quiet) {
$(self).triggerHandler({
type: "select",
type: "select",
value: new Date(year, month, day)
});
}
@ -64,16 +64,16 @@ function Calendar(options) {
function render() {
if (!elem) {
elem = $('<div class="calendar"/>')
.on('click', '.date-cell', onDateCellClick);
.on('click', '.date-cell', onDateCellClick);
}
if (showYear != year || showMonth != month) {
if (showYear != year || showMonth != month) {
elem.html(renderCalendarTable(year, month));
elem.find('caption').html(monthNames[month]+' '+year);
elem.find('caption').html(monthNames[month] + ' ' + year);
showYear = year;
showMonth = month;
}
if (day) {
var num = getCellByDate(new Date(year, month, day));
elem.find('td').eq(num).addClass("selected");
@ -86,9 +86,13 @@ function Calendar(options) {
}
function onDateCellClick(e) {
function onDateCellClick(e) {
day = $(e.target).html();
self.setValue({year: year, month: month, day: day});
self.setValue({
year: year,
month: month,
day: day
});
}
@ -96,7 +100,7 @@ function Calendar(options) {
* Возвращает по дате номер TD в таблице
* Использование:
* var td = table.getElementsByTagName('td')[getCellByDate(date)]
*/
*/
function getCellByDate(date) {
var dateDayOne = new Date(date.getFullYear(), date.getMonth(), 1);
@ -122,24 +126,24 @@ function Calendar(options) {
var table = ['<table class="calendar-table"><caption></caption><tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th>сб</th><th>вс</th></tr><tr>'];
for (var i=0; i<getDay(d); i++) {
for (var i = 0; i < getDay(d); i++) {
table.push('<td></td>');
}
// ячейки календаря с датами
while(d.getMonth() == month) {
table.push('<td class="date-cell">'+d.getDate()+'</td>');
while (d.getMonth() == month) {
table.push('<td class="date-cell">' + d.getDate() + '</td>');
if (getDay(d) % 7 == 6) { // вс, последний день - перевод строки
table.push('</tr><tr>');
}
d.setDate(d.getDate()+1);
d.setDate(d.getDate() + 1);
}
// добить таблицу пустыми ячейками, если нужно
if (getDay(d) != 0) {
for (var i=getDay(d); i<7; i++) {
for (var i = getDay(d); i < 7; i++) {
table.push('<td></td>');
}
}
@ -149,5 +153,4 @@ function Calendar(options) {
return table.join('\n')
}
}
}

View file

@ -2,7 +2,7 @@
* Возвращает по дате номер TD в таблице
* Использование:
* var td = table.find('td').eq(getCellByDate(date))
*/
*/
function getCellByDate(date) {
var date1 = new Date(date.getFullYear(), date.getMonth(), 1);
@ -30,24 +30,24 @@ function renderCalendarTable(year, month) {
var table = ['<table class="calendar-table"><tr><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th>сб</th><th>вс</th></tr><tr>'];
for (var i=0; i<getDay(d); i++) {
for (var i = 0; i < getDay(d); i++) {
table.push('<td></td>');
}
// ячейки календаря с датами
while(d.getMonth() == month) {
table.push('<td class="date-cell">'+d.getDate()+'</td>');
while (d.getMonth() == month) {
table.push('<td class="date-cell">' + d.getDate() + '</td>');
if (getDay(d) % 7 == 6) { // вс, последний день - перевод строки
table.push('</tr><tr>');
}
d.setDate(d.getDate()+1);
d.setDate(d.getDate() + 1);
}
// добить таблицу пустыми ячейками, если нужно
if (getDay(d) != 0) {
for (var i=getDay(d); i<7; i++) {
for (var i = getDay(d); i < 7; i++) {
table.push('<td></td>');
}
}
@ -55,4 +55,4 @@ function renderCalendarTable(year, month) {
table.push('</tr></table>');
return table.join('\n')
}
}

View file

@ -2,9 +2,9 @@
* options:
* year/month {number} год/месяц для календаря
* value {Date} текущая выбранная дата
*/
*/
function Calendar(options) {
var monthNames = 'Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь'.split(' ');
/* ваш код */
}
}

View file

@ -13,12 +13,12 @@ function AutocompleteList(provider) {
filteredResults = provider.filterByStart(value);
if (filteredResults.length) {
elem.html( '<li>' + filteredResults.join('</li><li>') + '</li>' );
elem.html('<li>' + filteredResults.join('</li><li>') + '</li>');
} else {
elem.empty();
}
currentIndex = 0;
currentIndex = 0;
renderCurrent();
// это событие, как и всё обновление,
@ -34,8 +34,8 @@ function AutocompleteList(provider) {
elem.children().eq(currentIndex).addClass('selected');
}
function clearCurrent() {
elem.children().eq(currentIndex).removeClass('selected');
function clearCurrent() {
elem.children().eq(currentIndex).removeClass('selected');
}
this.get = function() {

View file

@ -2,7 +2,7 @@ function Autocomplete(options) {
var self = this;
var elem = options.elem;
var input = $('input', elem);
var list;
@ -23,7 +23,7 @@ function Autocomplete(options) {
var KEY_ENTER = 13;
var KEY_ESC = 27;
switch(e.keyCode) {
switch (e.keyCode) {
case KEY_ARROW_UP:
list.up();
return false;
@ -31,12 +31,12 @@ function Autocomplete(options) {
case KEY_ARROW_RIGHT:
if (list.get()) {
self.setValue( list.get(), true );
self.setValue(list.get(), true);
}
break;
case KEY_ENTER:
self.setValue( list.get() || input.val() );
self.setValue(list.get() || input.val());
input.blur();
break;
@ -68,12 +68,13 @@ function Autocomplete(options) {
function onInputFocus() {
var inputValue = input.val();
function checkInput() {
if (inputValue != input.val()) {
if (!list) {
initList();
}
}
list.update(input.val());
inputValue = input.val();

View file

@ -2,61 +2,61 @@
* Taken from jQuery UI accordion and fixed, special hoverintent event
* http://benalman.com/news/2010/03/jquery-special-events/
*/
!function($) {
! function($) {
var cfg = {
sensitivity: 9,
interval: 50
};
var cfg = {
sensitivity: 9,
interval: 50
};
$.event.special.hoverintent = {
setup: function() {
$(this).on("mouseover", handler);
},
$.event.special.hoverintent = {
setup: function() {
$(this).on("mouseover", handler);
},
teardown: function() {
$(this).on("mouseover", handler);
},
teardown: function() {
$(this).on("mouseover", handler);
},
cfg: cfg
};
cfg: cfg
};
function handler(event) {
function handler(event) {
var self = this,
args = arguments,
target = $(event.target),
cX, cY, pX, pY;
var self = this,
args = arguments,
target = $(event.target),
cX, cY, pX, pY;
function track(event) {
cX = event.pageX;
cY = event.pageY;
};
pX = event.pageX;
pY = event.pageY;
function track(event) {
cX = event.pageX;
cY = event.pageY;
};
pX = event.pageX;
pY = event.pageY;
function clear() {
target.off("mousemove", track).off("mouseout", clear);
clearTimeout(timeout);
}
function clear() {
target.off("mousemove", track).off("mouseout", clear);
clearTimeout(timeout);
}
function handler() {
if((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
clear();
event.type = "hoverintent";
jQuery.event.simulate("hoverintent", event.target, $.event.fix(event), true);
} else {
pX = cX;
pY = cY;
timeout = setTimeout(handler, cfg.interval);
}
}
var timeout = setTimeout(handler, cfg.interval);
target.mousemove(track).mouseout(clear);
return true;
}
function handler() {
if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
clear();
event.type = "hoverintent";
jQuery.event.simulate("hoverintent", event.target, $.event.fix(event), true);
} else {
pX = cX;
pY = cY;
timeout = setTimeout(handler, cfg.interval);
}
}
var timeout = setTimeout(handler, cfg.interval);
target.mousemove(track).mouseout(clear);
return true;
}
}(jQuery);
}(jQuery);

View file

@ -16,7 +16,7 @@ function Menu(options) {
// ----------------------
function onLiClick(e) {
close();
var li = $(e.currentTarget).closest('li');
@ -26,7 +26,7 @@ function Menu(options) {
value: getLiValue(li)
});
return false;
return false;
}
function onTitleClick() {
@ -55,7 +55,7 @@ function Menu(options) {
function close(argument) {
elem.removeClass('open');
if (activeLi) {
@ -77,7 +77,7 @@ function Menu(options) {
// TODO: close menu on document click outside of it
$(document).on('click.menu-nested', function(e) {
if ( $(e.target).closest(elem).length ) return;
if ($(e.target).closest(elem).length) return;
close();
});
}
@ -93,7 +93,7 @@ function Menu(options) {
// collapse parents of last active until container of new element
collapseActiveUntil(li);
}
activeLi = li;
activeLi.addClass("active");
}
@ -101,7 +101,7 @@ function Menu(options) {
function collapseActiveUntil(li) {
var el = activeLi;
for(;;) {
for (;;) {
el.removeClass('active');
if (el[0].parentNode == li[0].parentNode) break;
el = getParentLi(el);
@ -109,12 +109,12 @@ function Menu(options) {
}
function openChildren() {
function openChildren() {
var subcontainer = activeLi.children('ol');
if (!subcontainer.length) return;
// show children
var left = activeLi.width(); // to the right of the parent
var top = activeLi.position().top; // at same height as current parent