aboutsummaryrefslogtreecommitdiffhomepage
path: root/examples/scripts/linkfollow.js
blob: e77219c8f14026319c50fb8c7346d9fbdb22a8ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// link follower for uzbl
// requires http://github.com/DuClare/uzbl/commit/6c11777067bdb8aac09bba78d54caea04f85e059
//
// first, it needs to be loaded before every time it is used.
// One way would be to use the load_commit_handler:
// set load_commit_handler = sh 'echo "act script /usr/share/uzbl/examples/scripts/linkfollow.js" > "$4"'
//
// when script is loaded, it can be invoked with
// bind f* = js hints.set("%s",   hints.open)
// bind f_ = js hints.follow("%s",hints.open)
//
// At the moment, it may be useful to have way of forcing uzbl to load the script
// bind :lf = script /usr/share/examples/scripts/linkfollow.js
//
// The default style for the hints are pretty ugly, so it is recommended to add the following
// to config file
// set stylesheet_uri = /usr/share/uzbl/examples/data/style.css
//
// based on follow_Numbers.js
//
// TODO: fix styling for the first element
// TODO: emulate mouseover events when visiting some elements
// TODO: rewrite the element->action handling


function Hints(){


  // if set to true, you must explicitly call hints.follow(), otherwise it will
  // follow the link if there is only one matching result
  var requireReturn = true;

  var uzblid = 'uzbl_hint';
  var uzblclass = 'uzbl_highlight';
  var uzblclassfirst = 'uzbl_h_first';
  var doc = document;
  var visible = [];
  var hintdiv;

  this.set = hint;
  this.follow = follow;
  this.keyPressHandler = keyPressHandler;

  function elementPosition(el) {
    var up = el.offsetTop;
    var left = el.offsetLeft; var width = el.offsetWidth;
    var height = el.offsetHeight;

    while (el.offsetParent) {
      el = el.offsetParent;
      up += el.offsetTop;
      left += el.offsetLeft;
    }
    return {up: up, left: left, width: width, height: height};
  }

  function elementInViewport(p) {
    return  (p.up < window.pageYOffset + window.innerHeight && 
            p.left < window.pageXOffset + window.innerWidth && 
            (p.up + p.height) > window.pageYOffset && 
            (p.left + p.width) > window.pageXOffset);
  }

  function isVisible(el) {
    if (el == doc) { return true; }
    if (!el) { return false; }
    if (!el.parentNode) { return false; }
    if (el.style) {
      if (el.style.display == 'none') {
          return false;
      }
      if (el.style.visibility == 'hidden') {
          return false;
      }
    }
    return isVisible(el.parentNode);
  }

  // the vimperator defaults minus the xhtml elements, since it gave DOM errors
  var hintable = " //*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @class='lk' or @role='link' or @href] | //input[not(@type='hidden')] | //a | //area | //iframe | //textarea | //button | //select";

  function Matcher(str){
    var numbers = str.replace(/[^\d]/g,"");
    var words = str.replace(/\d/g,"").split(/\s+/).map(function (n) { return new RegExp(n,"i")});
    this.test = test;
    this.toString = toString;
    this.numbers = numbers;
    function test(element) {
      // test all the regexp
      return words.every(function (regex) { return element.node.textContent.match(regex)});
    }
  }

  function HintElement(node,pos){

    this.node = node;
    this.isHinted = false;
    this.position = pos;
    this.num = 0;

    this.addHint = function (labelNum) {
      // TODO: fix uzblclassfirst
      if(!this.isHinted){
        this.node.className += " " + uzblclass;
      }
      this.isHinted = true;
        
      // create hint  
      var hintNode = doc.createElement('div');
      hintNode.name = uzblid;
      hintNode.innerText = labelNum;
      hintNode.style.left = this.position.left + 'px';
      hintNode.style.top =  this.position.up + 'px';
      hintNode.style.position = "absolute";
      doc.body.firstChild.appendChild(hintNode);
        
    }
    this.removeHint = function(){
      if(this.isHinted){
        var s = (this.num)?uzblclassfirst:uzblclass;
        this.node.className = this.node.className.replace(new RegExp(" "+s,"g"),"");
        this.isHinted = false;
      }
    }
  }

  function createHintDiv(){
    var hintdiv = doc.getElementById(uzblid);
    if(hintdiv){
      hintdiv.parentNode.removeChild(hintdiv);
    }
    hintdiv = doc.createElement("div");
    hintdiv.setAttribute('id',uzblid);
    doc.body.insertBefore(hintdiv,doc.body.firstChild);
    return hintdiv;
  }

  function init(){
    // WHAT?
    doc.body.setAttribute("onkeyup","hints.keyPressHandler(event)");
    hintdiv = createHintDiv();
    visible = [];

    var items = doc.evaluate(hintable,doc,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
    for (var i = 0;i<items.snapshotLength;i++){
      var item = items.snapshotItem(i);
      var pos = elementPosition(item);
      if(isVisible && elementInViewport(elementPosition(item))){
        visible.push(new HintElement(item,pos));
      }
    }
  }

  function clear(){

    visible.forEach(function (n) { n.removeHint(); } );
    hintdiv = doc.getElementById(uzblid);
    while(hintdiv){
      hintdiv.parentNode.removeChild(hintdiv);
      hintdiv = doc.getElementById(uzblid);
    }
  }

  function update(str,openFun) {
    var match = new Matcher(str);
    hintdiv = createHintDiv();
    var i = 1;
    visible.forEach(function (n) {
      if(match.test(n)) {
        n.addHint(i);
        i++;
      } else {
        n.removeHint();
      }});
    if(!requireReturn){
      if(i==2){ //only been incremented once
        follow(str,openFun);
      }
    }
  }

  function hint(str,openFun){
    if(str.length == 0) init();
    update(str,openFun);
  }

  function keyPressHandler(e) {
    var kC = window.event ? event.keyCode: e.keyCode;
    var Esc = window.event ? 27 : e.DOM_VK_ESCAPE;
    if (kC == Esc) {
        clear();
        doc.body.removeAttribute("onkeyup");
    }
  }

  this.openNewWindow = function(item){
    // TODO: this doesn't work yet
    window.open(item.href,"uzblnew","");
  }
  this.open = function(item){
    simulateMouseOver(item);
    window.location = item.href;
  }

  function simulateMouseOver(item){
    var evt = doc.createEvent("MouseEvents");
    evt.initMouseEvent("MouseOver",true,true,
        doc.defaultView,1,0,0,0,0,
        false,false,false,false,0,null);
    return item.dispatchEvent(evt);
  }


  function follow(str,openFunction){
    var m = new Matcher(str);
    var items = visible.filter(function (n) { return n.isHinted });
    clear();
    var num = parseInt(m.numbers,10);
    if(num){
      var item = items[num-1].node;
    } else {
      var item = items[0].node;
    }
    if (item) {
      // This causes some elements to move around. Guess it should only be applied to
      // links
      item.style.margin -= 3;
      item.style.padding -= 3;
      item.style.borderStyle = "dotted";
      item.style.borderWidth = "thin";

      var name = item.tagName;
      if (name == 'A') {
        if(item.click) {item.click()};
          openFunction(item);
      } else if (name == 'INPUT') {
        var type = item.getAttribute('type').toUpperCase();
        if (type == 'TEXT' || type == 'FILE' || type == 'PASSWORD') {
            item.focus();
            item.select();
        } else {
            item.click();
        }
      } else if (name == 'TEXTAREA' || name == 'SELECT') {
        item.focus();
        item.select();
      } else {
        item.click();
        openFunction(item);
      }
    }
  }
}

var hints = new Hints();

// vim:set et sw=2: