2020-07-14 14:06:52 +02:00
|
|
|
import { converse } from "@converse/headless/converse-core";
|
2020-07-09 08:57:25 +02:00
|
|
|
import { directive, html } from "lit-html";
|
|
|
|
|
|
|
|
|
2020-09-01 12:21:32 +02:00
|
|
|
/**
|
|
|
|
* lit-html directive which attempts to render an <img> element from a URL.
|
|
|
|
* It will fall back to rendering an <a> element if it can't.
|
|
|
|
*
|
|
|
|
* @param { String } src - The value that will be assigned to the `src` attribute of the `<img>` element.
|
|
|
|
* @param { String } href - The value that will be assigned to the `href` attribute of the `<img>` element.
|
|
|
|
* @param { Function } onLoad - A callback function to be called once the image has loaded.
|
|
|
|
* @param { Function } onClick - A callback function to be called once the image has been clicked.
|
|
|
|
*/
|
|
|
|
export const renderImage = directive((src, href, onLoad, onClick) => part => {
|
2020-07-09 08:57:25 +02:00
|
|
|
function onError () {
|
2020-08-31 20:29:51 +02:00
|
|
|
const u = converse.env.utils;
|
2020-09-01 12:21:32 +02:00
|
|
|
if (u.isURLWithImageExtension(src)) {
|
|
|
|
part.setValue(u.convertUrlToHyperlink(href));
|
2020-08-31 20:29:51 +02:00
|
|
|
part.commit();
|
|
|
|
} else {
|
|
|
|
// Before giving up and falling back to just rendering a hyperlink,
|
|
|
|
// we attach `.png` and try one more time.
|
|
|
|
// This works with some Imgur URLs
|
2020-09-01 12:21:32 +02:00
|
|
|
part.setValue(renderImage(`${src}.png`, href, onLoad, onClick));
|
2020-08-31 20:29:51 +02:00
|
|
|
part.commit();
|
|
|
|
}
|
2020-07-09 08:57:25 +02:00
|
|
|
}
|
|
|
|
part.setValue(
|
2020-09-01 12:21:32 +02:00
|
|
|
html`<a href="${href}"
|
2020-07-09 08:57:25 +02:00
|
|
|
class="chat-image__link"
|
|
|
|
target="_blank"
|
|
|
|
rel="noopener"
|
2020-09-01 12:21:32 +02:00
|
|
|
><img class="chat-image img-thumbnail" src="${src}" @click=${onClick} @error=${onError} @load=${onLoad}/></a>`
|
2020-07-09 08:57:25 +02:00
|
|
|
);
|
|
|
|
});
|