diff options
author | polwex <polwex@sortug.com> | 2025-09-11 01:48:14 +0700 |
---|---|---|
committer | polwex <polwex@sortug.com> | 2025-09-11 01:48:14 +0700 |
commit | b1d68ac307ed87d63e83820cbdf843fff0fd9f7f (patch) | |
tree | d6a684a70a80509e68ff667b842aa4e4c091906f /front/src/components |
init
Diffstat (limited to 'front/src/components')
21 files changed, 1884 insertions, 0 deletions
diff --git a/front/src/components/Avatar.tsx b/front/src/components/Avatar.tsx new file mode 100644 index 0000000..35b4386 --- /dev/null +++ b/front/src/components/Avatar.tsx @@ -0,0 +1,59 @@ +import useLocalState from "@/state/state"; +import type { Ship } from "@/types/urbit"; +import Sigil from "./Sigil"; +import ShipModal from "./modals/ShipModal"; + +export default function ({ + p, + size, + color, + noClickOnName, +}: { + p: Ship; + size: number; + color?: string; + noClickOnName?: boolean; +}) { + const { setModal } = useLocalState(); + // TODO revisit this when %whom updates + const avatar = ( + <div className="avatar-w sigil cp" role="link" onClick={openModal}> + <Sigil patp={p} size={size} color={color} /> + </div> + ); + const tooLong = (s: string) => (s.length > 15 ? " too-long" : ""); + function openModal(e: React.MouseEvent) { + if (noClickOnName) return; + e.stopPropagation(); + setModal(<ShipModal ship={p} />); + } + const name = ( + <div className="name cp" role="link" onMouseUp={openModal}> + <p className={"p-only" + tooLong(p)}>{p.length > 28 ? "Anon" : p}</p> + </div> + ); + return ( + <div className="ship-avatar"> + {avatar} + {name} + </div> + ); +} + +export function SigilOnly({ p, size, color }: any) { + const { setModal } = useLocalState(); + function openModal(e: React.MouseEvent) { + e.stopPropagation(); + setModal(<ShipModal ship={p} />); + } + return ( + <div + className="avatar-w sigil cp" + role="link" + onClick={openModal} + onMouseUp={openModal} + > + <Sigil patp={p} size={size} color={color} /> + </div> + ); +} diff --git a/front/src/components/Sigil.tsx b/front/src/components/Sigil.tsx new file mode 100644 index 0000000..4978a72 --- /dev/null +++ b/front/src/components/Sigil.tsx @@ -0,0 +1,50 @@ +import comet from "@/assets/icons/comet.svg"; +import { auraToHex } from "@/logic/utils"; +import { isValidPatp } from "urbit-ob"; +import { sigil } from "urbit-sigils"; +import { reactRenderer } from "urbit-sigils"; + +interface SigilProps { + patp: string; + size: number; + color?: string; +} + +const Sigil = (props: SigilProps) => { + const color = props.color ? auraToHex(props.color) : "black"; + if (!isValidPatp(props.patp)) return <div className="sigil bad-sigil">X</div>; + else if (props.patp.length > 28) + return ( + <img + className="comet-icon" + src={comet} + alt="" + style={{ width: `${props.size}px`, height: `${props.size}px` }} + /> + ); + else if (props.patp.length > 15) + // moons + return ( + <> + {sigil({ + patp: props.patp.substring(props.patp.length - 13), + renderer: reactRenderer, + size: props.size, + colors: ["grey", "white"], + })} + </> + ); + else + return ( + <> + {sigil({ + patp: props.patp, + renderer: reactRenderer, + size: props.size, + colors: [color, "white"], + })} + </> + ); +}; + +export default Sigil; diff --git a/front/src/components/feed/Body.tsx b/front/src/components/feed/Body.tsx new file mode 100644 index 0000000..2f11962 --- /dev/null +++ b/front/src/components/feed/Body.tsx @@ -0,0 +1,174 @@ +import type { + // TODO ref backend fetching!! + Reference, + Block, + Inline, + Media as MediaType, + ExternalContent, +} from "@/types/trill"; +import crow from "@/assets/icons/crow.svg"; +import type { PostProps } from "./Post"; +import Media from "./Media"; +import JSONContent, { YoutubeSnippet } from "./External"; +import { useLocation } from "wouter"; +import Quote from "./Quote"; +import PostData from "./PostData"; +import Card from "./Card.tsx"; +import type { Ship } from "@/types/urbit.ts"; + +function Body(props: PostProps) { + const text = props.poast.contents.filter((c) => { + return ( + "paragraph" in c || + "blockquote" in c || + "heading" in c || + "codeblock" in c || + "list" in c + ); + }); + + const media: MediaType[] = props.poast.contents.filter( + (c): c is MediaType => "media" in c, + ); + + const refs = props.poast.contents.filter((c): c is Reference => "ref" in c); + const json = props.poast.contents.filter( + (c): c is ExternalContent => "json" in c, + ); + + return ( + <div className="trill-post-body body"> + <div className="body-text"> + {text.map((b, i) => ( + <TextBlock key={JSON.stringify(b) + i} block={b} /> + ))} + </div> + {media.length > 0 && <Media media={media} />} + {refs.map((r, i) => ( + <Ref r={r} nest={props.nest || 0} key={JSON.stringify(r) + i} /> + ))} + <JSONContent content={json} /> + </div> + ); +} +export default Body; + +function TextBlock({ block }: { block: Block }) { + const key = JSON.stringify(block); + return "paragraph" in block ? ( + <div className="trill-post-paragraph"> + {block.paragraph.map((i, ind) => ( + <Inlin key={key + ind} i={i} /> + ))} + </div> + ) : "blockquote" in block ? ( + <blockquote> + {block.blockquote.map((i, ind) => ( + <Inlin key={key + ind} i={i} /> + ))} + </blockquote> + ) : "heading" in block ? ( + <Heading string={block.heading.text} num={block.heading.num} /> + ) : "codeblock" in block ? ( + <pre> + <code className={`language-${block.codeblock.lang}`}> + {block.codeblock.code} + </code> + </pre> + ) : "list" in block ? ( + block.list.ordered ? ( + <ol> + {block.list.text.map((i, ind) => ( + <li key={JSON.stringify(i) + ind}> + <Inlin key={key + ind} i={i} /> + </li> + ))} + </ol> + ) : ( + <ul> + {block.list.text.map((i, ind) => ( + <li key={JSON.stringify(i) + ind}> + <Inlin key={JSON.stringify(i) + ind} i={i} /> + </li> + ))} + </ul> + ) + ) : null; +} +function Inlin({ i }: { i: Inline }) { + const [_, navigate] = useLocation(); + function gotoShip(e: React.MouseEvent, ship: Ship) { + e.stopPropagation(); + navigate(`/feed/${ship}`); + } + return "text" in i ? ( + <span>{i.text}</span> + ) : "italic" in i ? ( + <i>{i.italic}</i> + ) : "bold" in i ? ( + <strong>{i.bold}</strong> + ) : "strike" in i ? ( + <span>{i.strike}</span> + ) : "underline" in i ? ( + <span>{i.underline}</span> + ) : "sup" in i ? ( + <sup>{i.sup}</sup> + ) : "sub" in i ? ( + <sub>{i.sub}</sub> + ) : "ship" in i ? ( + <span + className="mention" + role="link" + onMouseUp={(e) => gotoShip(e, i.ship)} + > + {i.ship} + </span> + ) : "codespan" in i ? ( + <code>{i.codespan}</code> + ) : "link" in i ? ( + <LinkParser {...i.link} /> + ) : "break" in i ? ( + <br /> + ) : null; +} + +function LinkParser({ href, show }: { href: string; show: string }) { + const YOUTUBE_REGEX_1 = /(youtube\.com\/watch\?v=)(\w+)/; + const YOUTUBE_REGEX_2 = /(youtu\.be\/)([a-zA-Z0-9-_]+)/; + const m1 = href.match(YOUTUBE_REGEX_1); + const m2 = href.match(YOUTUBE_REGEX_2); + const ytb = m1 && m1[2] ? m1[2] : m2 && m2[2] ? m2[2] : ""; + return ytb ? ( + <YoutubeSnippet href={href} id={ytb} /> + ) : ( + <a href={href}>{show}</a> + ); +} +function Heading({ string, num }: { string: string; num: number }) { + return num === 1 ? ( + <h1>{string}</h1> + ) : num === 2 ? ( + <h2>{string}</h2> + ) : num === 3 ? ( + <h3>{string}</h3> + ) : num === 4 ? ( + <h4>{string}</h4> + ) : num === 5 ? ( + <h5>{string}</h5> + ) : num === 6 ? ( + <h6>{string}</h6> + ) : null; +} + +function Ref({ r, nest }: { r: Reference; nest: number }) { + if (r.ref.type === "nostril") { + const comp = PostData({ + host: r.ref.ship, + id: r.ref.path.slice(1), + nest: nest + 1, + className: "quote-in-post", + })(Quote); + return <Card logo={crow}>{comp}</Card>; + } + return <></>; +} diff --git a/front/src/components/feed/Card.tsx b/front/src/components/feed/Card.tsx new file mode 100644 index 0000000..37f4911 --- /dev/null +++ b/front/src/components/feed/Card.tsx @@ -0,0 +1,9 @@ +export default function ({ children, logo, cn}: { cn?: string; logo: string; children: any }) { + const className = "trill-post-card" + (cn ? ` ${cn}`: "") + return ( + <div className={className}> + <img src={logo} alt="" className="trill-post-card-logo" /> + {children} + </div> + ); +} diff --git a/front/src/components/feed/Composer.tsx b/front/src/components/feed/Composer.tsx new file mode 100644 index 0000000..27da392 --- /dev/null +++ b/front/src/components/feed/Composer.tsx @@ -0,0 +1,52 @@ +import { openLock } from "@/logic/bunts"; +import { HASHTAGS_REGEX } from "@/logic/constants"; +import useLocalState from "@/state/state"; +import type { Poast, SentPoast } from "@/types/trill"; +import Sigil from "@/components/Sigil"; +import { useState } from "react"; + +function Composer({ + isAnon, + replying, +}: { + isAnon?: boolean; + replying?: Poast; +}) { + const { api, keys } = useLocalState(); + const our = api!.airlock.our!; + const [input, setInput] = useState(replying ? `${replying}: ` : ""); + async function poast() { + // TODO + // const parent = replying ? replying : null; + // const tokens = tokenize(input); + // const post: SentPoast = { + // host: parent ? parent.host : our, + // author: our, + // thread: parent ? parent.thread : null, + // parent: parent ? parent.id : null, + // contents: input, + // read: openLock, + // write: openLock, + // tags: input.match(HASHTAGS_REGEX) || [], + // }; + // TODO make it user choosable + const pubkey = keys[0]!; + await api!.addPost(pubkey, input); + } + const placeHolder = isAnon ? "> be me" : "What's going on in Urbit"; + return ( + <div id="composer"> + <div className="sigil"> + <Sigil patp={our} size={48} /> + </div> + <input + value={input} + onInput={(e) => setInput(e.currentTarget.value)} + placeholder={placeHolder} + /> + <button onClick={poast}>Post</button> + </div> + ); +} + +export default Composer; diff --git a/front/src/components/feed/External.tsx b/front/src/components/feed/External.tsx new file mode 100644 index 0000000..0ea1500 --- /dev/null +++ b/front/src/components/feed/External.tsx @@ -0,0 +1,41 @@ +import type { ExternalContent } from "@/types/trill"; +import youtube from "@/assets/icons/youtube.svg"; +import Card from "./Card"; + +interface JSONProps { + content: ExternalContent[]; +} + +function JSONContent({ content }: JSONProps) { + return ( + <> + {content.map((c, i) => { + if (!JSON.parse(c.json.content)) return <p key={i}>Error</p>; + else + return ( + <p + key={JSON.stringify(c.json)} + className="external-content-warning" + > + External content from "{c.json.origin}", use + <a href="https://urbit.org/applications/~sortug/ufa">UFA</a> + to display. + </p> + ); + })} + </> + ); +} +export default JSONContent; + +export function YoutubeSnippet({ href, id }: { href: string; id: string }) { + const thumbnail = `https://i.ytimg.com/vi/${id}/hqdefault.jpg`; + // todo styiling + return ( + <Card logo={youtube} cn="youtube-thumbnail"> + <a href={href}> + <img src={thumbnail} alt="" /> + </a> + </Card> + ); +} diff --git a/front/src/components/feed/Footer.tsx b/front/src/components/feed/Footer.tsx new file mode 100644 index 0000000..938a8c7 --- /dev/null +++ b/front/src/components/feed/Footer.tsx @@ -0,0 +1,237 @@ +import type { PostProps } from "./Post"; +import reply from "@/assets/icons/reply.svg"; +import quote from "@/assets/icons/quote.svg"; +import repost from "@/assets/icons/rt.svg"; +import { useState } from "react"; +import useLocalState from "@/state/state"; +import { useLocation } from "wouter"; +import { displayCount } from "@/logic/utils"; +import { TrillReactModal, stringToReact } from "./Reactions"; +import toast from "react-hot-toast"; +import NostrIcon from "./NostrIcon"; +function Footer({ poast, refetch }: PostProps) { + const [_showMenu, setShowMenu] = useState(false); + const [location, navigate] = useLocation(); + const [reposting, _setReposting] = useState(false); + const { api, setComposerData, setModal } = useLocalState(); + const our = api!.airlock.our!; + function doReply(e: React.MouseEvent) { + e.stopPropagation(); + setComposerData({ type: "reply", post: { service: "trill", post: poast } }); + navigate("/composer"); + } + function doQuote(e: React.MouseEvent) { + e.stopPropagation(); + setComposerData({ + type: "quote", + post: { service: "trill", post: poast }, + }); + navigate("/composer"); + } + const childrenCount = poast.children + ? poast.children.length + ? poast.children.length + : Object.keys(poast.children).length + : 0; + const myRP = poast.engagement.shared.find((r) => r.pid.ship === our); + async function cancelRP(e: React.MouseEvent) { + e.stopPropagation(); + const r = await api!.deletePost(our); + if (r) toast.success("Repost deleted"); + refetch(); + if (location.includes(poast.id)) navigate("/"); + } + async function sendRP(e: React.MouseEvent) { + // TODO update backend because contents are only markdown now + e.stopPropagation(); + // const c = [ + // { + // ref: { + // type: "trill", + // ship: poast.host, + // path: `/${poast.id}`, + // }, + // }, + // ]; + // const post: SentPoast = { + // host: our, + // author: our, + // thread: null, + // parent: null, + // contents: input, + // read: openLock, + // write: openLock, + // tags: [], // TODO + // }; + // const r = await api!.addPost(post, false); + // setReposting(true); + // if (r) { + // setReposting(false); + // toast.success("Your post was published"); + // } + } + function doReact(e: React.MouseEvent) { + e.stopPropagation(); + const modal = <TrillReactModal poast={poast} />; + setModal(modal); + } + function showReplyCount() { + if (poast.children[0]) fetchAndShow(); // Flatpoast + // else { + // const authors = Object.keys(poast.children).map( + // (i) => poast.children[i].post.author + // ); + // setEngagement({ type: "replies", ships: authors }, poast); + // } + } + async function fetchAndShow() { + // let authors = []; + // for (let i of poast.children as string[]) { + // const res = await scrypoastFull(poast.host, i); + // if (res) + // authors.push(res.post.author || "deleter"); + // } + // setEngagement({ type: "replies", ships: authors }, poast); + } + function showRepostCount() { + // const ships = poast.engagement.shared.map((entry) => entry.host); + // setEngagement({ type: "reposts", ships: ships }, poast); + } + function showQuoteCount() { + // setEngagement({ type: "quotes", quotes: poast.engagement.quoted }, poast); + } + function showReactCount() { + // setEngagement({ type: "reacts", reacts: poast.engagement.reacts }, poast); + } + + const mostCommonReact = Object.values(poast.engagement.reacts).reduce( + (acc: any, item) => { + if (!acc.counts[item]) acc.counts[item] = 0; + acc.counts[item] += 1; + if (!acc.winner || acc.counts[item] > acc.counts[acc.winner]) + acc.winner = item; + return acc; + }, + { counts: {}, winner: "" }, + ).winner; + const reactIcon = stringToReact(mostCommonReact); + + // TODO round up all helpers + + return ( + <div className="footer-wrapper post-footer"> + <footer> + <div className="icon"> + <span role="link" onMouseUp={showReplyCount} className="reply-count"> + {displayCount(childrenCount)} + </span> + <img role="link" onMouseUp={doReply} src={reply} alt="" /> + </div> + <div className="icon"> + <span role="link" onMouseUp={showQuoteCount} className="quote-count"> + {displayCount(poast.engagement.quoted.length)} + </span> + <img role="link" onMouseUp={doQuote} src={quote} alt="" /> + </div> + <div className="icon"> + <span + role="link" + onMouseUp={showRepostCount} + className="repost-count" + > + {displayCount(poast.engagement.shared.length)} + </span> + {reposting ? ( + <p>...</p> + ) : myRP ? ( + <img + role="link" + className="my-rp" + onMouseUp={cancelRP} + src={repost} + title="cancel repost" + /> + ) : ( + <img role="link" onMouseUp={sendRP} src={repost} title="repost" /> + )} + </div> + <div className="icon" role="link" onMouseUp={doReact}> + <span + role="link" + onMouseUp={showReactCount} + className="reaction-count" + > + {displayCount(Object.keys(poast.engagement.reacts).length)} + </span> + {reactIcon} + </div> + <NostrIcon poast={poast} /> + </footer> + </div> + ); +} +export default Footer; + +// function Menu({ +// poast, +// setShowMenu, +// refetch, +// }: { +// poast: Poast; +// setShowMenu: Function; +// refetch: Function; +// }) { +// const ref = useRef<HTMLDivElement>(null); +// const [location, navigate] = useLocation(); +// // TODO this is a mess and the event still propagates +// useEffect(() => { +// const checkIfClickedOutside = (e: any) => { +// e.stopPropagation(); +// if (ref && ref.current && !ref.current.contains(e.target)) +// setShowMenu(false); +// }; +// document.addEventListener("mousedown", checkIfClickedOutside); +// return () => { +// document.removeEventListener("mousedown", checkIfClickedOutside); +// }; +// }, []); +// const { our, setModal, setAlert } = useLocalState(); +// const mine = our === poast.host || our === poast.author; +// async function doDelete(e: React.MouseEvent) { +// e.stopPropagation(); +// deletePost(poast.host, poast.id); +// setAlert("Post deleted"); +// setShowMenu(false); +// refetch(); +// if (location.includes(poast.id)) navigate("/"); +// } +// async function copyLink(e: React.MouseEvent) { +// e.stopPropagation(); +// const link = trillPermalink(poast); +// await navigator.clipboard.writeText(link); +// // some alert +// setShowMenu(false); +// } +// function openStats(e: React.MouseEvent) { +// e.stopPropagation(); +// e.preventDefault(); +// const m = <StatsModal poast={poast} close={() => setModal(null)} />; +// setModal(m); +// } +// return ( +// <div ref={ref} id="post-menu"> +// {/* <p onClick={openShare}>Share to Groups</p> */} +// <p role="link" onMouseUp={openStats}> +// See Stats +// </p> +// <p role="link" onMouseUp={copyLink}> +// Permalink +// </p> +// {mine && ( +// <p role="link" onMouseUp={doDelete}> +// Delete Post +// </p> +// )} +// </div> +// ); +// } diff --git a/front/src/components/feed/Header.tsx b/front/src/components/feed/Header.tsx new file mode 100644 index 0000000..7658bfb --- /dev/null +++ b/front/src/components/feed/Header.tsx @@ -0,0 +1,33 @@ +import { date_diff } from "@/logic/utils"; +import type { PostProps } from "./Post"; +import { useLocation } from "wouter"; +function Header(props: PostProps) { + const [_, navigate] = useLocation(); + function go(e: React.MouseEvent) { + e.stopPropagation(); + } + function openThread(e: React.MouseEvent) { + e.stopPropagation(); + const sel = window.getSelection()?.toString(); + if (!sel) navigate(`/feed/${poast.host}/${poast.id}`); + } + const { poast } = props; + const name = ( + <div className="name cp"> + <p className="p-only">{poast.author}</p> + </div> + ); + return ( + <header> + <div className="author flex-align" role="link" onMouseUp={go}> + {name} + </div> + <div role="link" onMouseUp={openThread} className="date"> + <p title={new Date(poast.time).toLocaleString()}> + {date_diff(poast.time, "short")} + </p> + </div> + </header> + ); +} +export default Header; diff --git a/front/src/components/feed/Media.tsx b/front/src/components/feed/Media.tsx new file mode 100644 index 0000000..04ea156 --- /dev/null +++ b/front/src/components/feed/Media.tsx @@ -0,0 +1,35 @@ +import type { Media } from "@/types/trill"; +interface Props { + media: Media[]; +} +function M({ media }: Props) { + return ( + <div className="body-media"> + {media.map((m, i) => { + return "video" in m.media ? ( + <video key={JSON.stringify(m) + i} src={m.media.video} controls /> + ) : "audio" in m.media ? ( + <audio key={JSON.stringify(m) + i} src={m.media.audio} controls /> + ) : "images" in m.media ? ( + <Images key={JSON.stringify(m) + i} urls={m.media.images} /> + ) : null; + })} + </div> + ); +} +export default M; + +function Images({ urls }: { urls: string[] }) { + return ( + <> + {urls.map((u, i) => ( + <img + key={u + i} + className={`body-img body-img-1-of-${urls.length}`} + src={u} + alt="" + /> + ))} + </> + ); +} diff --git a/front/src/components/feed/NostrIcon.tsx b/front/src/components/feed/NostrIcon.tsx new file mode 100644 index 0000000..0c368fb --- /dev/null +++ b/front/src/components/feed/NostrIcon.tsx @@ -0,0 +1,22 @@ +import nostrIcon from "@/assets/icons/nostr.svg"; +import useLocalState from "@/state/state"; +import toast from "react-hot-toast"; +import type { Poast } from "@/types/trill"; +export default function ({ poast }: { poast: Poast }) { + const { relays, api, keys } = useLocalState(); + + async function sendToRelay(e: React.MouseEvent) { + e.stopPropagation(); + // + const urls = Object.keys(relays); + await api!.relayPost(poast.host, poast.id, urls); + toast.success("Post relayed"); + } + // TODO round up all helpers + + return ( + <div className="icon" role="link" onMouseUp={sendToRelay}> + <img role="link" src={nostrIcon} title="repost" /> + </div> + ); +} diff --git a/front/src/components/feed/Post.tsx b/front/src/components/feed/Post.tsx new file mode 100644 index 0000000..1211a97 --- /dev/null +++ b/front/src/components/feed/Post.tsx @@ -0,0 +1,79 @@ +import type { PostID, Poast, Reference } from "@/types/trill"; + +import Header from "./Header"; +import Body from "./Body"; +import Footer from "./Footer"; +import { useLocation } from "wouter"; +import useLocalState from "@/state/state"; +import RP from "./RP"; +import ShipModal from "../modals/ShipModal"; +import type { Ship } from "@/types/urbit"; +import Sigil from "../Sigil"; + +export interface PostProps { + poast: Poast; + fake?: boolean; + rter?: Ship; + rtat?: number; + rtid?: PostID; + nest?: number; + refetch: Function; +} +function Post(props: PostProps) { + const { poast } = props; + console.log({ poast }); + if (!poast || poast.contents === null) { + return null; + } + const isRP = + poast.contents.length === 1 && + "ref" in poast.contents[0] && + poast.contents[0].ref.type === "trill"; + if (isRP) { + const ref = (poast.contents[0] as Reference).ref; + return ( + <RP + host={ref.ship} + id={ref.path.slice(1)} + rter={poast.author} + rtat={poast.time} + rtid={poast.id} + /> + ); + } else return <TrillPost {...props} />; +} +export default Post; + +function TrillPost(props: PostProps) { + const { poast, fake } = props; + const { setModal } = useLocalState(); + const [_, navigate] = useLocation(); + function openThread(_e: React.MouseEvent) { + const sel = window.getSelection()?.toString(); + if (!sel) navigate(`/feed/${poast.host}/${poast.id}`); + } + + function openModal(e: React.MouseEvent) { + e.stopPropagation(); + setModal(<ShipModal ship={poast.author} />); + } + const avatar = ( + <div className="avatar-w sigil cp" role="link" onMouseUp={openModal}> + <Sigil patp={poast.author} size={42} /> + </div> + ); + return ( + <div + className={`timeline-post trill-post cp`} + role="link" + onMouseUp={openThread} + > + <div className="left">{avatar}</div> + <div className="right"> + <Header {...props} /> + <Body {...props} /> + {!fake && <Footer {...props} />} + </div> + </div> + ); +} diff --git a/front/src/components/feed/PostData.tsx b/front/src/components/feed/PostData.tsx new file mode 100644 index 0000000..f3c4715 --- /dev/null +++ b/front/src/components/feed/PostData.tsx @@ -0,0 +1,160 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import spinner from "@/assets/triangles.svg"; +import { useEffect, useRef, useState } from "react"; +import useLocalState from "@/state/state"; +import type { PostID } from "@/types/trill"; +import type { Ship } from "@/types/urbit"; + +function PostData(props: { + host: Ship; + id: PostID; + rter?: Ship; + rtat?: number; + rtid?: PostID; + nest?: number; // nested quotes + className?: string; +}) { + const { api } = useLocalState(); + const { host, id, nest } = props; + const [enest, setEnest] = useState(nest); + useEffect(() => { + setEnest(nest); + }, [nest]); + + return function (Component: React.ElementType) { + // const [showNested, setShowNested] = useState(nest <= 3); + const handleShowNested = (e: React.MouseEvent) => { + e.stopPropagation(); + setEnest(enest! - 3); + }; + const [dead, setDead] = useState(false); + const [denied, setDenied] = useState(false); + const { isLoading, isError, data, refetch } = useQuery({ + queryKey: ["trill-thread", host, id], + queryFn: fetchNode, + }); + const queryClient = useQueryClient(); + const dataRef = useRef(data); + useEffect(() => { + dataRef.current = data; + }, [data]); + + async function fetchNode(): Promise<any> { + const res = await api!.scryPost(host, id, null, null); + if ("fpost" in res) return res; + else { + const existing = queryClient.getQueryData(["trill-thread", host, id]); + const existingData = existing || data; + if ("bugen" in res) { + // we peek for the actual node + peekTheNode(); + // if we have a cache we don't invalidate it + if (existingData && "fpost" in existingData) return existingData; + // if we don't have a cache then we show the loading screen + else return res; + } + if ("no-node" in res) { + if (existingData && "fpost" in existingData) return existingData; + else return res; + } + } + } + function peekTheNode() { + let timer; + peekNode({ ship: host, id }); + timer = setTimeout(() => { + const gotPost = dataRef.current && "fpost" in dataRef.current; + setDead(!gotPost); + // clearTimeout(timer); + }, 10_000); + } + + useEffect(() => { + const path = `${host}/${id}`; + if (path in peekedPosts) { + queryClient.setQueryData(["trill-thread", host, id], { + fpost: peekedPosts[path], + }); + } else if (path in deniedPosts) { + setDenied(true); + } + }, [peekedPosts]); + useEffect(() => { + const path = `${host}/${id}`; + if (path in deniedPosts) setDenied(true); + }, [deniedPosts]); + + useEffect(() => { + const l = lastThread; + if (l && l.thread == id) { + queryClient.setQueryData(["trill-thread", host, id], { fpost: l }); + } + }, [lastThread]); + function retryPeek(e: React.MouseEvent) { + e.stopPropagation(); + setDead(false); + peekTheNode(); + } + if (enest > 3) + return ( + <div className={props.className}> + <div className="lazy x-center not-found"> + <button className="x-center" onMouseUp={handleShowNested}> + Load more + </button> + </div> + </div> + ); + else + return data ? ( + dead ? ( + <div className={props.className}> + <div className="no-response x-center not-found"> + <p>{host} did not respond</p> + <button className="x-center" onMouseUp={retryPeek}> + Try again + </button> + </div> + </div> + ) : denied ? ( + <div className={props.className}> + <p className="x-center not-found"> + {host} denied you access to this post + </p> + </div> + ) : "no-node" in data || "bucun" in data ? ( + <div className={props.className}> + <p className="x-center not-found">Post not found</p> + </div> + ) : "bugen" in data ? ( + <div className={props.className}> + <div className="x-center not-found"> + <p className="x-center">Post not found, requesting...</p> + <img src={spinner} className="x-center s-100" alt="" /> + </div> + </div> + ) : "fpost" in data && data.fpost.contents === null ? ( + <div className={props.className}> + <p className="x-center not-found">Post deleted</p> + </div> + ) : ( + <Component + data={data.fpost} + refetch={refetch} + {...props} + nest={enest} + /> + ) + ) : // no data + isLoading || isError ? ( + <div className={props.className}> + <img className="x-center post-spinner" src={spinner} alt="" /> + </div> + ) : ( + <div className={props.className}> + <p>...</p> + </div> + ); + }; +} +export default PostData; diff --git a/front/src/components/feed/PostList.tsx b/front/src/components/feed/PostList.tsx new file mode 100644 index 0000000..3d41ff8 --- /dev/null +++ b/front/src/components/feed/PostList.tsx @@ -0,0 +1,32 @@ +import TrillPost from "./Post"; +import type { FC } from "@/types/trill"; +// import { useEffect } from "react"; +// import { useQueryClient } from "@tanstack/react-query"; +// import { toFull } from "../thread/helpers"; + +function TrillFeed({ data, refetch }: { data: FC; refetch: Function }) { + // const qc = useQueryClient(); + // useEffect(() => { + // Object.values(data.feed).forEach((poast) => { + // const queryKey = ["trill-thread", poast.host, poast.id]; + // const existing = qc.getQueryData(queryKey); + // if (!existing || !("fpost" in (existing as any))) { + // qc.setQueryData(queryKey, { + // fpost: toFull(poast), + // }); + // } + // }); + // }, [data]); + return ( + <> + {Object.keys(data.feed) + .sort() + .reverse() + .map((i) => ( + <TrillPost key={i} poast={data.feed[i]} refetch={refetch} /> + ))} + </> + ); +} + +export default TrillFeed; diff --git a/front/src/components/feed/Quote.tsx b/front/src/components/feed/Quote.tsx new file mode 100644 index 0000000..d71be40 --- /dev/null +++ b/front/src/components/feed/Quote.tsx @@ -0,0 +1,37 @@ +import type { FullNode } from "@/types/trill"; +import { date_diff } from "@/logic/utils"; +import { useLocation } from "wouter"; +import Body from "./Body"; +import Sigil from "../Sigil"; +import { toFlat } from "./RP"; + +function Quote({ + data, + refetch, + nest, +}: { + data: FullNode; + refetch?: Function; + nest: number; +}) { + const [_, navigate] = useLocation(); + function gotoQuote(e: React.MouseEvent) { + e.stopPropagation(); + navigate(`/feed/${data.host}/${data.id}`); + } + return ( + <div onMouseUp={gotoQuote} className="quote-in-post"> + <header className="btw"> + ( + <div className="quote-author flex"> + <Sigil patp={data.author} size={20} /> + {data.author} + </div> + )<span>{date_diff(data.time, "short")}</span> + </header> + <Body poast={toFlat(data)} nest={nest} refetch={refetch!} /> + </div> + ); +} + +export default Quote; diff --git a/front/src/components/feed/RP.tsx b/front/src/components/feed/RP.tsx new file mode 100644 index 0000000..dc733cc --- /dev/null +++ b/front/src/components/feed/RP.tsx @@ -0,0 +1,47 @@ +import Post from "./Post"; +import type { Ship } from "@/types/urbit"; +import type { Poast, FullNode, ID } from "@/types/trill"; +import PostData from "./PostData"; +export default function (props: { + host: string; + id: string; + rter: Ship; + rtat: number; + rtid: ID; + refetch?: Function; +}) { + return PostData(props)(RP); +} + +function RP({ + data, + refetch, + rter, + rtat, + rtid, +}: { + data: FullNode; + refetch: Function; + rter: Ship; + rtat: number; + rtid: ID; +}) { + return ( + <Post + poast={toFlat(data)} + rter={rter} + rtat={rtat} + rtid={rtid} + refetch={refetch} + /> + ); +} + +export function toFlat(n: FullNode): Poast { + return { + ...n, + children: !n.children + ? [] + : Object.keys(n.children).map((c) => n.children[c].id), + }; +} diff --git a/front/src/components/feed/Reactions.tsx b/front/src/components/feed/Reactions.tsx new file mode 100644 index 0000000..58662cd --- /dev/null +++ b/front/src/components/feed/Reactions.tsx @@ -0,0 +1,118 @@ +import type { Poast } from "@/types/trill"; +import yeschad from "@/assets/reacts/yeschad.png"; +import cringe from "@/assets/reacts/cringe.png"; +import cry from "@/assets/reacts/cry.png"; +import doom from "@/assets/reacts/doom.png"; +import galaxy from "@/assets/reacts/galaxy.png"; +import gigachad from "@/assets/reacts/gigachad.png"; +import pepechin from "@/assets/reacts/pepechin.png"; +import pepeeyes from "@/assets/reacts/pepeeyes.png"; +import pepegmi from "@/assets/reacts/pepegmi.png"; +import pepesad from "@/assets/reacts/pepesad.png"; +import pink from "@/assets/reacts/pink.png"; +import soy from "@/assets/reacts/soy.png"; +import chad from "@/assets/reacts/chad.png"; +import pika from "@/assets/reacts/pika.png"; +import facepalm from "@/assets/reacts/facepalm.png"; +import emoji from "@/assets/icons/emoji.svg"; +import emojis from "@/logic/emojis.json"; +import Modal from "../modals/Modal"; +import useLocalState from "@/state/state"; + +export function ReactModal({ send }: { send: (s: string) => Promise<number> }) { + const { setModal } = useLocalState(); + async function sendReact(e: React.MouseEvent, s: string) { + e.stopPropagation(); + const res = await send(s); + if (res) setModal(null); + } + // todo one more meme + return ( + <Modal> + <div id="react-list"> + <span onMouseUp={(e) => sendReact(e, "❤️")}>️️❤️</span> + <span onMouseUp={(e) => sendReact(e, "🤔")}>🤔</span> + <span onMouseUp={(e) => sendReact(e, "😅")}>😅</span> + <span onMouseUp={(e) => sendReact(e, "🤬")}>🤬</span> + <span onMouseUp={(e) => sendReact(e, "😂")}>😂️</span> + <span onMouseUp={(e) => sendReact(e, "🫡")}>🫡️</span> + <span onMouseUp={(e) => sendReact(e, "🤢")}>🤢</span> + <span onMouseUp={(e) => sendReact(e, "😭")}>😭</span> + <span onMouseUp={(e) => sendReact(e, "😱")}>😱</span> + <img + onMouseUp={(e) => sendReact(e, "facepalm")} + src={facepalm} + alt="" + /> + <span onMouseUp={(e) => sendReact(e, "👍")}>👍️</span> + <span onMouseUp={(e) => sendReact(e, "👎")}>👎️</span> + <span onMouseUp={(e) => sendReact(e, "☝")}>☝️</span> + <span onMouseUp={(e) => sendReact(e, "🤝")}>🤝</span>️ + <span onMouseUp={(e) => sendReact(e, "🙏")}>🙏</span> + <span onMouseUp={(e) => sendReact(e, "🤡")}>🤡</span> + <span onMouseUp={(e) => sendReact(e, "👀")}>👀</span> + <span onMouseUp={(e) => sendReact(e, "🎤")}>🎤</span> + <span onMouseUp={(e) => sendReact(e, "💯")}>💯</span> + <span onMouseUp={(e) => sendReact(e, "🔥")}>🔥</span> + <img onMouseUp={(e) => sendReact(e, "yeschad")} src={yeschad} alt="" /> + <img + onMouseUp={(e) => sendReact(e, "gigachad")} + src={gigachad} + alt="" + /> + <img onMouseUp={(e) => sendReact(e, "pika")} src={pika} alt="" /> + <img onMouseUp={(e) => sendReact(e, "cringe")} src={cringe} alt="" /> + <img onMouseUp={(e) => sendReact(e, "pepegmi")} src={pepegmi} alt="" /> + <img onMouseUp={(e) => sendReact(e, "pepesad")} src={pepesad} alt="" /> + <img onMouseUp={(e) => sendReact(e, "galaxy")} src={galaxy} alt="" /> + <img onMouseUp={(e) => sendReact(e, "pink")} src={pink} alt="" /> + <img onMouseUp={(e) => sendReact(e, "soy")} src={soy} alt="" /> + <img onMouseUp={(e) => sendReact(e, "cry")} src={cry} alt="" /> + <img onMouseUp={(e) => sendReact(e, "doom")} src={doom} alt="" /> + </div> + </Modal> + ); +} + +export function stringToReact(s: string) { + const em = (emojis as Record<string, string>)[s.replace(/\:/g, "")]; + if (s === "yeschad") + return <img className="react-img" src={yeschad} alt="" />; + if (s === "facepalm") + return <img className="react-img" src={facepalm} alt="" />; + if (s === "yes.jpg") + return <img className="react-img" src={yeschad} alt="" />; + if (s === "gigachad") + return <img className="react-img" src={gigachad} alt="" />; + if (s === "pepechin") + return <img className="react-img" src={pepechin} alt="" />; + if (s === "pepeeyes") + return <img className="react-img" src={pepeeyes} alt="" />; + if (s === "pepegmi") + return <img className="react-img" src={pepegmi} alt="" />; + if (s === "pepesad") + return <img className="react-img" src={pepesad} alt="" />; + if (s === "") + return <img className="react-img no-react" src={emoji} alt="" />; + if (s === "cringe") return <img className="react-img" src={cringe} alt="" />; + if (s === "cry") return <img className="react-img" src={cry} alt="" />; + if (s === "crywojak") return <img className="react-img" src={cry} alt="" />; + if (s === "doom") return <img className="react-img" src={doom} alt="" />; + if (s === "galaxy") return <img className="react-img" src={galaxy} alt="" />; + if (s === "pink") return <img className="react-img" src={pink} alt="" />; + if (s === "pinkwojak") return <img className="react-img" src={pink} alt="" />; + if (s === "soy") return <img className="react-img" src={soy} alt="" />; + if (s === "chad") return <img className="react-img" src={chad} alt="" />; + if (s === "pika") return <img className="react-img" src={pika} alt="" />; + if (em) return <span className="react-icon">{em}</span>; + else if (s.length > 2) return <span className="react-icon"></span>; + else return <span className="react-icon">{s}</span>; +} + +export function TrillReactModal({ poast }: { poast: Poast }) { + const { api } = useLocalState(); + async function sendReact(s: string) { + return await api!.addReact(poast.host, poast.id, s); + } + return <ReactModal send={sendReact} />; +} diff --git a/front/src/components/feed/StatsModal.tsx b/front/src/components/feed/StatsModal.tsx new file mode 100644 index 0000000..4720b2a --- /dev/null +++ b/front/src/components/feed/StatsModal.tsx @@ -0,0 +1,106 @@ +import type { Poast } from "@/types/trill"; +import Modal from "../modals/Modal"; +import { useState } from "react"; +import Post from "./Post"; +import RP from "./RP"; +import Avatar from "../Avatar"; +import { stringToReact } from "./Reactions"; + +function StatsModal({ poast, close }: { close: any; poast: Poast }) { + const [tab, setTab] = useState("replies"); + const replies = poast.children || []; + const quotes = poast.engagement.quoted; + const reposts = poast.engagement.shared; + const reacts = poast.engagement.reacts; + function set(e: React.MouseEvent, s: string) { + e.stopPropagation(); + setTab(s); + } + // TODO revise the global thingy here + return ( + <Modal close={close}> + <div id="stats-modal"> + <Post poast={poast} refetch={() => {}} /> + <div id="tabs"> + <div + role="link" + className={"tab" + (tab === "replies" ? " active-tab" : "")} + onClick={(e) => set(e, "replies")} + > + <h4>Replies</h4> + </div> + <div + role="link" + className={"tab" + (tab === "quotes" ? " active-tab" : "")} + onClick={(e) => set(e, "quotes")} + > + <h4>Quotes</h4> + </div> + <div + role="link" + className={"tab" + (tab === "reposts" ? " active-tab" : "")} + onClick={(e) => set(e, "reposts")} + > + <h4>Reposts</h4> + </div> + <div + role="link" + className={"tab" + (tab === "reacts" ? " active-tab" : "")} + onClick={(e) => set(e, "reacts")} + > + <h4>Reacts</h4> + </div> + </div> + <div id="engagement"> + {tab === "replies" ? ( + <div id="replies"> + {replies.map((p) => ( + <div key={p} className="reply-stat"> + <RP + host={poast.host} + id={p} + rter={undefined} + rtat={undefined} + rtid={undefined} + /> + </div> + ))} + </div> + ) : tab === "quotes" ? ( + <div id="quotes"> + {quotes.map((p) => ( + <div key={p.pid.id} className="quote-stat"> + <RP + host={p.pid.ship} + id={p.pid.id} + rter={undefined} + rtat={undefined} + rtid={undefined} + /> + </div> + ))} + </div> + ) : tab === "reposts" ? ( + <div id="reposts"> + {reposts.map((p) => ( + <div key={p.pid.id} className="repost-stat"> + <Avatar p={p.pid.ship} size={40} /> + </div> + ))} + </div> + ) : tab === "reacts" ? ( + <div id="reacts"> + {Object.keys(reacts).map((p) => ( + <div key={p} className="react-stat btw"> + <Avatar p={p} size={32} /> + {stringToReact(reacts[p])} + </div> + ))} + </div> + ) : null} + </div> + </div> + </Modal> + ); +} +export default StatsModal; diff --git a/front/src/components/layout/Sidebar.tsx b/front/src/components/layout/Sidebar.tsx new file mode 100644 index 0000000..1568421 --- /dev/null +++ b/front/src/components/layout/Sidebar.tsx @@ -0,0 +1,81 @@ +import { RADIO, versionNum } from "@/logic/constants"; +import { useLocation } from "wouter"; +import useLocalState from "@/state/state"; +import key from "@/assets/icons/key.svg"; +import logo from "@/assets/icons/logo.png"; +import home from "@/assets/icons/home.svg"; +import bell from "@/assets/icons/bell.svg"; +import settings from "@/assets/icons/settings.svg"; +import messages from "@/assets/icons/messages.svg"; +import profile from "@/assets/icons/profile.svg"; +import pals from "@/assets/icons/pals.svg"; +import rumors from "@/assets/icons/rumors.svg"; +import { ThemeSwitcher } from "@/styles/ThemeSwitcher"; + +function SlidingMenu() { + const [_, navigate] = useLocation(); + const { api } = useLocalState(); + function goto(to: string) { + navigate(to); + } + return ( + <div id="left-menu"> + <div id="logo"> + <img src={logo} /> + <h3> Nostril </h3> + </div> + <h3>Feeds</h3> + <div className="opt" role="link" onClick={() => goto(`/feed/global`)}> + <img src={home} alt="" /> + <div>Home</div> + </div> + <div className="opt" role="link" onClick={() => goto(`/hark`)}> + <img src={bell} alt="" /> + <div>Activity</div> + </div> + <hr /> + + <div className="opt" role="link" onClick={() => goto("/chat")}> + <img src={messages} alt="" /> + <div>Messages</div> + </div> + <div className="opt" role="link" onClick={() => goto("/pals")}> + <img src={pals} alt="" /> + <div>Pals</div> + </div> + <hr /> + <div + className="opt" + role="link" + onClick={() => goto(`/feed/${api!.airlock.our}`)} + > + <img src={profile} alt="" /> + <div>Profile</div> + </div> + <div className="opt" role="link" onClick={() => goto("/feed/anon")}> + <img src={rumors} alt="" /> + <div>Rumors</div> + </div> + <hr /> + <div className="opt" role="link" onClick={() => goto("/radio")}> + <div className="img">{RADIO}</div> + <div>Radio</div> + </div> + <hr /> + <div + className="opt" + role="link" + onClick={() => (window.location.href = "/cookies")} + > + <img src={key} alt="" /> + <div>Logins</div> + </div> + <div className="opt" role="link" onClick={() => goto("/sets")}> + <img src={settings} alt="" /> + <div>Settings</div> + </div> + <ThemeSwitcher /> + </div> + ); +} +export default SlidingMenu; diff --git a/front/src/components/modals/Modal.tsx b/front/src/components/modals/Modal.tsx new file mode 100644 index 0000000..7dd688c --- /dev/null +++ b/front/src/components/modals/Modal.tsx @@ -0,0 +1,72 @@ +import useLocalState from "@/state/state"; +import { useEffect, useRef, useState } from "react"; + +function Modal({ children }: any) { + const { setModal } = useLocalState(); + function onKey(event: any) { + if (event.key === "Escape") setModal(null); + } + useEffect(() => { + document.addEventListener("keyup", onKey); + return () => { + document.removeEventListener("keyup", onKey); + }; + }, [children]); + + function clickAway(e: React.MouseEvent) { + console.log("clicked away"); + e.stopPropagation(); + if (!modalRef.current || !modalRef.current.contains(e.target)) + setModal(null); + } + const modalRef = useRef(null); + return ( + <div id="modal-background" onClick={clickAway}> + <div id="modal" ref={modalRef}> + {children} + </div> + </div> + ); +} +export default Modal; + +export function Welcome() { + return ( + <Modal> + <div id="welcome-msg"> + <h1>Welcome to Nostril!</h1> + <p> + Trill is the world's only truly free and sovereign social media + platform, powered by Urbit. + </p> + <p> + Click on the crow icon on the top left to see all available feeds. + </p> + <p>The Global feed should be populated by default.</p> + <p>Follow people soon so your Global feed doesn't go stale.</p> + <p> + Trill is still on beta. The UI is Mobile only, we recommend you use + your phone or the browser dev tools. Desktop UI is on the works. + </p> + <p> + If you have any feedback please reach out to us on Groups at + ~hoster-dozzod-sortug/trill or here at ~polwex + </p> + </div> + </Modal> + ); +} + +export function Tooltip({ children, text, className }: any) { + const [show, toggle] = useState(false); + return ( + <div + className={"tooltip-wrapper " + (className || "")} + onMouseOver={() => toggle(true)} + onMouseOut={() => toggle(false)} + > + {children} + {show && <div className="tooltip">{text}</div>} + </div> + ); +} diff --git a/front/src/components/modals/ShipModal.tsx b/front/src/components/modals/ShipModal.tsx new file mode 100644 index 0000000..86bffbb --- /dev/null +++ b/front/src/components/modals/ShipModal.tsx @@ -0,0 +1,45 @@ +import type { Ship } from "@/types/urbit"; +import Modal from "./Modal"; +import Avatar from "../Avatar"; +import copyIcon from "@/assets/icons/copy.svg"; +import useLocalState from "@/state/state"; +import { useLocation } from "wouter"; +import toast from "react-hot-toast"; + +export default function ({ ship }: { ship: Ship }) { + const { setModal, api } = useLocalState(); + const [_, navigate] = useLocation(); + function close() { + setModal(null); + } + async function copy(e: React.MouseEvent) { + e.stopPropagation(); + await navigator.clipboard.writeText(ship); + toast.success("Copied to clipboard"); + } + return ( + <Modal close={close}> + <div id="ship-modal"> + <div className="flex"> + <Avatar p={ship} size={60} /> + <img + className="copy-icon cp" + role="link" + onClick={copy} + src={copyIcon} + alt="" + /> + </div> + <div className="buttons f1"> + <button onClick={() => navigate(`/feed/${ship}`)}>Feed</button> + <button onClick={() => navigate(`/pals/${ship}`)}>Profile</button> + {ship !== api!.airlock.our && ( + <> + <button onClick={() => navigate(`/chat/dm/${ship}`)}>DM</button> + </> + )} + </div> + </div> + </Modal> + ); +} diff --git a/front/src/components/snippets/Snippets.tsx b/front/src/components/snippets/Snippets.tsx new file mode 100644 index 0000000..68f5446 --- /dev/null +++ b/front/src/components/snippets/Snippets.tsx @@ -0,0 +1,395 @@ +import { fetchTweet, lurkTweet } from "@/logic/twatter/calls"; +import { pokeDister, scryDister, scryGangs } from "@/logic/requests/tlon"; +import { useEffect, useState } from "react"; +import Tweet from "@/sections/twatter/Tweet"; +import { toFlat } from "@/sections/feed/thread/helpers"; +import PostData from "@/sections/feed/PostData"; +import Post from "@/sections/feed/post/Post"; +import { FullNode, SortugRef } from "@/types/trill"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { subscribe, unsub } from "@/logic/requests/generic"; +import { AppData, GroupMetadata } from "@/types/tlon"; +import comet from "@/assets/icons/comet.svg"; +import Sigil from "@/ui/Sigil"; +import { PollLoader } from "@/sections/feed/poll/Show"; +import { parseThread, parseTweet } from "@/logic/twatter/parser"; +import { Tweet as TweetType } from "@/types/twatter"; +import { scryRadio } from "@/logic/requests/nostril"; +import useLocalState from "@/state/state"; +import { RadioTower, ScheduledRadio, radioLink } from "@/logic/requests/radio"; +import { Ship } from "@/types/urbit"; +import { RADIO } from "@/logic/constants"; +import { SigilOnly } from "../Avatar"; +import { date_diff } from "@/logic/utils"; +import ShipsModal from "../modals/ShipsModal"; + +export function TrillSnippet({ r }: { r: SortugRef }) { + const { ship, path } = r; + return PostData({ host: ship, id: path.slice(1) })(TrillSnippetMarkup); +} +function TrillSnippetMarkup({ + data, + refetch, +}: { + data: FullNode; + refetch: Function; +}) { + return ( + <div className="trill-snippet"> + <Post poast={toFlat(data)} refetch={refetch} /> + </div> + ); +} +// <div +// onClick={() => { +// if (pop) pop(link); +// }} +// className="chat-snippet trill-snippet" +// > +// Post not found +// </div> +// ); + +export function TweetSnippet({ + link, + giveBack, +}: { + link: string; + giveBack?: Function; +}) { + const id = link.split("/")[5]; + const { isLoading, isError, data } = useQuery({ + queryKey: ["twatter-thread", id], + queryFn: () => lurkTweet(id), + }); + const [tw, setTw] = useState<TweetType>(); + useEffect(() => { + if (data && "thread-lurk" in data) { + const js = JSON.parse(data["thread-lurk"]).data.tweetResult; + if (JSON.stringify(js) === "{}") return; + if (giveBack) giveBack(JSON.stringify(parseTweet(js.result))); + } + }, [data]); + if (isLoading || isError) + return ( + <div className="tweet-snippet"> + <p>Fetching Tweet from your Urbit...</p> + </div> + ); + else { + if ("no-coki" in data) + return ( + <div id="cookie-error" className="x-center"> + <p className="">Your Twitter cookie isn't working correctly.</p> + <a href="/cookies">Check it out</a> + </div> + ); + if ("fail" in data) + return ( + <p> + Bad request. Please send some feedback (here) of what you were trying + to fetch. + </p> + ); + if ("thread-lurk" in data) { + const js = JSON.parse(data["thread-lurk"]).data.tweetResult; + if (JSON.stringify(js) === "{}") + return null; // TODO wtf + else + return ( + <div className="tweet-snippet"> + <Tweet tweet={parseTweet(js.result)} quote={true} /> + </div> + ); + } + // else { + // const head = parseThread(JSON.parse(data.thread)); + // const tweet = head.thread.tweets[0] + // giveBack(JSON.stringify(tweet)) + // return ( + // <div className="tweet-snippet"> + // <Tweet tweet={tweet} quote={true} /> + // </div> + // ); + // } + } +} + +export function AppSnippet({ r }: { r: SortugRef }) { + async function sub() { + if (!subn) { + const s = await subscribe( + "treaty", + "/treaties", + (data: { add: AppData }) => { + if ("ini" in data) { + const app = Object.values(data.ini).find((d) => d.desk === name); + setApp(app); + } + if ("add" in data && data.add.desk === name) setApp(data.add); + if (appData) unsub(subn); + }, + ); + setSub(s); + const res = await pokeDister(ship); + } + } + const { ship, path } = r; + const name = path.slice(1); + const [appData, setApp] = useState<AppData>(); + const [subn, setSub] = useState<number>(); + const { isLoading, data, isError } = useQuery({ + queryKey: ["dister", ship], + queryFn: () => scryDister(ship), + }); + if (isLoading || isError) return <div className="reference">...</div>; + else { + const app = Object.values(data.ini).find((d) => d.desk === name); + if (!app && !appData) sub(); + const a = app + ? app + : appData + ? appData + : { title: name, image: comet, info: "", ship }; + return ( + <div className="reference app-ref"> + <AppDiv app={a} /> + </div> + ); + } +} +function AppDiv({ app }: { app: Partial<AppData> }) { + return ( + <> + <img src={app.image} alt="" /> + <div className="text"> + <p className="app-name">{app.title}</p> + <p className="app-info">{app.info}</p> + <p className="app-host">App from {app.ship}</p> + </div> + <p className="ref-ship"> + <Sigil patp={app.ship} size={40} /> + </p> + </> + ); +} + +export function TlonSnippet({ r }: { r: SortugRef }) { + if (r.type === "app") return <AppSnippet r={r} />; + if (r.type === "groups") return <GroupSnippet r={r} />; +} +export function GroupSnippet({ r }: { r: SortugRef }) { + const queryClient = useQueryClient(); + async function sub() { + if (!subn) { + const path = `/gangs/index/${ship}`; + const s = await subscribe("groups", path, (data: any) => { + const key = `${ship}/${name}`; + const val = data[key]; + queryClient.setQueryData(["gangs"], (old: any) => { + return { ...old, [key]: { preview: val } }; + }); + }); + setSub(s); + } + } + const { ship, path } = r; + const name = path.slice(1); + const [groupData, setGroup] = useState<GroupMetadata>(); + const [subn, setSub] = useState<number>(); + const { isLoading, data, isError } = useQuery({ + queryKey: ["gangs"], + queryFn: scryGangs, + }); + if (isLoading || isError) return <div className="reference">...</div>; + else { + const group = data[`${ship}/${name}`]; + if (!group && !groupData) sub(); + const a = + group && group.preview + ? group.preview.meta + : groupData + ? groupData + : { title: name, image: comet, cover: "", description: "" }; + return ( + <div className="reference app-ref"> + {a.image.startsWith("#") ? ( + <div + className="group-color" + style={{ backgroundColor: a.image }} + ></div> + ) : ( + <img src={a.image} alt="" /> + )} + <div className="text"> + <p className="app-name">{a.title}</p> + <p className="app-info"> + {a.description.length > 25 + ? a.description.substring(0, 25) + "..." + : a.description} + </p> + <p className="group-host">Group by {ship}</p> + </div> + {/* <p className="ref-ship"> + <Sigil patp={ship} size={40} /> + </p> */} + </div> + ); + } +} + +export function PollSnippet({ r }: { r: SortugRef }) { + return ( + <div className="poll-snippet"> + <PollLoader ship={r.ship} id={r.path.slice(1)} /> + </div> + ); +} + +export function SnippetHandler(props: { r: SortugRef }) { + if (props.r.type === "trill") return <TrillSnippet r={props.r} />; + if (props.r.type === "trill-polls") return <PollSnippet r={props.r} />; + if (props.r.type === "app") return <AppSnippet r={props.r} />; + if (props.r.type === "groups") return <GroupSnippet r={props.r} />; +} + +export function RadioSnippet({ ship }: { ship: Ship }) { + const { our } = useLocalState(); + return ship === our ? <OwnRadio /> : <DudesRadio ship={ship} />; +} + +function DudesRadio({ ship }: { ship }) { + function onc() { + radioLink(ship); + } + const { radioTowers } = useLocalState(); + const tower = radioTowers.find((t) => t.location === ship); + if (!tower) + return ( + <div role="link" onMouseUp={onc} className="radio-snippet"> + <p className="img">{RADIO}</p> + <div className="radio-text"> + <p>Radio data not published. Click and check.</p>; + </div> + </div> + ); + else + return ( + <div role="link" onMouseUp={onc} className="radio-snippet"> + <p className="img">{RADIO}</p> + <div className="radio-text"> + <p>Radio Session. Playing: {tower.description}</p> + <p>Started {new Date(tower.time).toLocaleString()}</p> + </div> + <div> + <SigilOnly p={ship} size={42} /> + <span className="viewers"> + {tower.viewers} + <span>👀</span> + </span> + </div> + </div> + ); +} + +function OwnRadio() { + const { currentRadio, our, setModal, radioTowers } = useLocalState(); + const [scheduled, setS] = useState<ScheduledRadio | null>(null); + function onc() { + radioLink(our); + } + useEffect(() => { + scryRadio().then((r) => { + if (r) setS(r.radio); + }); + }, []); + function showViewers() { + const modal = ( + <ShipsModal + ships={currentRadio.viewers} + header={`People watching your %radio show`} + /> + ); + setModal(modal); + } + if (scheduled && scheduled.time > Date.now()) + return ( + <div role="link" onMouseUp={onc} className="radio-snippet"> + <p className="img">{RADIO}</p> + <div className="radio-text"> + <p> + Radio Session. Playing: + <a className="radio-link" href={scheduled.url}> + {scheduled.desc} + </a> + </p> + <p>Starting at {new Date(scheduled.time).toLocaleString()}</p> + </div> + <div> + <SigilOnly p={our} size={42} /> + </div> + </div> + ); + else if (!currentRadio) + return ( + <div role="link" onMouseUp={onc} className="radio-snippet"> + <p className="img">{RADIO}</p> + <div className="radio-text"> + <p>Radio unavailable</p> + </div> + </div> + ); + else + return ( + <div role="link" onMouseUp={onc} className="radio-snippet"> + <p className="img">{RADIO}</p> + <div className="radio-text"> + <p> + Radio Session. Playing: + <a className="radio-link" href={currentRadio.stream}> + {currentRadio.description} + </a> + </p> + {/* <p>Started {date_diff(currentRadio.time, "long")}</p> */} + </div> + <div> + <SigilOnly p={our} size={42} /> + <span onClick={showViewers} className="viewers"> + {currentRadio?.viewers?.length || ""} + <span>👀</span> + </span> + </div> + </div> + ); + + // return ( + // {scheduled > Date.now() + // ? (<> + // <p> + // Radio Session. Playing: + // <a className="radio-link" target="_blank" href={currentRadio.stream}> + // {currentRadio.description} + // </a> + // </p> + + // <p>Starting at {new Date(scheduled).toLocaleString()}</p> + // </> + + // ): scheduled !== 0() + + // } + // <p> + // Radio Session. Playing: + // <a className="radio-link" target="_blank" href={currentRadio.stream}> + // {currentRadio.description} + // </a> + // </p> + // {scheduled && scheduled > Date.now() ? ( + // <p>Starting at {new Date(scheduled).toLocaleString()}</p> + // ) : scheduled !== 0 ? ( + // <p>Started {date_diff(new Date(scheduled), "long")}. Click to join.</p> + // ) : ( + // <p>Unscheduled session. Click to join.</p> + // )} + // ); +} |