discourse/app/assets/javascripts/pretty-text/image-short-url.js.es6

69 lines
1.6 KiB
Plaintext
Raw Normal View History

let _cache = {};
export function lookupCachedUploadUrl(shortUrl) {
return _cache[shortUrl];
}
export function lookupUncachedUploadUrls(urls, ajax) {
2018-06-15 23:03:24 +08:00
return ajax("/uploads/lookup-urls", {
method: "POST",
data: { short_urls: urls }
}).then(uploads => {
uploads.forEach(upload =>
cacheShortUploadUrl(upload.short_url, upload.url)
);
urls.forEach(url =>
cacheShortUploadUrl(url, lookupCachedUploadUrl(url) || "missing")
);
2018-06-15 23:03:24 +08:00
return uploads;
});
}
export function cacheShortUploadUrl(shortUrl, url) {
_cache[shortUrl] = url;
}
export function resetCache() {
_cache = {};
}
function _loadCachedShortUrls($images) {
$images.each((idx, image) => {
const $image = $(image);
const url = lookupCachedUploadUrl($image.data("orig-src"));
if (url) {
2018-06-15 23:03:24 +08:00
$image.removeAttr("data-orig-src");
if (url !== "missing") {
2018-06-15 23:03:24 +08:00
$image.attr("src", url);
}
}
});
}
function _loadShortUrls($images, ajax) {
const urls = $images.toArray().map(img => $(img).data("orig-src"));
return lookupUncachedUploadUrls(urls, ajax).then(() =>
2018-06-15 23:03:24 +08:00
_loadCachedShortUrls($images)
);
}
export function resolveAllShortUrls(ajax) {
2018-06-15 23:03:24 +08:00
let $shortUploadUrls = $("img[data-orig-src]");
if ($shortUploadUrls.length > 0) {
_loadCachedShortUrls($shortUploadUrls);
2018-06-15 23:03:24 +08:00
$shortUploadUrls = $("img[data-orig-src]");
if ($shortUploadUrls.length > 0) {
// this is carefully batched so we can do a leading debounce (trigger right away)
return Ember.run.debounce(
2018-06-15 23:03:24 +08:00
null,
() => _loadShortUrls($shortUploadUrls, ajax),
2018-06-15 23:03:24 +08:00
450,
true
);
}
}
}