snort/src/Text.js

103 lines
4.1 KiB
JavaScript
Raw Normal View History

2023-01-06 11:05:27 +00:00
import { Link } from "react-router-dom";
import Invoice from "./element/Invoice";
import { UrlRegex, FileExtensionRegex, MentionRegex, InvoiceRegex } from "./Const";
2023-01-06 14:36:13 +00:00
import { eventLink, profileLink } from "./Util";
2023-01-06 11:05:27 +00:00
export function extractLinks(fragments) {
return fragments.map(f => {
if (typeof f === "string") {
return f.split(UrlRegex).map(a => {
if (a.startsWith("http")) {
try {
2023-01-06 17:00:33 +00:00
const url = new URL(a);
const vParam = url.searchParams.get('v')
const isYoutube = (url.host === "www.youtube.com" || url.host === "youtube.com" ) && vParam
const ext = url.pathname.toLowerCase().match(FileExtensionRegex);
2023-01-06 11:05:27 +00:00
if (ext) {
switch (ext[1]) {
case "gif":
case "jpg":
case "jpeg":
case "png":
case "bmp":
case "webp": {
return <img key={url} src={url} />;
}
case "mp4":
2023-01-06 15:21:06 +00:00
case "mov":
2023-01-06 11:05:27 +00:00
case "mkv":
case "avi":
case "m4v": {
return <video key={url} src={url} controls />
}
}
2023-01-06 17:00:33 +00:00
} else if (isYoutube) {
return (
<iframe
src={`https://www.youtube.com/embed/${vParam}`}
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen=""
/>
)
2023-01-06 11:05:27 +00:00
} else {
2023-01-06 12:45:06 +00:00
return <a key={url} href={url}>{url.toString()}</a>
2023-01-06 11:05:27 +00:00
}
} catch (e) {
console.warn(`Not a valid url: ${a}`);
}
}
return a;
});
}
return f;
}).flat();
}
export function extractMentions(fragments, tags, users) {
return fragments.map(f => {
if (typeof f === "string") {
return f.split(MentionRegex).map((match) => {
let matchTag = match.match(/#\[(\d+)\]/);
if (matchTag && matchTag.length === 2) {
let idx = parseInt(matchTag[1]);
let ref = tags.find(a => a.Index === idx);
if (ref) {
switch (ref.Key) {
case "p": {
let pUser = users[ref.PubKey]?.name ?? ref.PubKey.substring(0, 8);
2023-01-06 14:36:13 +00:00
return <Link key={ref.PubKey} to={profileLink(ref.PubKey)} onClick={(ev) => ev.stopPropagation()}>@{pUser}</Link>;
2023-01-06 11:05:27 +00:00
}
case "e": {
let eText = ref.Event.substring(0, 8);
2023-01-06 14:36:13 +00:00
return <Link key={ref.Event} to={eventLink(ref.Event)}>#{eText}</Link>;
2023-01-06 11:05:27 +00:00
}
}
}
return <b style={{ color: "red" }}>{matchTag[0]}?</b>;
} else {
return match;
}
});
}
return f;
}).flat();
}
export function extractInvoices(fragments) {
return fragments.map(f => {
if (typeof f === "string") {
return f.split(InvoiceRegex).map(i => {
if (i.toLowerCase().startsWith("lnbc")) {
return <Invoice key={i} invoice={i} />
} else {
return i;
}
});
}
return f;
}).flat();
}