]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LinkPreview/linkpreview.js
Localisation updates from http://translatewiki.net.
[quix0rs-gnu-social.git] / plugins / LinkPreview / linkpreview.js
1 /**
2  * (c) 2010 StatusNet, Inc.
3  */
4
5 (function() {
6     /**
7      * Quickie wrapper around ooembed JSON lookup
8      */
9     var oEmbed = {
10         api: 'https://noembed.com/embed',
11         width: 100,
12         height: 75,
13         cache: {},
14         callbacks: {},
15
16         /**
17          * Do a cached oEmbed lookup for the given URL.
18          *
19          * @param {String} url
20          * @param {function} callback
21          */
22         lookup: function(url, callback)
23         {
24             if (typeof oEmbed.cache[url] == "object") {
25                 // We already have a successful lookup.
26                 callback(oEmbed.cache[url]);
27             } else if (typeof oEmbed.callbacks[url] == "undefined") {
28                 // No lookup yet... Start it!
29                 oEmbed.callbacks[url] = [callback];
30
31                 oEmbed.rawLookup(url, function(data) {
32                     oEmbed.cache[url] = data;
33                     var callbacks = oEmbed.callbacks[url];
34                     oEmbed.callbacks[url] = undefined;
35                     for (var i = 0; i < callbacks.length; i++) {
36                         callbacks[i](data);
37                     }
38                 });
39             } else {
40                 // A lookup is in progress.
41                 oEmbed.callbacks[url].push(callback);
42             }
43         },
44
45         /**
46          * Do an oEmbed lookup for the given URL.
47          *
48          * @fixme proxy through ourselves if possible?
49          * @fixme use the global thumbnail size settings
50          *
51          * @param {String} url
52          * @param {function} callback
53          */
54         rawLookup: function(url, callback)
55         {
56             var params = {
57                 url: url,
58                 format: 'json',
59                 maxwidth: oEmbed.width,
60                 maxheight: oEmbed.height,
61                 token: $('#token').val()
62             };
63             $.ajax({
64                 url: oEmbed.api,
65                 data: params,
66                 dataType: 'json',
67                 success: function(data, xhr) {
68                     callback(data);
69                 },
70                 error: function(xhr, textStatus, errorThrown) {
71                     callback(null);
72                 }
73             });
74         }
75     };
76
77     SN.Init.LinkPreview = function(params) {
78         if (params.api) oEmbed.api = params.api;
79         if (params.width) oEmbed.width = params.width;
80         if (params.height) oEmbed.height = params.height;
81     }
82
83     // Piggyback on the counter update...
84     var origCounter = SN.U.Counter;
85     SN.U.Counter = function(form) {
86         var preview = form.data('LinkPreview');
87         if (preview) {
88             preview.previewLinks(form.find('.notice_data-text:first').val());
89         }
90         return origCounter(form);
91     }
92
93     // Customize notice form init...
94     var origSetup = SN.Init.NoticeFormSetup;
95     SN.Init.NoticeFormSetup = function(form) {
96         origSetup(form);
97
98         form
99             .bind('reset', function() {
100                 LinkPreview.clear();
101             });
102
103         var LinkPreview = {
104             links: [],
105             state: [],
106             refresh: [],
107
108             /**
109              * Find URL links from the source text that may be interesting.
110              *
111              * @param {String} text
112              * @return {Array} list of URLs
113              */
114             findLinks: function (text)
115             {
116                 // @fixme match this to core code
117                 var re = /(?:^| )(https?:\/\/.+?\/.+?)(?= |$)/mg;
118                 var links = [];
119                 var matches;
120                 while ((matches = re.exec(text)) !== null) {
121                     links.push(matches[1]);
122                 }
123                 return links;
124             },
125
126             ensureArea: function() {
127                 if (form.find('.link-preview').length < 1) {
128                     form.append('<div class="notice-status link-preview thumbnails"></div>');
129                 }
130             },
131
132             /**
133              * Start looking up info for a link preview...
134              * May start async data loads.
135              *
136              * @param {number} col: column number to insert preview into
137              */
138             prepLinkPreview: function(col)
139             {
140                 var id = 'link-preview-' + col;
141                 var url = LinkPreview.links[col];
142                 LinkPreview.refresh[col] = false;
143                 LinkPreview.markLoading(col);
144
145                 oEmbed.lookup(url, function(data) {
146                     var thumb = null;
147                     var width = 100;
148                     if (data && typeof data.thumbnail_url == "string") {
149                         thumb = data.thumbnail_url;
150                         if (typeof data.thumbnail_width !== "undefined") {
151                             if (data.thumbnail_width < width) {
152                                 width = data.thumbnail_width;
153                             }
154                         }
155                     } else if (data && data.type == 'photo' && typeof data.url == "string") {
156                         thumb = data.url;
157                         if (typeof data.width !== "undefined") {
158                             if (data.width < width) {
159                                 width = data.width;
160                             }
161                         }
162                     }
163
164                     if (thumb) {
165                         LinkPreview.ensureArea();
166                         var link = $('<span class="inline-attachment"><a><img/></a></span>');
167                         link.find('a')
168                                 .attr('href', url)
169                                 .attr('target', '_blank')
170                                 .last()
171                             .find('img')
172                                 .attr('src', thumb)
173                                 .attr('width', width)
174                                 .attr('title', data.title || data.url || url);
175                         form.find('.' + id)
176                             .empty()
177                             .append(link);
178                     } else {
179                         // No thumbnail available or error retriving it.
180                         LinkPreview.clearLink(col);
181                     }
182
183                     if (LinkPreview.refresh[col]) {
184                         // Darn user has typed more characters.
185                         // Go fetch another link!
186                         LinkPreview.prepLinkPreview(col);
187                     } else {
188                         LinkPreview.markDone(col);
189                     }
190                 });
191             },
192
193             /**
194              * Update the live preview section with links found in the given text.
195              * May start async data loads.
196              *
197              * @param {String} text: free-form input text
198              */
199             previewLinks: function(text)
200             {
201                 var i;
202                 var old = LinkPreview.links;
203                 var links = LinkPreview.findLinks(text);
204                 LinkPreview.links = links;
205
206                 // Check for existing common elements...
207                 for (i = 0; i < old.length && i < links.length; i++) {
208                     if (links[i] != old[i]) {
209                         if (LinkPreview.state[i] == "loading") {
210                             // Slate this column for a refresh when this one's done.
211                             LinkPreview.refresh[i] = true;
212                         } else {
213                             // Change an existing entry!
214                             LinkPreview.prepLinkPreview(i);
215                         }
216                     }
217                 }
218                 if (links.length > old.length) {
219                     // Adding new entries, whee!
220                     for (i = old.length; i < links.length; i++) {
221                         LinkPreview.addPreviewArea(i);
222                         LinkPreview.prepLinkPreview(i);
223                     }
224                 } else if (old.length > links.length) {
225                     // Remove preview entries for links that have been removed.
226                     for (i = links.length; i < old.length; i++) {
227                         LinkPreview.clearLink(i);
228                     }
229                 }
230                 if (links.length == 0) {
231                     LinkPreview.clear();
232                 }
233             },
234
235             addPreviewArea: function(col) {
236                 LinkPreview.ensureArea();
237                 var id = 'link-preview-' + col;
238                 if (form.find('.' + id).length < 1) {
239                     form.find('.link-preview').append('<span class="' + id + '"></span>');
240                 }
241             },
242
243             clearLink: function(col) {
244                 var id = 'link-preview-' + col;
245                 form.find('.' + id).html('');
246             },
247
248             markLoading: function(col) {
249                 LinkPreview.state[col] = "loading";
250                 var id = 'link-preview-' + col;
251                 form.find('.' + id).attr('style', 'opacity: 0.5');
252             },
253
254             markDone: function(col) {
255                 LinkPreview.state[col] = "done";
256                 var id = 'link-preview-' + col;
257                 form.find('.' + id).removeAttr('style');
258             },
259
260             /**
261              * Clear out any link preview data.
262              */
263             clear: function() {
264                 LinkPreview.links = [];
265                 form.find('.link-preview').remove();
266             }
267         };
268         form.data('LinkPreview', LinkPreview);
269     }
270 })();