-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Д/з 5 — Жевак Антон #3
Open
mayton
wants to merge
15
commits into
yandex-shri-ekb:master
Choose a base branch
from
mayton:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
677f688
созданы необходимые файлы
mayton 60b76d0
рабочая версия
mayton 4d87033
мелкие исправления
mayton ee475d3
исправления для firefox
mayton 714ba16
head -> html
mayton 69b1516
мелкие исправления
mayton bbaf8ea
замена layout.force на layout.tree, переделан алгоритм
mayton 4a6e3fd
изменен алгоритм запросов данны�
mayton 3975c69
небольшая, но важная корректировка
mayton 8564a9b
увеличен таймаут загрузки модулей requirejs
mayton 3f0ba8d
косметические изменения
mayton 977ad44
grunt
mayton f02437c
ls переименован в cache
mayton de4ec9d
изменена работа кеша
mayton 648a191
добавлен вывод инфы о текущем состоянии дел и возможность очистки кеша
mayton File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
.idea | ||
node_modules | ||
.gitignore |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
module.exports = function(grunt) { | ||
|
||
grunt.initConfig({ | ||
pkg: grunt.file.readJSON('package.json'), | ||
|
||
uglify : { | ||
main : { | ||
options : { | ||
banner : 'javascript:void' | ||
}, | ||
files : { | ||
'build/bookmarklet.min.js' : 'bookmarklet.js' | ||
} | ||
} | ||
}, | ||
|
||
requirejs : { | ||
compile : { | ||
options : { | ||
name : 'main', | ||
out : 'build/all.min.js', | ||
paths : { | ||
jquery : 'empty:', | ||
d3 : 'empty:' | ||
}, | ||
exclude : ['text'] | ||
} | ||
} | ||
} | ||
}); | ||
|
||
grunt.loadNpmTasks('grunt-contrib-uglify'); | ||
grunt.loadNpmTasks('grunt-contrib-requirejs'); | ||
|
||
grunt.registerTask('default', ['uglify', 'requirejs']); | ||
|
||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,226 @@ | ||
'use strict'; | ||
|
||
|
||
define([ | ||
'jquery', | ||
'tree', | ||
'cache', | ||
'text!main.css', | ||
'text!main.html' | ||
], function($, Tree, Cache, css, html) { | ||
|
||
/** | ||
* Приложение. | ||
* @constructor | ||
* @param {Object} config настройки | ||
*/ | ||
var App = function(config) { | ||
this.config = config || {}; | ||
this.config.userCount = config.userCount || 2; | ||
this.config.blackList = config.blackList || []; | ||
|
||
// Извлекаем имена пользователей, с которых мы начнём строить дерево | ||
this.startUsernames = this.getStartUsernames(this.config.userCount); | ||
$('head').append('<style>' + css + '</style>'); | ||
$(document.body).html(html).show(); | ||
|
||
this.config.gui = { | ||
statusText : $(config.gui.statusText), | ||
queueLength : $(config.gui.queueLength), | ||
cacheLength : $(config.gui.cacheLength), | ||
clearButton : $(config.gui.clearButton) | ||
}; | ||
|
||
this.usersUrl = this.config.usersUrl; | ||
|
||
// Игнорируемые | ||
this.blackList = this.config.blackList; | ||
|
||
// Визуализация дерева | ||
this.tree = new Tree; | ||
|
||
// Работа с кешем | ||
this.cache = new Cache; | ||
|
||
// Очередь детей, о которых надо получить информацию и добавить в дерево | ||
this.queue = []; | ||
|
||
// Количество запросов в очереди | ||
this.delay = 0; | ||
|
||
// Величина паузы между запросами к серверу, мс | ||
this.timeout = 500; | ||
|
||
// Префикс для кеширования данных о пользователях | ||
this.USER_PREFIX = 'habraUserv2.'; | ||
|
||
var self = this; | ||
this.config.gui.clearButton.on('click', function() { | ||
self.cache.clear(); | ||
self.updateGui(); | ||
return false; | ||
}); | ||
}; | ||
|
||
/** | ||
* Строит дерево. | ||
*/ | ||
App.prototype.start = function() { | ||
var self = this; | ||
|
||
// Ищем корни и добавляем их в дерево | ||
for (var i = 0, len = this.startUsernames.length; i < len; i++) { | ||
if (self.blackListCheck(this.startUsernames[i])) | ||
continue; | ||
|
||
this.getUserInfo(this.startUsernames[i]).then(function(user) { | ||
// TODO: внутри findRoot не проверяется черный список | ||
self.findRoot(user).then(function(user) { | ||
$.proxy(self.addUser(user), self); | ||
}); | ||
}); | ||
} | ||
|
||
// Через определённые промежутки времени | ||
// будем доставать из очереди пользователя | ||
var step = setInterval(function() { | ||
if (self.queue.length > 0) { | ||
var username = self.queue.shift(); | ||
|
||
// Некоторые пользователи (BarsMonster) приглашали других дважды (grokru) | ||
if (self.queue.indexOf(username) > -1) return; | ||
|
||
if (self.blackListCheck(username)) return; | ||
|
||
// Получать о нём информацию и добавлять в дерево | ||
self.getUserInfo(username).then(function(user) { | ||
$.proxy(self.addUser(user), self); | ||
}); | ||
} | ||
}, 100); | ||
}; | ||
|
||
/** | ||
* Проверяет, есть ли пользователь с указанным именем в чёрном списке. | ||
* @param {string} name имя пользователя | ||
* @return {boolean} | ||
*/ | ||
App.prototype.blackListCheck = function(name) { | ||
return this.blackList.indexOf(name) > -1; | ||
}; | ||
|
||
/** | ||
* Добавляет пользователя в дерево, а имена его детей в очередь на обход. | ||
* @param {Object} user пользователь | ||
*/ | ||
App.prototype.addUser = function(user) { | ||
this.tree.addNode(user); | ||
this.tree.update(); | ||
if (user.children.length > 0) { | ||
for (var i = 0, l = user.children.length; i < l; i++) | ||
this.queue.push(user.children[i]); | ||
} | ||
}; | ||
|
||
/** | ||
* Ищет первого зарегистрировавшегося, с которого началась ветка. | ||
* @param {Object} user пользователь | ||
* @return {Object} Deferred-объект | ||
*/ | ||
App.prototype.findRoot = function(user) { | ||
var d; | ||
// Если у пользователя есть родитель, значит запрашиваем информацию о его родителе | ||
if (user.parent) { | ||
var self = this; | ||
d = this.getUserInfo(user.parent).then(function(parent) { | ||
return self.findRoot(parent); | ||
}); | ||
return d; | ||
} else { // Если пользователь зарегистрировался по приглашению НЛО | ||
d = $.Deferred(); | ||
return d.resolve(user); | ||
} | ||
}; | ||
|
||
/** | ||
* Находит на странице имена либо всех, либо первых n пользователей. | ||
* @param {number} n максимальное число имён пользователей | ||
* @return {Array} имена пользователей | ||
*/ | ||
App.prototype.getStartUsernames = function(n) { | ||
var users = $('.username a'), | ||
usernames = []; | ||
n = n || users.length; | ||
for (var i = 0; i < n; i++) { | ||
usernames.push(users[i].innerHTML); | ||
} | ||
return usernames; | ||
}; | ||
|
||
/** | ||
* Получает информацию о запрашиваемом пользователе из localStorage, либо со страницы его профиля. | ||
* @param {string} username ник пользователя | ||
* @return {Object} Deferred-объект | ||
*/ | ||
App.prototype.getUserInfo = function(username) { | ||
var d = $.Deferred(), | ||
self = this, | ||
user = this.cache.get(this.USER_PREFIX + username); | ||
|
||
// Если пользователя нет в кеше, делаем запрос | ||
if (user === null) { | ||
setTimeout(function() { | ||
$.get(self.usersUrl + username + '/').then(function(data) { | ||
self.delay--; | ||
|
||
var user = {}; | ||
user.name = username; // $(data).find('.user_header h2.username a').text(); | ||
user.avatar = $(data).find('.user_header .avatar img').attr('src'); | ||
user.parent = $(data).find('#invited-by').text() || null; | ||
user.children = []; | ||
|
||
// [rel=friend] - иначе при большом кол-ве приглашённых появляется ссылка "показать все" | ||
var children = $(data).find('#invited_data_items a[rel=friend]'); | ||
if (children.length > 0) { | ||
for (var i = 0, l = children.length; i < l; i++) | ||
user.children.push(children[i].innerHTML); | ||
} | ||
|
||
// Кешируем в localStorage | ||
self.cache.set(self.USER_PREFIX + user.name, user); | ||
|
||
self.updateGui(); | ||
|
||
d.resolve(user); | ||
}); | ||
}, this.delay++ * this.timeout); | ||
} else { | ||
d.resolve(user); | ||
} | ||
|
||
this.updateGui(); | ||
|
||
return d; | ||
}; | ||
|
||
/** | ||
* Обновляет информацию на экране о текущем состоянии дел. | ||
*/ | ||
App.prototype.updateGui = function() { | ||
var queue = this.delay + this.queue.length; | ||
|
||
this.config.gui.cacheLength.text(this.cache.count()); | ||
if (queue > 0) { | ||
var status = 'Идёт сканирование'; | ||
$(document.body).removeClass('ready'); | ||
} else { | ||
var status = 'Дерево построено'; | ||
$(document.body).addClass('ready'); | ||
} | ||
this.config.gui.statusText.text(status); | ||
this.config.gui.queueLength.text(queue); | ||
}; | ||
|
||
return App; | ||
|
||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
(function() { | ||
|
||
var config = { | ||
require : '//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.9/require.min.js', | ||
start : 'https://rawgithub.com/mayton/5-async/master/build/all.min.js' | ||
}; | ||
|
||
if (window.location.href !== 'http://habrahabr.ru/users/') { | ||
alert('Для запуска сценария перейдите по адресу http://habrahabr.ru/users/'); | ||
return; | ||
} | ||
|
||
var body = document.body; | ||
if (body.getAttribute('count') !== null) { | ||
alert('Для повторного запуска сценария необходимо обновить страницу.'); | ||
return; | ||
} | ||
|
||
var userCount = prompt('Сколько пользователей брать для анализа?', 2); | ||
if (userCount === null) | ||
return; | ||
|
||
body.setAttribute('count', userCount); | ||
body.style.display = 'none'; | ||
|
||
var head = document.getElementsByTagName('head')[0]; | ||
head.innerHTML = '<title>Домашняя работа №5</title>'; | ||
|
||
var s = document.createElement('script'); | ||
s.setAttribute('src', config.require); | ||
s.setAttribute('data-main', config.start); | ||
head.appendChild(s); | ||
|
||
})(); |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
UglifyJS заменяет круглые скобки на восклицательный знак и букмарклет перестаёт работать в Firefox. Кто умный, скажите как исправить :-)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
banner : 'javascript:void'
->javascript:void!function(){...}()
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Спасибо. То, что нужно.