]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LinkPreview/linkpreview.js
Merge branch 'master' into 0.9.x
[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: 'http://oohembed.com/oohembed',
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     var LinkPreview = {
78         links: [],
79         state: [],
80         refresh: [],
81
82         /**
83          * Find URL links from the source text that may be interesting.
84          *
85          * @param {String} text
86          * @return {Array} list of URLs
87          */
88         findLinks: function (text)
89         {
90             // @fixme match this to core code
91             var re = /(?:^| )(https?:\/\/.+?\/.+?)(?= |$)/mg;
92             var links = [];
93             var matches;
94             while ((matches = re.exec(text)) !== null) {
95                 links.push(matches[1]);
96             }
97             return links;
98         },
99
100         /**
101          * Start looking up info for a link preview...
102          * May start async data loads.
103          *
104          * @param {number} col: column number to insert preview into
105          */
106         prepLinkPreview: function(col)
107         {
108             var id = 'link-preview-' + col;
109             var url = LinkPreview.links[col];
110             LinkPreview.refresh[col] = false;
111             LinkPreview.markLoading(col);
112
113             oEmbed.lookup(url, function(data) {
114                 var thumb = null;
115                 var width = 100;
116                 if (data && typeof data.thumbnail_url == "string") {
117                     thumb = data.thumbnail_url;
118                     if (typeof data.thumbnail_width !== "undefined") {
119                         if (data.thumbnail_width < width) {
120                             width = data.thumbnail_width;
121                         }
122                     }
123                 } else if (data && data.type == 'photo' && typeof data.url == "string") {
124                     thumb = data.url;
125                     if (typeof data.width !== "undefined") {
126                         if (data.width < width) {
127                             width = data.width;
128                         }
129                     }
130                 }
131
132                 if (thumb) {
133                     var link = $('<span class="inline-attachment"><a><img/></a></span>');
134                     link.find('a')
135                             .attr('href', url)
136                             .attr('target', '_blank')
137                             .last()
138                         .find('img')
139                             .attr('src', thumb)
140                             .attr('width', width)
141                             .attr('title', data.title || data.url || url);
142                     $('#' + id).empty();
143                     $('#' + id).append(link);
144                 } else {
145                     // No thumbnail available or error retriving it.
146                     LinkPreview.clearLink(col);
147                 }
148
149                 if (LinkPreview.refresh[col]) {
150                     // Darn user has typed more characters.
151                     // Go fetch another link!
152                     LinkPreview.prepLinkPreview(col);
153                 } else {
154                     LinkPreview.markDone(col);
155                 }
156             });
157         },
158
159         /**
160          * Update the live preview section with links found in the given text.
161          * May start async data loads.
162          *
163          * @param {String} text: free-form input text
164          */
165         previewLinks: function(text)
166         {
167             var i;
168             var old = LinkPreview.links;
169             var links = LinkPreview.findLinks(text);
170             LinkPreview.links = links;
171
172             // Check for existing common elements...
173             for (i = 0; i < old.length && i < links.length; i++) {
174                 if (links[i] != old[i]) {
175                     if (LinkPreview.state[i] == "loading") {
176                         // Slate this column for a refresh when this one's done.
177                         LinkPreview.refresh[i] = true;
178                     } else {
179                         // Change an existing entry!
180                         LinkPreview.prepLinkPreview(i);
181                     }
182                 }
183             }
184             if (links.length > old.length) {
185                 // Adding new entries, whee!
186                 for (i = old.length; i < links.length; i++) {
187                     LinkPreview.addPreviewArea(i);
188                     LinkPreview.prepLinkPreview(i);
189                 }
190             } else if (old.length > links.length) {
191                 // Remove preview entries for links that have been removed.
192                 for (i = links.length; i < old.length; i++) {
193                     LinkPreview.clearLink(i);
194                 }
195             }
196         },
197
198         addPreviewArea: function(col) {
199             var id = 'link-preview-' + col;
200             $('#link-preview').append('<span id="' + id + '"></span>');
201         },
202
203         clearLink: function(col) {
204             var id = 'link-preview-' + col;
205             $('#' + id).html('');
206         },
207
208         markLoading: function(col) {
209             LinkPreview.state[col] = "loading";
210             var id = 'link-preview-' + col;
211             $('#' + id).attr('style', 'opacity: 0.5');
212         },
213
214         markDone: function(col) {
215             LinkPreview.state[col] = "done";
216             var id = 'link-preview-' + col;
217             $('#' + id).removeAttr('style');
218         },
219
220         /**
221          * Clear out any link preview data.
222          */
223         clear: function() {
224             LinkPreview.links = [];
225             $('#link-preview').empty();
226         }
227     };
228
229     SN.Init.LinkPreview = function(params) {
230         if (params.api) oEmbed.api = params.api;
231         if (params.width) oEmbed.width = params.width;
232         if (params.height) oEmbed.height = params.height;
233
234         $('#form_notice')
235             .append('<div id="link-preview" class="thumbnails"></div>')
236             .bind('reset', function() {
237                 LinkPreview.clear();
238             });
239
240         // Piggyback on the counter update...
241         var origCounter = SN.U.Counter;
242         SN.U.Counter = function(form) {
243             LinkPreview.previewLinks($('#notice_data-text').val());
244             return origCounter(form);
245         }
246     }
247 })();