gamja/lib/linkify.js

66 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-10-13 09:33:41 -04:00
import { linkifyjs, html } from "./index.js";
2020-06-25 11:26:40 -04:00
2021-10-13 09:33:41 -04:00
linkifyjs.options.defaults.defaultProtocol = "https";
2021-05-31 22:39:35 -04:00
2021-10-13 09:33:41 -04:00
linkifyjs.registerCustomProtocol("irc");
linkifyjs.registerCustomProtocol("ircs");
2024-01-10 05:38:23 -05:00
linkifyjs.registerCustomProtocol("geo", true);
2021-05-31 22:39:35 -04:00
2024-01-10 05:33:20 -05:00
const IRCChannelToken = linkifyjs.createTokenClass("ircChannel", {
isLink: true,
toHref() {
return "irc:///" + this.v;
},
});
2021-10-13 09:33:41 -04:00
2024-01-10 05:33:20 -05:00
linkifyjs.registerPlugin("ircChannel", ({ scanner, parser }) => {
const { POUND, UNDERSCORE, DOT, HYPHEN } = scanner.tokens;
const { alphanumeric } = scanner.tokens.groups;
const Prefix = parser.start.tt(POUND);
const Channel = new linkifyjs.State(IRCChannelToken);
const Divider = Channel.tt(DOT);
Prefix.ta(alphanumeric, Channel);
Prefix.tt(POUND, Channel);
Prefix.tt(UNDERSCORE, Channel);
Prefix.tt(DOT, Divider);
Prefix.tt(HYPHEN, Channel);
Channel.ta(alphanumeric, Channel);
Channel.tt(POUND, Channel);
Channel.tt(UNDERSCORE, Channel);
Channel.tt(HYPHEN, Channel);
Divider.ta(alphanumeric, Channel);
2021-10-13 09:33:41 -04:00
});
export default function linkify(text, onClick) {
2021-10-13 09:33:41 -04:00
let links = linkifyjs.find(text);
2020-06-25 11:26:40 -04:00
2021-06-10 12:11:11 -04:00
let children = [];
let last = 0;
2020-06-25 11:26:40 -04:00
links.forEach((match) => {
2021-10-13 09:33:41 -04:00
if (!match.isLink) {
return;
2020-06-25 11:26:40 -04:00
}
2024-09-29 05:48:45 -04:00
const prefix = text.substring(last, match.start);
2021-10-13 09:33:41 -04:00
children.push(prefix);
2020-06-25 11:26:40 -04:00
children.push(html`
<a
href=${match.href}
target="_blank"
rel="noreferrer noopener"
onClick=${onClick}
>${match.value}</a>
`);
2020-06-25 11:26:40 -04:00
last = match.end;
});
2021-05-31 22:39:35 -04:00
2024-09-29 05:48:45 -04:00
const suffix = text.substring(last);
2021-10-13 09:33:41 -04:00
children.push(suffix);
2020-06-25 11:26:40 -04:00
return children;
}