/*
* @title Open by Drag
* @description drag and open
* @include http://*
* @domain http://d.hatena.ne.jp/
* @license MIT License
* @require http://gist.github.com/3239.txt#createElementFromString
*/
selectNodeByDrag(function (results) {
if (confirm(results.length + ' links selected. Open All?')) {
for (var i = 0, len = results.length; i < len; i++) {
window.open(results[i]);
}
}
});
function selectNodeByDrag (callback) {
var sel = document.createElement('div');
document.body.appendChild(sel);
sel.setAttribute('style', 'outline: #000 3px solid; background: #fff; opacity: 0.5; position: absolute; display: none;');
var down = false;
function onmousedown (e) {
e.preventDefault();
e.stopPropagation();
sel.style.left = e.pageX + "px";
sel.style.top = e.pageY + "px";
sel.style.width = "0";
sel.style.height = "0";
sel._x = e.pageX;
sel._y = e.pageY;
sel._w = sel._h = 0;
down = true;
sel.style.display = "block";
}
function onmousemove (e) {
if (!down) return;
e.preventDefault();
e.stopPropagation();
var dx = e.pageX - sel._x;
var dy = e.pageY - sel._y;
if (dy < 0) sel.style.top = sel._y + dy + 'px';
if (dx < 0) sel.style.left = sel._x + dx + 'px';
sel._w = Math.abs(dx);
sel._h = Math.abs(dy);
sel.style.width = sel._w + 'px';
sel.style.height = sel._h + 'px';
var ax = sel.offsetLeft, ay = sel.offsetTop;
var aw = sel._w, ah = sel._h;
var targets = findLinksByArea(ax, ay, aw, ah);
}
function onmouseup (e) {
if (!down) return;
e.preventDefault();
e.stopPropagation();
var targets = [];
var ax = sel.offsetLeft, ay = sel.offsetTop;
var aw = sel._w, ah = sel._h;
var targets = findLinksByArea(ax, ay, aw, ah);
window.removeEventListener("mousedown", onmousedown, true);
window.removeEventListener("mousemove", onmousemove, true);
window.removeEventListener("mouseup", onmouseup, true);
try {
callback(targets);
} catch (e) {
alert(e);
}
sel.parentNode.removeChild(sel);
}
function findLinksByArea (ax, ay, aw, ah) {
var ret = [];
var links = document.getElementsByTagName("a");
for (var i = 0, len = links.length; i < len; i++) {
var n = links[i];
var bx = offset('Left', n), by = offset('Top', n);
var bw = n.offsetWidth, bh = n.offsetHeight;
if ((ax <= bx + bw) &&
(bx <= ax + aw) &&
(ay <= by + bh) &&
(by <= ay + ah)) {
n.style.outline = '2px solid red';
ret.push(n.href);
} else {
n.style.outline = '';
}
}
return ret;
}
function offset(dir, e) {
var ret = 0;
do {
ret += e['offset' + dir];
} while ((e = e.offsetParent));
return ret;
}
window.addEventListener("mousedown", onmousedown, true);
window.addEventListener("mousemove", onmousemove, true);
window.addEventListener("mouseup", onmouseup, true);
}