PageSourceSearch

https://everlasting.nu/static/widgets/likes.js

js everlasting.nu collected 2026-09-27 01:10:44 UTC 12,202 bytes, 318 lines download raw bytes

1
2
3(function() {
4    
5    var scriptFileName = '/static/widgets/likes.js';
6    
7    var scriptBase = (function() {
8        return document.location.protocol + "//" + document.location.host;
9    })();
10    
11    var Config = {
12        // js: {
13        //     current_user: scriptBase + '/api/current_user.jsonp'
14        // },
15        css: scriptBase + '/static/widgets/likewidget.css',
16        debug: false
17    };
18
19    if ( !window.BSELikes ) {
20        // Setup likes object, import css and attach document/ready event handler
21        window.BSELikes = {loaded: true, 
22                            debug: Config.debug,
23                            cache: [],
24                            entries: [],
25                            more_entries: function() {
26                                debug_log("more_entries()");
27                                fix_script_tags();
28                                load_likes();
29                            }
30                        };
31
32        if (window.BSEIgnoreLikeCSS != true) {
33            var head = document.getElementsByTagName('head')[0];
34            var link = document.createElement('link');
35            link.rel = 'stylesheet';
36            link.type = 'text/css';
37            link.href = Config.css;
38            head.appendChild(link);
39        }
40
41        if ( document.addEventListener ) {
42            debug_log("addEventListener: DOMContentLoaded()");
43            document.addEventListener( "DOMContentLoaded", function(){
44                debug_log("DOMContentLoaded() fired!");
45                document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
46                load_likes();
47            }, false);
48        } else if ( document.attachEvent ) {
49            debug_log("addEventListener: onreadystatechange()");
50            document.attachEvent("onreadystatechange", function(){
51                debug_log("addEventListener: onreadystatechange() readyState == " + document.readyState);
52                if ( document.readyState === "complete" ) {
53                    document.detachEvent( "onreadystatechange", arguments.callee );
54                    load_likes();
55                }
56            });
57        } else {
58            window.addEventListener('load', load_likes, false )
59        }
60
61        window.onload = function() {
62            debug_log("window.onload() fired!")
63            load_likes();
64        }
65    }
66
67
68
69    function init_container(scriptTag) {
70        var container = document.createElement("div"),
71            id = scriptTag.getAttribute("data-entryid");
72        container.id = "like-" + scriptTag.getAttribute("data-entryid");
73        container.className = "like-container";
74        container.style.display = "inline-block";
75        insertAfter(scriptTag, container);
76
77        window.BSELikes.entries.push({'entryid': id, 'timestamp': scriptTag.getAttribute('data-timestamp')});
78
79        var div = document.createElement("div"),
80            theme = scriptTag.getAttribute("data-theme") ? " likebtn_theme_" + scriptTag.getAttribute("data-theme") : "",
81            size = scriptTag.getAttribute("data-size") ? " likebtn_size_" + scriptTag.getAttribute("data-size") : "",
82            bubblepos = scriptTag.getAttribute("data-bubblepos") ? " likebtn_pos_" + scriptTag.getAttribute("data-bubblepos") : "";
83        div.className = "likebtn" + theme + size + bubblepos; // + scriptTag.className.replace('likewidget', '');
84        var span = document.createElement("span");
85        span.className = "likebtn__count not_loaded";
86        span.innerHTML = "0";
87
88        div.appendChild(span);
89
90        var link = document.createElement("a");
91        link.className = "likebtn__btn";
92        link.setAttribute('href', '#');
93        link.setAttribute('title', 'Gilla inlägget');
94        link.innerHTML = "Gilla";
95
96        div.appendChild(link);
97
98        debug_log("Adding event listener for a-tag " + id);
99        link.addEventListener('click', like_clickhandler, false);
100        container.appendChild(div);
101    }
102
103
104    function fetchData(entries) {
105        debug_log("Fetching data for entries: ", entries);
106        var month_arr = {}, cached_entries = {};
107        for (entry in entries) {
108            var id = entries[entry].entryid,
109                ts = new Date(entries[entry].timestamp*1000),
110                ts_str = ts.toISOString().substr(0,4) + "/" + ts.toISOString().substr(5,2),
111                cached = false;
112
113            for (ce in window.BSELikes.cache) {
114                if (window.BSELikes.cache[ce].entryid == id) {
115                    debug_log("Entryid "+id+" already in cache, skipping...");
116                    cached = true;
117                    cached_entries[id] = window.BSELikes.cache[ce].likes;
118                    break;
119                }
120            }
121            if (!cached && (!month_arr[ ts_str ] || month_arr[ ts_str ] > entries[entry].timestamp)) {
122                month_arr[ ts_str ] = entries[entry].timestamp;
123            }
124        }
125        if (Object.keys(cached_entries).length > 0) {
126            debug_log("Drawing cached likes: ", cached_entries);
127            drawLikes(cached_entries);
128        }
129
130        debug_log("Months needed to fetch likes for: ", month_arr);
131
132        for (month in month_arr) {
133            debug_log('Fetching /_mobile/likes/' + month + '/' +month_arr[month]);
134            loadJSON('/_mobile/likes/' + month + '/' +month_arr[month], function(data) {
135                debug_log('Result from /_mobile/likes/' + month + '/' +month_arr[month] + "': " + data.count + " entries returned (last_ts: " + data.last_ts + ")");
136                for (entryid in data.entries) {
137                    debug_log("Caching entry => Entryid: " + entryid + ", likes: " + data.entries[entryid]);
138                    window.BSELikes.cache.push({entryid: entryid, likes: data.entries[entryid]});
139                }
140
141                // We received new likes data from server, time to update browser with stuff!
142                if (window.BSELikes.entries) {
143                    drawLikes(data.entries);
144                }
145            });
146        }
147    }
148
149    function drawLikes(entries) {
150        // Update the entries stores in BSELikes.entries with cached result!
151        for (entry in entries) {
152            var entryid = entry, //entries[entry].entryid,
153                likes = entries[entry];
154            // if (window.BSELikes.cache[entryid]) 
155            //     likes = window.BSELikes.cache[entryid].likes;
156
157            // for (e in window.BSELikes.cache) {
158            //     if (window.BSELikes.cache[e].entryid == entryid) {
159            //         likes = window.BSELikes.cache[e].likes;
160            //         break;
161            //     }
162            // }
163
164            debug_log("DRAWING entry => entryid: " + entryid + ", likes: " + likes);
165            var container = document.getElementById("like-" + entryid);
166            if (container) {
167                var ticker = container.getElementsByClassName("likebtn__count")[0];
168                ticker.setAttribute("data-likes", likes);
169                ticker.className = ticker.className.replace(" not_loaded", "");
170                ticker.innerHTML = likes;
171            }
172        }
173    }
174
175    function like_clickhandler(e) {
176        e.preventDefault();
177
178        debug_log("Like button clicked");
179        var el = e.srcElement ? e.srcElement : e.currentTarget;
180        if (el.nodeName == 'A') el = el.parentNode;
181        entryid = el.parentNode.getAttribute("id").replace("like-", "");
182        if (el.className.indexOf('liked') == -1) {
183            debug_log("Add like for entry " + entryid);
184            el.className = el.className.replace(" unliked", "") + " liked";
185            loadJSON('/_like/'+entryid+'/add.json', function(res) {
186                if (res.success) {
187                    var ticker = el.getElementsByClassName("likebtn__count")[0],
188                        likes = parseInt(ticker.getAttribute("data-likes") ? ticker.getAttribute("data-likes") : 0) + 1;
189
190                    ticker.setAttribute("data-likes", likes);
191                    ticker.innerHTML = likes;
192                    ticker.className = ticker.className.replace(" not_loaded", "");
193                }
194            });
195        } else {
196            debug_log("Remove like for entry " + entryid);
197            el.className = el.className.replace(" liked", "") + " unliked";
198            loadJSON('/_like/'+entryid+'/remove.json', function(res) {
199                if (res.success) {
200                    var ticker = el.getElementsByClassName("likebtn__count")[0],
201                         likes = parseInt(ticker.getAttribute("data-likes") ? ticker.getAttribute("data-likes") : 0) - 1;
202                    if (likes < 1) likes = 0;
203                    ticker.setAttribute("data-likes", likes);
204                    ticker.innerHTML = likes;
205                }
206            });
207        }
208        return false;
209    }
210
211    function fix_script_tags() {
212        var scripts = document.getElementsByClassName('likewidget');
213        for ( var i = scripts.length-1, script; script = scripts[i]; i-- ) {
214            debug_log("Script found: " + script)
215            init_container(script);
216            script.className = "";
217        }
218    }
219
220    function load_likes() {
221        debug_log("load_likes() (loading " + window.BSELikes.entries.length + " entries)");
222        // On document/ready this function executes to load likes data and populate containers.
223        if (window.BSELikes.entries.length) {
224            fetchData(window.BSELikes.entries);
225            window.BSELikes.entries = [];
226        }
227    }
228
229    fix_script_tags();
230
231
232
233    // Some helper functions follow
234    function insertAfter(referenceNode, newNode) {
235        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
236    }
237
238    function debug_log() {
239        if (!window.BSELikes.debug) return;
240        console.log("LIKES/LOG", arguments);
241    }
242
243    var JSONP = (function(){
244    	var head, query, key, window = this;
245
246    	function load(url) {
247    		var script = document.createElement('script'), done = false;
248    		script.src = url;
249    		script.async = true;
250
251    		script.onload = script.onreadystatechange = function() {
252    			if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
253    				done = true;
254    				script.onload = script.onreadystatechange = null;
255    				if ( script && script.parentNode ) {
256    					script.parentNode.removeChild( script );
257    				}
258    			}
259    		};
260    		if ( !head )
261    			head = document.getElementsByTagName('head')[0];
262    		head.appendChild( script );
263    	}
264    	function jsonp(url, params, callback) {
265    		query = "?";
266    		params = params || {};
267    		for ( key in params )
268    			if ( params.hasOwnProperty(key) )
269    				query += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
270    		var jsonp = "callback_" + (((1 + Math.random()) * 0x10000) | 0).toString(32);
271    		window[ jsonp ] = function(data){
272    			callback(data);
273    			try {
274    				delete window[ jsonp ];
275    			} catch (e) {}
276    			window[ jsonp ] = null;
277    		};
278
279    		load(url + query + "callback=" + jsonp);
280    		return jsonp;
281    	}
282    	return {get: jsonp};
283    })();
284
285    function loadJSON(url, callback)
286    {
287       var http_request = new XMLHttpRequest();
288       try{
289          // Opera 8.0+, Firefox, Chrome, Safari
290          http_request = new XMLHttpRequest();
291       }catch (e){
292          // Internet Explorer Browsers
293          try{
294             http_request = new ActiveXObject("Msxml2.XMLHTTP");
295          }catch (e) {
296             try{
297                http_request = new ActiveXObject("Microsoft.XMLHTTP");
298             }catch (e){
299                // Something went wrong
300                // alert("Your browser broke!");
301                return false;
302             }
303          }
304       }
305       http_request.onreadystatechange  = function(){
306          if (http_request.readyState == 4  )
307          {
308            // Javascript function JSON.parse to parse JSON data
309            var jsonObj = JSON.parse(http_request.responseText);
310            callback(jsonObj);
311          }
312       }
313       http_request.open("GET", url, true);
314       http_request.send();
315    }
316})();
317
318

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.