2021-03-02 16:46:48 -05:00
|
|
|
import { anchorme, html } from "./index.js";
|
2020-06-25 11:26:40 -04:00
|
|
|
|
2021-05-31 22:39:35 -04:00
|
|
|
function linkifyChannel(text, transformChannel) {
|
2021-06-06 10:00:37 -04:00
|
|
|
// Don't match punctuation at the end of the channel name
|
2021-06-09 10:28:07 -04:00
|
|
|
const channelRegex = /(?:^|\s)(#[^\s]+[^\s.?!…():;,])/gid;
|
2021-05-31 22:39:35 -04:00
|
|
|
|
2021-06-06 10:00:37 -04:00
|
|
|
var children = [];
|
|
|
|
var match;
|
2021-05-31 22:39:35 -04:00
|
|
|
var last = 0;
|
|
|
|
while ((match = channelRegex.exec(text)) !== null) {
|
2021-06-01 03:53:11 -04:00
|
|
|
var channel = match[1];
|
|
|
|
var [start, end] = match.indices[1];
|
2021-05-31 22:39:35 -04:00
|
|
|
|
|
|
|
children.push(text.substring(last, start));
|
|
|
|
children.push(transformChannel(channel));
|
|
|
|
|
2021-06-01 03:53:11 -04:00
|
|
|
last = end;
|
2021-05-31 22:39:35 -04:00
|
|
|
}
|
|
|
|
children.push(text.substring(last));
|
|
|
|
|
|
|
|
return children;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function linkify(text, onChannelClick) {
|
|
|
|
function transformChannel(channel) {
|
|
|
|
function onClick(event) {
|
|
|
|
event.preventDefault();
|
|
|
|
onChannelClick(channel);
|
|
|
|
}
|
|
|
|
return html`
|
|
|
|
<a
|
|
|
|
href="irc:///${encodeURIComponent(channel)}"
|
|
|
|
onClick=${onClick}
|
|
|
|
>${channel}</a>`;
|
|
|
|
}
|
|
|
|
|
2020-06-25 11:26:40 -04:00
|
|
|
var links = anchorme.list(text);
|
|
|
|
|
|
|
|
var children = [];
|
|
|
|
var last = 0;
|
|
|
|
links.forEach((match) => {
|
2021-05-31 22:39:35 -04:00
|
|
|
const prefix = text.substring(last, match.start)
|
|
|
|
children.push(...linkifyChannel(prefix, transformChannel));
|
2020-06-25 11:26:40 -04:00
|
|
|
|
|
|
|
var proto = match.protocol || "https://";
|
|
|
|
if (match.isEmail) {
|
|
|
|
proto = "mailto:";
|
|
|
|
}
|
|
|
|
|
|
|
|
var url = match.string;
|
|
|
|
if (!url.startsWith(proto)) {
|
|
|
|
url = proto + url;
|
|
|
|
}
|
|
|
|
|
|
|
|
children.push(html`<a href=${url} target="_blank" rel="noreferrer noopener">${match.string}</a>`);
|
|
|
|
|
|
|
|
last = match.end;
|
|
|
|
});
|
2021-05-31 22:39:35 -04:00
|
|
|
|
|
|
|
const suffix = text.substring(last)
|
|
|
|
children.push(...linkifyChannel(suffix, transformChannel));
|
2020-06-25 11:26:40 -04:00
|
|
|
|
|
|
|
return children;
|
|
|
|
}
|