diff --git a/src/app.html b/src/app.html index 41147b96..4e1b63ae 100644 --- a/src/app.html +++ b/src/app.html @@ -2,7 +2,7 @@ - + %sveltekit.head% diff --git a/src/hooks.server.ts b/src/hooks.server.ts index f6a13b19..f3f87e04 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -1,19 +1,27 @@ import { error } from '@sveltejs/kit' +function buildUrl(inputUrl: URL): URL { + let withoutCors = inputUrl.pathname.replace('/cors/', '') + + if (!withoutCors.startsWith('https://')) { + withoutCors = 'https://' + withoutCors + } + + return new URL(`${withoutCors}?${inputUrl.searchParams.toString()}`) +} + export async function handle({ event, resolve }) { // annoying hack to fix lemmy's CORS if (event.url.pathname.startsWith('/cors')) { - const instance = `${event.url.pathname.split('/')[2]}` - const url = `${event.url.pathname - .split('/') - .slice(3) - .join('/')}?${event.url.searchParams.toString()}` + // cut off the 1st slash (empty), and remove the /cors event.request.headers.delete('origin') event.request.headers.delete('host') try { - const data = await fetch(`https://${instance}/${url.toString()}`, { + const url = buildUrl(event.url) + + const data = await fetch(url, { method: event.request.method, body: event.request.body, headers: event.request.headers, @@ -22,9 +30,33 @@ export async function handle({ event, resolve }) { signal: AbortSignal.timeout(20 * 1000), }) - const json = await data.json() + if (!data.ok) { + return new Response( + JSON.stringify({ + message: await data.text(), + }), + { + status: data.status, + } + ) + } - return new Response(JSON.stringify(json)) + try { + const json = await data.json() + + return new Response(JSON.stringify(json), { + status: data.status, + }) + } catch (err) { + return new Response( + JSON.stringify({ + message: 'Failed to fetch', + }), + { + status: data.status, + } + ) + } } catch (error) { console.error(error) return new Response( diff --git a/src/lib/components/community/CommunityLink.svelte b/src/lib/components/community/CommunityLink.svelte index ee1d94aa..0ef51309 100644 --- a/src/lib/components/community/CommunityLink.svelte +++ b/src/lib/components/community/CommunityLink.svelte @@ -7,13 +7,13 @@ function linkFromCommunity(community: Community) { const local = community.local - if (local) { - return `/c/${community.name}` - } else { - const domain = new URL(community.actor_id).hostname + // if (local) { + // return `/c/${community.name}` + // } else { + const domain = new URL(community.actor_id).hostname - return `/c/${community.name}@${domain}` - } + return `/c/${community.name}@${domain}` + // } } @@ -26,6 +26,7 @@ width={24} height={24} class="rounded-full aspect-square object-cover" + loading="lazy" /> {/if} {community.title} diff --git a/src/routes/post/[id]/Avatar.svelte b/src/lib/components/ui/Avatar.svelte similarity index 51% rename from src/routes/post/[id]/Avatar.svelte rename to src/lib/components/ui/Avatar.svelte index 95905de2..6619e1db 100644 --- a/src/routes/post/[id]/Avatar.svelte +++ b/src/lib/components/ui/Avatar.svelte @@ -5,4 +5,10 @@ export let width: number - + diff --git a/src/lib/components/ui/Navbar.svelte b/src/lib/components/ui/Navbar.svelte index 4ebad951..ee868d62 100644 --- a/src/lib/components/ui/Navbar.svelte +++ b/src/lib/components/ui/Navbar.svelte @@ -1,9 +1,16 @@ + +
+
+ +
+

{toast.title}

+

{toast.content}

+
+ +
diff --git a/src/lib/components/ui/toasts/ToastContainer.svelte b/src/lib/components/ui/toasts/ToastContainer.svelte new file mode 100644 index 00000000..10d16566 --- /dev/null +++ b/src/lib/components/ui/toasts/ToastContainer.svelte @@ -0,0 +1,19 @@ + + +
+ {#each $toasts as toast (toast.id)} +
+ +
+ {/each} +
diff --git a/src/lib/components/ui/toasts/toasts.ts b/src/lib/components/ui/toasts/toasts.ts new file mode 100644 index 00000000..e59834e9 --- /dev/null +++ b/src/lib/components/ui/toasts/toasts.ts @@ -0,0 +1,39 @@ +import { writable } from 'svelte/store' + +export enum ToastType { + 'error' = 'from-red-400 to-red-400 text-red-400', + 'warning' = 'from-yellow-300 to-yellow-300 text-yellow-300', + 'success' = 'from-green-400 to-green-400 text-green-400', + 'info' = '', +} + +export interface Toast { + id: number + title: string + content: string + type: ToastType +} + +export const toasts = writable([]) + +export function addToast(title: string, content: string, type: ToastType) { + let id = 0 + + toasts.update((toasts) => { + id = Math.floor(Math.random() * 10000) + + return [ + { + id: id, + content: content, + title: title, + type: type, + }, + ...toasts, + ] + }) + + setTimeout(() => { + toasts.update((toasts) => toasts.filter((toast) => toast.id != id)) + }, 5000) +} diff --git a/src/lib/lemmy.ts b/src/lib/lemmy.ts index 3a45cb20..2cec0218 100644 --- a/src/lib/lemmy.ts +++ b/src/lib/lemmy.ts @@ -3,13 +3,17 @@ import { LemmyHttp, type LoginResponse, } from 'lemmy-js-client' -import { writable } from 'svelte/store' +import { get, writable } from 'svelte/store' import { PUBLIC_PROXY_URL } from '$env/static/public' export const DEFAULT_INSTANCE_URL = 'programming.dev' export let instance_url = writable(DEFAULT_INSTANCE_URL) -export function getClient(instance: string = `programming.dev`): LemmyHttp { +export function getClient(instance?: string): LemmyHttp { + if (!instance) { + instance = get(authData)?.instance ?? DEFAULT_INSTANCE_URL + } + return new LemmyHttp(`${PUBLIC_PROXY_URL}/cors/${instance}`) } @@ -19,18 +23,20 @@ export interface AuthData { instance: string } -export const authData = writable() -export const user = writable() - -if (typeof localStorage != 'undefined') { - if (localStorage.getItem('user')) { - try { - authData.set(JSON.parse(localStorage.getItem('user') ?? '')) - } catch (error) { - localStorage.removeItem('user') +export const authData = writable( + await (() => { + if (typeof localStorage != 'undefined') { + if (localStorage.getItem('user')) { + try { + return JSON.parse(localStorage.getItem('user') ?? '') + } catch (error) { + localStorage.removeItem('user') + } + } } - } -} + })() +) +export const user = writable() authData.subscribe(async (data) => { if (!data) return diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index ddf51007..49c85724 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -4,6 +4,7 @@ import { navigating, page } from '$app/stores' import nProgress from 'nprogress' import 'nprogress/nprogress.css' + import ToastContainer from '$lib/components/ui/toasts/ToastContainer.svelte' nProgress.configure({ minimum: 0.4, @@ -22,6 +23,7 @@ +
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index e26f4258..7407b4d8 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -14,7 +14,7 @@ PencilSquare, UserGroup, } from 'svelte-hero-icons' - import Avatar from './post/[id]/Avatar.svelte' + import Avatar from '../lib/components/ui/Avatar.svelte' import Post from './post/[id]/Post.svelte' import FormattedNumber from '$lib/components/util/FormattedNumber.svelte' import Markdown from '$lib/components/markdown/Markdown.svelte' diff --git a/src/routes/c/[name]/+page.svelte b/src/routes/c/[name]/+page.svelte index 7974f24d..307b746e 100644 --- a/src/routes/c/[name]/+page.svelte +++ b/src/routes/c/[name]/+page.svelte @@ -3,7 +3,7 @@ import Link from '$lib/components/input/Link.svelte' import MultiSelect from '$lib/components/input/MultiSelect.svelte' import SvelteMarkdown from 'svelte-markdown' - import Avatar from '../../post/[id]/Avatar.svelte' + import Avatar from '../../../lib/components/ui/Avatar.svelte' import Post from '../../post/[id]/Post.svelte' import { goto } from '$app/navigation' import RelativeDate from '$lib/components/util/RelativeDate.svelte' diff --git a/src/routes/c/[name]/+page.ts b/src/routes/c/[name]/+page.ts index 5e9a538b..cd1842cf 100644 --- a/src/routes/c/[name]/+page.ts +++ b/src/routes/c/[name]/+page.ts @@ -1,5 +1,6 @@ -import { getClient } from '$lib/lemmy.js' +import { authData, getClient } from '$lib/lemmy.js' import type { ListingType, SortType } from 'lemmy-js-client' +import { get } from 'svelte/store' export function load(req: any) { const page = Number(req.url.searchParams.get('page') || 1) || 1 @@ -13,6 +14,7 @@ export function load(req: any) { community_name: req.params.name, page: page, sort: sort, + auth: get(authData)?.token, }), streamed: { community: getClient().getCommunity({ diff --git a/src/routes/communities/+page.svelte b/src/routes/communities/+page.svelte index 552f6633..a66ae8e0 100644 --- a/src/routes/communities/+page.svelte +++ b/src/routes/communities/+page.svelte @@ -12,6 +12,7 @@ import CommunityLink from '$lib/components/community/CommunityLink.svelte' import Link from '$lib/components/input/Link.svelte' import { Color } from '$lib/ui/colors.js' + import TextInput from '$lib/components/input/TextInput.svelte' export let data @@ -32,7 +33,7 @@ }} />
- + import { goto } from '$app/navigation' import Button from '$lib/components/input/Button.svelte' import TextInput from '$lib/components/input/TextInput.svelte' import Card from '$lib/components/ui/Card.svelte' + import { ToastType, addToast } from '$lib/components/ui/toasts/toasts.js' import { DEFAULT_INSTANCE_URL, authData, getClient } from '$lib/lemmy.js' import { Color } from '$lib/ui/colors.js' let data = { + instance: DEFAULT_INSTANCE_URL, username: '', password: '', loading: false, } + async function validateURL(instance: string): Promise { + if (instance == '') return false + + if (!instance.startsWith('https://')) { + instance = 'https://' + instance + } + + const url = new URL(instance) + + try { + await getClient(url.toString()).getSite({}) + } catch (err) { + throw new Error('Invalid instance URL') + } + + return true + } + async function logIn() { data.loading = true try { - const response = await getClient().login({ + if (!(await validateURL(data.instance))) { + throw new Error('Invalid instance URL') + } + + const response = await getClient(data.instance).login({ username_or_email: data.username, password: data.password, }) - if (response.jwt) { + if (response?.jwt) { authData.set({ - instance: DEFAULT_INSTANCE_URL, + instance: data.instance, token: response.jwt, username: data.username, }) + + addToast('Success', 'Successfully logged in.', ToastType.success) + goto('/') + } else { + throw new Error('Invalid credentials') } } catch (error) { - alert('failed') + addToast('Error', error as any, ToastType.error) } data.loading = false } @@ -36,6 +66,11 @@

Log in

+ undefined) - - node.comment_view.my_vote = Number(!upvoted) } async function downvote() { @@ -43,6 +43,8 @@ const upvoted = node.comment_view.my_vote == -1 + node.comment_view.my_vote = -Number(!upvoted) + await getClient() .likeComment({ score: upvoted ? 0 : -1, @@ -50,8 +52,6 @@ comment_id: node.comment_view.comment.id, }) .catch((_) => undefined) - - node.comment_view.my_vote = -Number(!upvoted) } diff --git a/src/routes/post/[id]/comment/CommentForm.svelte b/src/routes/post/[id]/comment/CommentForm.svelte index 688562e1..f571ad22 100644 --- a/src/routes/post/[id]/comment/CommentForm.svelte +++ b/src/routes/post/[id]/comment/CommentForm.svelte @@ -4,6 +4,7 @@ import type { Comment, Post } from 'lemmy-js-client' import { authData, getClient, user } from '$lib/lemmy.js' import { createEventDispatcher } from 'svelte' + import { ToastType, addToast } from '$lib/components/ui/toasts/toasts.js' export let postId: number export let parentId: number | undefined = undefined @@ -28,8 +29,13 @@ dispatch('comment', response) newComment = '' + addToast( + 'Success', + 'Your comment was added. You may need to refresh to see it.', + ToastType.success + ) } catch (err) { - alert('Failed to comment') + addToast('Error', 'Failed to comment.', ToastType.error) } loading = false diff --git a/static/img/logo-background.svg b/static/img/logo-background.svg new file mode 100644 index 00000000..cc6fca1f --- /dev/null +++ b/static/img/logo-background.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file