aboutsummaryrefslogtreecommitdiffstats
path: root/highlight.js
blob: 60dda0424c38e853b2d7139fbce47c62a1f1f319 (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
/*
 * ==VimperatorPlugin==
 * @name            highlight.js
 * @description     Factory for the object to highlight specified element[s]. this set in plugins.highlighterFactory.
 * @description-ja  指定した要素をハイライトするオブジェクトを返す Factory 。 plugins.highlighterFactory に構築される。
 * @author          janus_wel <janus_wel@fb3.so-net.ne.jp>
 * @version         0.11
 * @minversion      2.0pre 2008/10/16
 * ==/VimperatorPlugin==
 *
 * LICENSE
 *  New BSD License
 *
 * USAGE
 *  plugins.highlighterFactory() return the object to highlight element[s].
 *  arguments is object that have below properties.
 *      color:    color name that define by css or RGB format ( #xxxxxx ),
 *      opacity:  opacity for -moz-opacity property in css.
 *      interval: interval to blink ( unit: msec ). if 0 specified, not blink.
 *
 *  returned object has 3 methods.
 *      set:            setter that accept object have above properties.
 *      highlight:      method to highlight specified element.
 *      unhighlightAll: unhighlight all.
 *
 *  highlight is implement by "div" element that have style "position: absolute;".
 *  it has class name "vimp_plugin_highlightelement", so you should use buffer.evaluateXPath
 *  with query that like '//div[contains(concat(" ", @class, " "), " vimp_plugin_highlightelement ")]'
 *  when you want to process elements to highlight.
 *
 * EXAMPLE
 *  let h = plugins.highlighterFactory({
 *      color:    '#0080ff',
 *      opacity:  0.7,
 *      interval: 0,
 *  );
 *  h.highlight(content.document.getElementsByTagName('A'));
 *  h.unhighlightAll();
 *
 * TODO
 *  need valid English.
 * */

( function () {

const fixedStyle = [
    'position: absolute;',
    'display:  block;',
    'z-index:  2147483647;',
].join('');

// class definition
function Highlighter() {
    this._initialize.apply(this, arguments);
}
Highlighter.prototype = {
    _initialize: function (args) {
        if (args) this.set(args);
        this.highlightList = [];
    },

    set: function (args) {
        this.color    = args.color;
        this.opacity  = args.opacity;
        this.interval = args.interval;

        this._prepareTemplate();

        return this;
    },

    _prepareTemplate: function () {
        let div = window.document.createElement('div');
        div.className = 'vimp_plugin_highlightelement';

        let style = fixedStyle + [
            'background-color: ' + this.color + ';',
            '-moz-opacity: ' + this.opacity + ';'
        ].join('');
        div.setAttribute('style', style);

        this._highlightTemplate = div;
    },

    highlight: function (element) {
        if (!this._isDisplay(element)) return;

        let doc = element.ownerDocument;

        // TODO: highlight XUL elements
        if (!doc.body) return;

        let scrollX = doc.defaultView.scrollX;
        let scrollY = doc.defaultView.scrollY;

        let rects = element.getClientRects();
        for (let i=0, l=rects.length ; i<l ; ++i) {
            let r = rects[i];
            let h = this._buildHighlighter({
                top:    r.top + scrollY,
                left:   r.left + scrollX,
                width:  r.right - r.left,
                height: r.bottom - r.top,
            });
            this.highlightList.push(h);
            doc.body.appendChild(h);
        }
    },

    _unhighlight: function (element) {
        if (element.intervalId) clearInterval(element.intervalId);
        element.parentNode.removeChild(element);
    },

    unhighlightAll: function () {
        let list = this.highlightList;
        while (list.length) this._unhighlight(list.pop());
    },

    _isDisplay: function (element) {
        let computedStyle = content.document.defaultView.getComputedStyle(element, null);
        return (   computedStyle.getPropertyValue('visibility') !== 'hidden'
                && computedStyle.getPropertyValue('display')    !== 'none');
    },

    _buildHighlighter: function (rect) {
        let div = this._highlightTemplate.cloneNode(false);
        div.style.top    = rect.top + 'px';
        div.style.left   = rect.left + 'px';
        div.style.width  = rect.width + 'px';
        div.style.height = rect.height + 'px';

        if (this.interval > 0) {
            div.intervalId = setInterval(
                function () {
                    let d = div.style.display;
                    div.style.display = (d === 'block' ? 'none' : 'block');
                },
                this.interval
            );
        }
        else {
            div.intervalId = undefined;
        }

        return div;
    },
};

if (!plugins.highlighterFactory) {
    plugins.highlighterFactory = function () {
        let h = new Highlighter();
        return h.set.apply(h, arguments);
    }
}

} )();

// vim: set sw=4 ts=4 et;
an>, displayDelay: 500, }; //////////////////////////////////////////////////////////////// // setting //////////////////////////////////////////////////////////////// let _gv; // 評価を遅延するために関数にしておく function gv () { if (_gv) return _gv; if (liberator.globalVariables) { if (!liberator.globalVariables.autoDetectLink) liberator.globalVariables.autoDetectLink = {}; _gv = liberator.globalVariables.autoDetectLink; } for (let key in defaultSetting) { if (_gv[key] == undefined) _gv[key] = defaultSetting[key]; } return _gv; } const APPREF = 'greasemonkey.scriptvals.http://swdyh.yu.to//AutoPagerize.cacheInfo'; let ap_cache = eval(Application.prefs.getValue(APPREF, null)); for each (let cache in ap_cache) { cache.info = cache.info.filter(function (i) 'url' in i); cache.info.sort(function (a, b) b.url.length - a.url.length); } //////////////////////////////////////////////////////////////// // functions //////////////////////////////////////////////////////////////// // 空白を function removeSpace (str) str.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' '); // Array#find function find (ary, f) { var func = (typeof f == 'function') ? f : function (v) v == f; for (let i = 0, l = ary.length; i < l; i++) { if (func(ary[i])) { return ary[i]; } } return null; } // 要素をクリックする function clickElement (elem) buffer.followLink(elem); // 開いたURIなどの表示 function displayOpened (link) { var msg = 'open: ' + link.type + ' <' + removeSpace(link.text) + '> ' + link.uri; setTimeout(function () liberator.echo(msg, commandline.FORCE_SINGLELINE), gv().displayDelay); } // リンクを開く function open (link) { if (link.element) { clickElement(link.element); } else if (link.uri) { link.frame.location.href = link.uri; } displayOpened(link); } // 元の文字列、詰め込む文字、長さ function padChar (s, c, n) s.replace(new RegExp('^(.{0,'+(n-1)+'})$'), function (s) padChar(c+s, c, n)); // (次|前)の数字文字列リストを取得 function succNumber (n, next) { var m = (parseInt(n || 0, 10) + (next ? 1 : -1)).toString(); var result = [m]; if (m.length < n.length) result.unshift(padChar(m.toString(), '0', n.length)); return result; } // (次|前)の文字列リストを取得 function succString (s, next) { var result = [], d = next ? 1 : -1; var c = String.fromCharCode(s.charCodeAt(0) + d); if (('a' <= c && c <= 'z') || 'A' <= c && c <= 'Z') result.push(c); return result; } // (次|前)のURIリストを取得 function succURI (uri, next) { var urim = uri.match(/^(.+\/)([^\/]+)$/); if (!urim) return []; var [_, dir, file] = urim, result = []; // succ number let (dm, file = file, left = '', temp = []) { while (file && (dm = file.match(/\d+/))) { let [rcontext, lcontext, lmatch] = [RegExp.rightContext, RegExp.leftContext, RegExp.lastMatch]; left += lcontext; succNumber(lmatch, next).forEach(function (succ) { temp.push(dir + left + succ + rcontext); }); left += lmatch; file = rcontext; } result = result.concat(temp.reverse()); } // succ string let (dm, file = file, left = '', temp = []) { while (file && (dm = file.match(/(^|[^a-zA-Z])([a-zA-Z])([^a-zA-Z]|$)/))) { let [rcontext, lcontext] = [RegExp.rightContext, RegExp.leftContext]; left += lcontext + dm[1]; succString(dm[2], next).forEach(function (succ) { temp.push(dir + left + succ + dm[3] + rcontext); }); left += dm[1]; file = dm[3] + rcontext; } result = result.concat(temp.reverse()); } return result; } // パターンマッチング function match (pattern, link) pattern instanceof Function ? pattern(link) : !link.text ? null : pattern instanceof RegExp ? pattern.test(link.text) : link.text.toLowerCase().indexOf(pattern.toString().toLowerCase()) >= 0; // 要素が表示されているか? function isVisible (element) { var st; try { st = content.document.defaultView.getComputedStyle(element, null); return !(st.display && st.display.indexOf('none') >= 0) && (!element.parentNode || isVisible(element.parentNode)) } catch (e) { return true; } } // リンクのフィルタ function linkElementFilter (elem) isVisible(elem) && elem.href && elem.href.indexOf('@') < 0 && /^(?:(?:https?|f(?:ile|tp)):\/\/|javascript:)/.test(elem.href) && elem.textContent; // 全てのリンクを取得 // 再帰的にフレーム内のも取得する function getAllLinks (content) { var result = []; // Anchor var elements = content.document.links; for (let i = 0, l = elements.length; i < l; i++) { let it = elements[i]; if (linkElementFilter(it)) result.push({ type: 'link', frame: content, uri: it.href, rel: it.rel, text: it.textContent, element: it }); } // Form elements = content.document.getElementsByTagName('input'); for (let i = 0, l = elements.length; i < l; i++) { (function (input) { result.push({ type: 'input', frame: content, uri: input.form && input.form.action, text: input.value, click: input.click, element: input, }); })(elements[i]); } // Frame if (content.frames) { for (let i = 0, l = content.frames.length; i < l; i++) { result = result.concat(getAllLinks(content.frames[i])); } } return result; } // 全フレームの URL を得る function getAllLocations (content) { let result = [content.location.href]; if (content.frames) { for (let i = 0, l = content.frames.length; i < l; i++) { result = result.concat(getAllLocations(content.frames[i])); } } return result; } // 上書きした設定を返す。 function getCurrentSetting (setting) { if (!setting) setting = {}; for (let n in gv()) { if (setting[n] == undefined) setting[n] = gv()[n]; } return setting; } // 相対アドレスから絶対アドレスに変換するんじゃないの? function toAbsPath (path) { with (content.document.createElement('a')) return (href = path) && href; } // AutoPagerize のデータからマッチする物を取得 function getAutopagerizeNext () { if (!ap_cache) return; var info = (function () { var uri = buffer.URL; for each (let cache in ap_cache) { for (let i = 0, l = cache.info.length; i < l; i++) { let info = cache.info[i]; if (uri.match(info.url)) return info; } } })(); if (!info) return; var doc = content.document; var result = doc.evaluate(info.nextLink, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); if (result.singleNodeValue) return result.singleNodeValue; } //////////////////////////////////////////////////////////////// // main //////////////////////////////////////////////////////////////// // リンクを探す function detect (next, setting) { try { setting = getCurrentSetting(setting); // TODO if (setting.useAutoPagerize && next) { let apnext = getAutopagerizeNext(); if (apnext) { return { type: 'aplink', frame: content, uri: apnext.href || apnext.action || apnext.value, text: apnext.textContent || apnext.title || apnext, element: apnext }; } } patterns = next ? setting.nextPatterns : setting.backPatterns; let uri = window.content.location.href; let links = getAllLinks(window.content); // rel="prev|next" { let relValue = next ? /(?:^|[ \t\r\n])next(?:[ \t\n\r]|$)/ : /(?:^|[ \t\r\n])prev(?:[ \t\n\r]|$)/; let link = find(links, function (link) ((typeof link.rel == 'string') && relValue.test(link.rel.toLowerCase()))); if (link) return link; } // keywords { let link; if (patterns.some(function (pattern) { link = find(links, function (link) match(pattern, link)); return link ? true : false; })) return link; } // succ let succs = []; getAllLocations(window.content).forEach(function (uri) { succs = succs.concat(succURI(uri, next)); }); if (setting.useSuccPattern) { let link; if (succs.some(function (succ) { link = find(links, function (link) link.uri && (link.uri.indexOf(succ) >= 0)); return link ? true : false; })) return link; } // force if (setting.force && succs.length) { return { type: 'force', uri: succs[0], text: '-force-', frame: window.content, }; } } catch (e) { liberator.log(e); liberator.echoerr(e); } } // 猫又 function go (next, setting) { setting = getCurrentSetting(setting); if ((next && setting.useNextHistory) || (!next && setting.useBackHistory)) { next ? BrowserForward() : BrowserBack(); displayOpened({uri: 'history', text: next ? 'next' : 'back'}); return; } var link = detect(next, setting); if (link) open(link); } // 外部から使用可能にする。 if (liberator.plugins) liberator.plugins.autoDetectLink = {detect: detect, go: go}; //////////////////////////////////////////////////////////////// // Mappings //////////////////////////////////////////////////////////////// if (gv().nextMappings.length) { mappings.remove([modes.NORMAL], gv().nextMappings); mappings.addUserMap( [modes.NORMAL], gv().nextMappings, 'Go next', function () go(true) ); } if (gv().backMappings.length) { mappings.remove([modes.NORMAL], gv().backMappings); mappings.addUserMap( [modes.NORMAL], gv().backMappings, 'Go back', function () go(false) ); } liberator.log('auto_detect_link.js loaded'); })();