snort/packages/app/src/Pages/Layout.tsx

248 lines
7.2 KiB
TypeScript
Raw Normal View History

2022-12-29 15:36:40 +00:00
import "./Layout.css";
import { useEffect, useMemo, useState } from "react";
2022-12-27 23:46:13 +00:00
import { useDispatch, useSelector } from "react-redux";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
2023-03-28 14:34:01 +00:00
import { FormattedMessage } from "react-intl";
import { RelaySettings } from "@snort/nostr";
import messages from "./messages";
2023-02-10 19:23:52 +00:00
2023-03-28 14:34:01 +00:00
import { bech32ToHex, randomSample } from "Util";
2023-03-02 17:47:02 +00:00
import Icon from "Icons/Icon";
2023-01-20 11:11:50 +00:00
import { RootState } from "State/Store";
2023-02-05 06:29:46 +00:00
import { init, setRelays } from "State/Login";
2023-02-20 23:14:15 +00:00
import { System } from "System";
2023-01-20 11:11:50 +00:00
import ProfileImage from "Element/ProfileImage";
import useLoginFeed from "Feed/LoginFeed";
import { totalUnread } from "Pages/MessagesPage";
2023-01-28 21:43:56 +00:00
import useModeration from "Hooks/useModeration";
2023-02-05 12:32:34 +00:00
import { NoteCreator } from "Element/NoteCreator";
2023-03-03 14:30:31 +00:00
import { db } from "Db";
import { UserCache } from "State/Users/UserCache";
2023-03-28 14:34:01 +00:00
import { FollowsRelays } from "State/Relays";
import useEventPublisher from "Feed/EventPublisher";
import { SnortPubKey } from "Const";
import SubDebug from "Element/SubDebug";
2023-01-28 21:43:56 +00:00
2023-01-16 18:14:08 +00:00
export default function Layout() {
const location = useLocation();
const [show, setShow] = useState(false);
const dispatch = useDispatch();
const navigate = useNavigate();
2023-03-28 14:34:01 +00:00
const { loggedOut, publicKey, relays, preferences, newUserKey } = useSelector((s: RootState) => s.login);
2023-02-09 18:05:45 +00:00
const [pageClass, setPageClass] = useState("page");
const pub = useEventPublisher();
useLoginFeed();
const shouldHideNoteCreator = useMemo(() => {
2023-02-12 12:31:48 +00:00
const hideOn = ["/settings", "/messages", "/new", "/login", "/donate", "/p/"];
2023-02-09 18:05:45 +00:00
return hideOn.some(a => location.pathname.startsWith(a));
}, [location]);
const shouldHideHeader = useMemo(() => {
2023-02-12 12:31:48 +00:00
const hideOn = ["/login", "/new"];
2023-02-09 18:05:45 +00:00
return hideOn.some(a => location.pathname.startsWith(a));
}, [location]);
useEffect(() => {
if (location.pathname.startsWith("/login")) {
setPageClass("");
} else {
setPageClass("page");
}
}, [location]);
useEffect(() => {
2023-02-20 23:14:15 +00:00
System.HandleAuth = pub.nip42Auth;
}, [pub]);
useEffect(() => {
if (relays) {
2023-03-28 14:34:01 +00:00
(async () => {
for (const [k, v] of Object.entries(relays)) {
await System.ConnectToRelay(k, v);
2023-01-20 17:07:14 +00:00
}
2023-03-28 14:34:01 +00:00
for (const [k, c] of System.Sockets) {
if (!relays[k] && !c.Ephemeral) {
System.DisconnectRelay(k);
}
}
})();
}
}, [relays]);
function setTheme(theme: "light" | "dark") {
const elm = document.documentElement;
if (theme === "light" && !elm.classList.contains("light")) {
elm.classList.add("light");
} else if (theme === "dark" && elm.classList.contains("light")) {
elm.classList.remove("light");
}
}
useEffect(() => {
2023-02-07 19:47:57 +00:00
const osTheme = window.matchMedia("(prefers-color-scheme: light)");
setTheme(
2023-02-09 12:26:54 +00:00
preferences.theme === "system" && osTheme.matches ? "light" : preferences.theme === "light" ? "light" : "dark"
);
2023-02-09 12:26:54 +00:00
osTheme.onchange = e => {
if (preferences.theme === "system") {
setTheme(e.matches ? "light" : "dark");
}
};
return () => {
osTheme.onchange = null;
};
}, [preferences.theme]);
useEffect(() => {
// check DB support then init
2023-03-03 14:30:31 +00:00
db.isAvailable().then(async a => {
db.ready = a;
if (a) {
await UserCache.preload();
2023-03-28 14:34:01 +00:00
await FollowsRelays.preload();
}
2023-03-03 14:30:31 +00:00
console.debug(`Using db: ${a ? "IndexedDB" : "In-Memory"}`);
dispatch(init());
2023-01-29 19:44:53 +00:00
try {
if ("registerProtocolHandler" in window.navigator) {
2023-02-14 11:08:25 +00:00
window.navigator.registerProtocolHandler(
"web+nostr",
`${window.location.protocol}//${window.location.host}/handler/%s`
);
console.info("Registered protocol handler for 'web+nostr'");
2023-01-29 19:44:53 +00:00
}
} catch (e) {
console.error("Failed to register protocol handler", e);
}
});
}, []);
async function handleNewUser() {
2023-02-07 19:47:57 +00:00
let newRelays: Record<string, RelaySettings> = {};
try {
2023-02-07 19:47:57 +00:00
const rsp = await fetch("https://api.nostr.watch/v1/online");
if (rsp.ok) {
2023-02-07 19:47:57 +00:00
const online: string[] = await rsp.json();
2023-02-10 19:23:52 +00:00
const pickRandom = randomSample(online, 4);
2023-02-09 12:26:54 +00:00
const relayObjects = pickRandom.map(a => [a, { read: true, write: true }]);
newRelays = Object.fromEntries(relayObjects);
dispatch(
setRelays({
2023-02-07 19:47:57 +00:00
relays: newRelays,
createdAt: 1,
})
);
}
} catch (e) {
console.warn(e);
2023-01-20 18:59:08 +00:00
}
const ev = await pub.addFollow(bech32ToHex(SnortPubKey), newRelays);
pub.broadcast(ev);
}
2023-02-05 06:29:46 +00:00
useEffect(() => {
if (newUserKey === true) {
handleNewUser().catch(console.warn);
2023-02-05 06:29:46 +00:00
}
}, [newUserKey]);
if (typeof loggedOut !== "boolean") {
return null;
}
return (
2023-02-09 18:05:45 +00:00
<div className={pageClass}>
{!shouldHideHeader && (
<header>
<div className="logo" onClick={() => navigate("/")}>
Snort
</div>
<div>
{publicKey ? (
2023-03-28 14:34:01 +00:00
<AccountHeader />
2023-02-09 18:05:45 +00:00
) : (
<button type="button" onClick={() => navigate("/login")}>
<FormattedMessage {...messages.Login} />
</button>
)}
</div>
</header>
)}
<Outlet />
{!shouldHideNoteCreator && (
<>
2023-02-09 12:26:54 +00:00
<button className="note-create-button" type="button" onClick={() => setShow(!show)}>
2023-03-02 18:40:46 +00:00
<Icon name="plus" size={16} />
</button>
2023-02-09 12:26:54 +00:00
<NoteCreator replyTo={undefined} autoFocus={true} show={show} setShow={setShow} />
</>
)}
2023-03-28 14:34:01 +00:00
{window.localStorage.getItem("debug") && <SubDebug />}
</div>
);
2023-01-19 23:19:09 +00:00
}
2023-03-28 14:34:01 +00:00
const AccountHeader = () => {
const navigate = useNavigate();
const { isMuted } = useModeration();
const { publicKey, latestNotification, readNotifications, dms } = useSelector((s: RootState) => s.login);
const hasNotifications = useMemo(
() => latestNotification > readNotifications,
[latestNotification, readNotifications]
);
const unreadDms = useMemo(
() =>
publicKey
? totalUnread(
dms.filter(a => !isMuted(a.pubkey)),
publicKey
)
: 0,
[dms, publicKey]
);
async function goToNotifications(e: React.MouseEvent) {
e.stopPropagation();
// request permissions to send notifications
if ("Notification" in window) {
try {
if (Notification.permission !== "granted") {
const res = await Notification.requestPermission();
console.debug(res);
}
} catch (e) {
console.error(e);
}
}
navigate("/notifications");
}
return (
<div className="header-actions">
<div className="btn btn-rnd" onClick={() => navigate("/wallet")}>
<Icon name="bitcoin" />
</div>
<div className="btn btn-rnd" onClick={() => navigate("/search")}>
<Icon name="search" />
</div>
<div className="btn btn-rnd" onClick={() => navigate("/messages")}>
<Icon name="envelope" />
{unreadDms > 0 && <span className="has-unread"></span>}
</div>
<div className="btn btn-rnd" onClick={goToNotifications}>
<Icon name="bell" />
{hasNotifications && <span className="has-unread"></span>}
</div>
<ProfileImage pubkey={publicKey || ""} showUsername={false} />
</div>
);
};