2016-06-15 02:31:51 +08:00
|
|
|
const localCache = {};
|
|
|
|
const failedCache = {};
|
|
|
|
|
2016-10-24 18:46:22 +08:00
|
|
|
// Perform a lookup of a onebox based an anchor element.
|
|
|
|
// It will insert a loading indicator and remove it when the loading is complete or fails.
|
2016-07-01 01:55:44 +08:00
|
|
|
export function load(e, refresh, ajax) {
|
2016-10-24 18:46:22 +08:00
|
|
|
const $elem = $(e);
|
2016-06-15 02:31:51 +08:00
|
|
|
|
2016-10-24 18:46:22 +08:00
|
|
|
// If the onebox has loaded or is loading, return
|
2016-06-15 02:31:51 +08:00
|
|
|
if ($elem.data('onebox-loaded')) return;
|
|
|
|
if ($elem.hasClass('loading-onebox')) return;
|
|
|
|
|
|
|
|
const url = e.href;
|
|
|
|
|
|
|
|
// Unless we're forcing a refresh...
|
|
|
|
if (!refresh) {
|
|
|
|
// If we have it in our cache, return it.
|
|
|
|
const cached = localCache[url];
|
|
|
|
if (cached) return cached;
|
|
|
|
|
|
|
|
// If the request failed, don't do anything
|
|
|
|
const failed = failedCache[url];
|
|
|
|
if (failed) return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add the loading CSS class
|
|
|
|
$elem.addClass('loading-onebox');
|
|
|
|
|
|
|
|
// Retrieve the onebox
|
2016-07-01 01:55:44 +08:00
|
|
|
return ajax("/onebox", {
|
2016-06-15 02:31:51 +08:00
|
|
|
dataType: 'html',
|
|
|
|
data: { url, refresh },
|
|
|
|
cache: true
|
|
|
|
}).then(html => {
|
|
|
|
localCache[url] = html;
|
|
|
|
$elem.replaceWith(html);
|
2016-10-24 18:46:22 +08:00
|
|
|
}, () => {
|
2016-06-15 02:31:51 +08:00
|
|
|
failedCache[url] = true;
|
|
|
|
}).finally(() => {
|
|
|
|
$elem.removeClass('loading-onebox');
|
|
|
|
$elem.data('onebox-loaded');
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function lookupCache(url) {
|
|
|
|
return localCache[url];
|
|
|
|
}
|