feat: start dashboard

This commit is contained in:
sam 2024-10-18 22:13:23 +02:00
parent bacbc6db0e
commit ec7aa9faba
Signed by: sam
GPG key ID: 5F3C3C1B3166639D
50 changed files with 3624 additions and 18 deletions

21
Catalogger.Frontend/.gitignore vendored Normal file
View file

@ -0,0 +1,21 @@
node_modules
# Output
.output
.vercel
.svelte-kit
build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

View file

@ -0,0 +1 @@
engine-strict=true

View file

@ -0,0 +1,4 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock

View file

@ -0,0 +1,5 @@
{
"useTabs": true,
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

View file

@ -0,0 +1,38 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

View file

@ -0,0 +1,32 @@
import eslint from "@eslint/js";
import prettier from "eslint-config-prettier";
import svelte from "eslint-plugin-svelte";
import globals from "globals";
import tseslint from "typescript-eslint";
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommended,
...svelte.configs["flat/recommended"],
prettier,
...svelte.configs["flat/prettier"],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node,
},
},
},
{
files: ["**/*.svelte"],
languageOptions: {
parserOptions: {
parser: tseslint.parser,
},
},
},
{
ignores: ["build/", ".svelte-kit/", "dist/"],
},
);

View file

@ -0,0 +1,35 @@
{
"name": "catalogger.frontend",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . && eslint .",
"format": "prettier --write ."
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.5",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"@sveltestrap/sveltestrap": "^6.2.7",
"@types/eslint": "^9.6.0",
"bootstrap": "^5.3.3",
"eslint": "^9.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.36.0",
"globals": "^15.0.0",
"prettier": "^3.1.1",
"prettier-plugin-svelte": "^3.1.2",
"sass": "^1.80.1",
"svelte": "^4.2.7",
"svelte-check": "^4.0.0",
"typescript": "^5.0.0",
"typescript-eslint": "^8.0.0",
"vite": "^5.0.3"
},
"type": "module"
}

13
Catalogger.Frontend/src/app.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View file

@ -0,0 +1,3 @@
@use "bootstrap/scss/bootstrap" with (
$color-mode-type: media-query
);

View file

@ -0,0 +1,55 @@
export type User = {
id: string;
tag: string;
avatar_url: string;
};
export type PartialGuild = {
id: string;
name: string;
icon_url: string;
bot_in_guild: boolean;
};
export type CurrentUser = {
user: User;
guilds: PartialGuild[];
};
export type AuthCallback = CurrentUser & { token: string };
export type ApiError = {
error_code: string;
message: string;
};
export const TOKEN_KEY = "catalogger-token";
export default async function apiFetch<T>(
method: "GET" | "POST" | "PATCH" | "DELETE",
path: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
body: any = null,
) {
const token = localStorage.getItem(TOKEN_KEY);
const headers = {
...(body != null
? { "Content-Type": "application/json; charset=utf-8" }
: {}),
...(token ? { Authorization: token } : {}),
};
const reqBody = body ? JSON.stringify(body) : undefined;
console.debug("Sending", method, "request to", path, "with body", reqBody);
const resp = await fetch(path, {
method,
body: body ? JSON.stringify(body) : undefined,
headers,
});
if (resp.status < 200 || resp.status > 299)
throw (await resp.json()) as ApiError;
return (await resp.json()) as T;
}

View file

@ -0,0 +1,51 @@
<script lang="ts">
import { goto } from "$app/navigation";
import { TOKEN_KEY, type User } from "$lib/api";
import { addToast } from "$lib/toast";
import {
Button,
Navbar,
NavbarBrand,
NavbarToggler,
Collapse,
Nav,
NavItem,
NavLink,
} from "@sveltestrap/sveltestrap";
export let user: User | null;
let isOpen = false;
const logOut = async () => {
localStorage.removeItem(TOKEN_KEY);
addToast({ header: "Logged out", body: "Successfully logged out." });
await goto("/", { invalidateAll: true });
};
</script>
<Navbar expand="lg">
<NavbarBrand href="/">Catalogger</NavbarBrand>
<NavbarToggler on:click={() => (isOpen = !isOpen)} />
<Collapse {isOpen} navbar expand="lg">
<Nav class="ms-auto" navbar>
<NavItem>
<NavLink href="/">Home</NavLink>
</NavItem>
{#if user}
<NavItem>
<NavLink href="/dash">Dashboard</NavLink>
</NavItem>
<NavItem>
<NavLink on:click={logOut}>Log out</NavLink>
</NavItem>
{:else}
<NavItem>
<NavLink href="/api/authorize">Log in with Discord</NavLink>
</NavItem>
{/if}
</Nav>
</Collapse>
</Navbar>

View file

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

View file

@ -0,0 +1,37 @@
import { writable } from "svelte/store";
export interface ToastData {
header?: string;
body: string;
duration?: number;
}
interface IdToastData extends ToastData {
id: number;
}
export const toastStore = writable<IdToastData[]>([]);
let maxId = 0;
export const addToast = (data: ToastData) => {
const id = maxId++;
toastStore.update((toasts) => (toasts = [...toasts, { ...data, id }]));
if (data.duration !== -1) {
setTimeout(() => {
toastStore.update(
(toasts) => (toasts = toasts.filter((toast) => toast.id !== id)),
);
}, data.duration ?? 5000);
}
return id;
};
export const delToast = (id: number) => {
toastStore.update(
(toasts) => (toasts = toasts.filter((toast) => toast.id !== id)),
);
};

View file

@ -0,0 +1,23 @@
<script lang="ts">
import Navbar from "$lib/components/Navbar.svelte";
import { toastStore } from "$lib/toast";
import { Toast, ToastHeader, ToastBody } from "@sveltestrap/sveltestrap";
import "../app.scss";
import type { LayoutData } from "./$types";
export let data: LayoutData;
</script>
<Navbar user={data.user} />
<div class="container">
<slot />
<div class="position-absolute top-0 start-50 translate-middle-x">
{#each $toastStore as toast}
<Toast>
{#if toast.header}<ToastHeader>{toast.header}</ToastHeader>{/if}
<ToastBody>{toast.body}</ToastBody>
</Toast>
{/each}
</div>
</div>

View file

@ -0,0 +1,21 @@
import { building } from "$app/environment";
import apiFetch, { TOKEN_KEY, type CurrentUser } from "$lib/api";
export const ssr = false;
export const csr = true;
export const prerender = true;
export const load = async () => {
const token = localStorage.getItem(TOKEN_KEY);
let user: CurrentUser | null = null;
if (token && !building) {
try {
user = await apiFetch<CurrentUser>("GET", "/api/current-user");
} catch (e) {
console.error("Could not fetch user from API: ", e);
localStorage.removeItem(TOKEN_KEY);
}
}
return { user: user?.user || null, guilds: user?.guilds || null };
};

View file

@ -0,0 +1,22 @@
<script lang="ts">
import apiFetch from "$lib/api";
import { onMount } from "svelte";
let guildCount: number | null = 0;
type MetaResponse = { guilds: number };
onMount(async () => {
const meta = await apiFetch<MetaResponse>("GET", "/api/meta");
guildCount = meta.guilds;
});
</script>
<h1>Welcome to SvelteKit</h1>
<p>
Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation
</p>
<p>
In {guildCount ?? "(loading)"} servers!
</p>

View file

@ -0,0 +1 @@
export const prerender = true;

View file

@ -0,0 +1,54 @@
<script lang="ts">
import { goto } from "$app/navigation";
import apiFetch, { TOKEN_KEY, type AuthCallback } from "$lib/api";
import { addToast } from "$lib/toast";
import { onMount } from "svelte";
import type { PageData } from "./$types";
let error = false;
export let data: PageData;
onMount(async () => {
const params = new URLSearchParams(window.location.search);
const code = params.get("code");
const state = params.get("state");
if (data.user) {
addToast({ header: "Cannot log in", body: "You are already logged in." });
await goto("/dash");
return;
}
if (!code || !state) {
addToast({
header: "Cannot log in",
body: "Missing 'code' or 'state' parameters.",
});
await goto("/");
return;
}
try {
const resp = await apiFetch<AuthCallback>("POST", "/api/callback", {
code,
state,
});
localStorage.setItem(TOKEN_KEY, resp.token);
await goto("/dash", { invalidateAll: true });
} catch (e) {
console.error("Callback request failed: ", e);
error = true;
}
});
</script>
{#if !error}
<h1>Loading...</h1>
<p>You should be redirected to the dashboard within a few seconds.</p>
{:else}
<h1>Could not log in</h1>
<p>An error occurred while logging in with Discord. Please try again.</p>
{/if}

View file

@ -0,0 +1 @@
<slot />

View file

@ -0,0 +1,12 @@
import { addToast } from "$lib/toast";
import { redirect } from "@sveltejs/kit";
export const load = async ({ parent }) => {
const data = await parent();
if (!data.user) {
addToast({ body: "You are not logged in." });
redirect(303, "/");
}
return { user: data.user!, guilds: data.guilds! };
};

View file

@ -0,0 +1,48 @@
<script lang="ts">
import { ListGroup, ListGroupItem } from "@sveltestrap/sveltestrap";
import type { PageData } from "./$types";
export let data: PageData;
$: joinedGuilds = data.guilds.filter((g) => g.bot_in_guild);
$: unjoinedGuilds = data.guilds.filter((g) => !g.bot_in_guild);
</script>
<h1>Manage your servers</h1>
<div class="row">
{#if joinedGuilds.length > 0}
<div class="col-lg">
<h2>Servers you can manage</h2>
<ListGroup>
{#each joinedGuilds as guild (guild.id)}
<ListGroupItem tag="a" href="/dash/{guild.id}">
<img
src={guild.icon_url}
alt="Icon for {guild.name}"
style="border-radius: 0.75em; height: 1.5em;"
/>
{guild.name}
</ListGroupItem>
{/each}
</ListGroup>
</div>
{/if}
{#if unjoinedGuilds.length > 0}
<div class="col-lg">
<h2>Servers you can add Catalogger to</h2>
<ListGroup>
{#each unjoinedGuilds as guild (guild.id)}
<ListGroupItem tag="a" href="/api/add-guild/{guild.id}">
<img
src={guild.icon_url}
alt="Icon for {guild.name}"
style="border-radius: 0.75em; height: 1.5em;"
/>
{guild.name}
</ListGroupItem>
{/each}
</ListGroup>
</div>
{/if}
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -0,0 +1,20 @@
import adapter from "@sveltejs/adapter-static";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter({
fallback: "index.html",
}),
},
};
export default config;

View file

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

View file

@ -0,0 +1,18 @@
import { sveltekit } from "@sveltejs/kit/vite";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [sveltekit()],
server: {
proxy: {
"/api": {
target: "http://localhost:5005",
changeOrigin: true,
},
},
hmr: {
host: "localhost",
protocol: "ws",
},
},
});

File diff suppressed because it is too large Load diff