Linkify channel names

This commit is contained in:
Tom Lebreux 2021-05-31 22:39:35 -04:00 committed by Simon Ser
parent 9affdb894f
commit 0bcd044f10
4 changed files with 62 additions and 8 deletions

View file

@ -1,12 +1,46 @@
import { anchorme, html } from "./index.js";
export default function linkify(text) {
function linkifyChannel(text, transformChannel) {
var children = [];
// TODO: Don't match punctuation
const channelRegex = /(^|\s)(#[^\s]+)/gid;
let match;
var last = 0;
while ((match = channelRegex.exec(text)) !== null) {
const [_, spaces, channel] = match;
const start = match.index + spaces.length;
children.push(text.substring(last, start));
children.push(transformChannel(channel));
last = match.index + spaces.length + channel.length;
}
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>`;
}
var links = anchorme.list(text);
var children = [];
var last = 0;
links.forEach((match) => {
children.push(text.substring(last, match.start));
const prefix = text.substring(last, match.start)
children.push(...linkifyChannel(prefix, transformChannel));
var proto = match.protocol || "https://";
if (match.isEmail) {
@ -22,7 +56,9 @@ export default function linkify(text) {
last = match.end;
});
children.push(text.substring(last));
const suffix = text.substring(last)
children.push(...linkifyChannel(suffix, transformChannel));
return children;
}