feat: so much more frontend stuff

This commit is contained in:
sam 2024-11-24 22:19:53 +01:00
parent c179669799
commit 261435c252
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
24 changed files with 682 additions and 107 deletions

View file

@ -6,10 +6,12 @@ import log from "$lib/log";
import type { LayoutServerLoad } from "./$types";
export const load = (async ({ fetch, cookies }) => {
let token: string | null = null;
let meUser: MeUser | null = null;
if (cookies.get(TOKEN_COOKIE_NAME)) {
try {
meUser = await apiRequest<MeUser>("GET", "/users/@me", { fetch, cookies });
token = cookies.get(TOKEN_COOKIE_NAME) || null;
} catch (e) {
if (e instanceof ApiError && e.code === ErrorCode.AuthenticationRequired) clearToken(cookies);
else log.error("Could not fetch /users/@me and token has not expired:", e);
@ -17,5 +19,5 @@ export const load = (async ({ fetch, cookies }) => {
}
const meta = await apiRequest<Meta>("GET", "/meta", { fetch, cookies });
return { meta, meUser };
return { meta, meUser, token };
}) satisfies LayoutServerLoad;

View file

@ -1,5 +1,5 @@
import { apiRequest } from "$api";
import type { UserWithMembers } from "$api/models";
import type { PartialMember, UserWithMembers } from "$api/models";
export const load = async ({ params, fetch, cookies, url }) => {
const user = await apiRequest<UserWithMembers>("GET", `/users/${params.username}`, {
@ -8,12 +8,17 @@ export const load = async ({ params, fetch, cookies, url }) => {
});
// Paginate members on the server side
let currentPage = Number(url.searchParams.get("page") || "0");
const pageCount = Math.ceil(user.members.length / 20);
let members = user.members.slice(currentPage * 20, (currentPage + 1) * 20);
if (members.length === 0) {
members = user.members.slice(0, 20);
currentPage = 0;
let currentPage = 0;
let pageCount = 0;
let members: PartialMember[] = [];
if (user.members) {
currentPage = Number(url.searchParams.get("page") || "0");
pageCount = Math.ceil(user.members.length / 20);
members = user.members.slice(currentPage * 20, (currentPage + 1) * 20);
if (members.length === 0) {
members = user.members.slice(0, 20);
currentPage = 0;
}
}
return { user, members, currentPage, pageCount };

View file

@ -4,5 +4,5 @@ export const load = async ({ parent }) => {
const data = await parent();
if (!data.meUser) redirect(303, "/auth/log-in");
return { user: data.meUser! };
return { user: data.meUser!, token: data.token! };
};

View file

@ -29,7 +29,8 @@
</FormGroup>
{#if form?.ok}
<p class="text-success-emphasis">
<Icon name="check-circle-fill" /> Successfully changed your username!
<Icon name="check-circle-fill" />
{$t("settings.username-update-success")}
</p>
{:else if usernameError}
<p class="text-danger-emphasis text-has-newline">
@ -46,7 +47,7 @@
</p>
</div>
<div class="col-md-3 text-center">
<h5>Avatar</h5>
<h5>{$t("settings.avatar")}</h5>
<Avatar
url={data.user.avatar_url}
alt={$t("avatar-tooltip", { name: "@" + data.user.username })}

View file

@ -0,0 +1,42 @@
<script lang="ts">
import type { Snippet } from "svelte";
import { page } from "$app/stores";
import { t } from "$lib/i18n";
type Props = { children: Snippet };
let { children }: Props = $props();
const isActive = (path: string) => $page.url.pathname === path;
</script>
<h3>{$t("edit-profile.user-header")}</h3>
<div class="row">
<div class="col-md-3 mt-1 mb-3">
<div class="list-group">
<a
href="/settings/profile"
class="list-group-item list-group-item-action"
class:active={isActive("/settings/profile")}
>
{$t("edit-profile.general-tab")}
</a>
<a
href="/settings/profile/names-pronouns"
class="list-group-item list-group-item-action"
class:active={isActive("/settings/profile/names-pronouns")}
>
{$t("edit-profile.names-pronouns-tab")}
</a>
<a
href="/settings/profile/bio"
class="list-group-item list-group-item-action"
class:active={isActive("/settings/profile/bio")}
>
{$t("edit-profile.bio-tab")}
</a>
</div>
</div>
<div class="col-md-9">
{@render children?.()}
</div>
</div>

View file

@ -0,0 +1,29 @@
import { apiRequest, fastRequest } from "$api";
import ApiError from "$api/error";
import log from "$lib/log.js";
export const actions = {
options: async ({ request, fetch, cookies }) => {
const body = await request.formData();
let memberTitle = body.get("member-title") as string | null;
if (!memberTitle || memberTitle === "") memberTitle = null;
let timezone = body.get("timezone") as string | null;
if (!timezone || timezone === "") timezone = null;
let hideMemberList = !!body.get("hide-member-list");
try {
await fastRequest("PATCH", "/users/@me", {
body: { timezone, member_title: memberTitle, member_list_hidden: hideMemberList },
fetch,
cookies,
});
return { error: null, ok: true };
} catch (e) {
if (e instanceof ApiError) return { error: e.obj, ok: false };
log.error("Error patching user:", e);
throw e;
}
},
};

View file

@ -0,0 +1,190 @@
<script lang="ts">
import type { ActionData, PageData } from "./$types";
import { t } from "$lib/i18n";
import { Button, ButtonGroup, Icon, InputGroup } from "@sveltestrap/sveltestrap";
import { PUBLIC_SHORT_URL } from "$env/static/public";
import AvatarEditor from "$components/editor/AvatarEditor.svelte";
import { apiRequest, fastRequest } from "$api";
import ApiError from "$api/error";
import ErrorAlert from "$components/ErrorAlert.svelte";
import type { MeUser } from "$api/models/user";
import log from "$lib/log";
import { DateTime, FixedOffsetZone } from "luxon";
import FormStatusMarker from "$components/editor/FormStatusMarker.svelte";
type Props = { data: PageData; form: ActionData };
let { data, form }: Props = $props();
let error: ApiError | null = $state(null);
const copySid = async () => {
const url = `${PUBLIC_SHORT_URL}/${data.user.sid}`;
await navigator.clipboard.writeText(url);
};
// Editable properties
let sid = $state(data.user.sid);
let lastSidReroll = $state(data.user.last_sid_reroll);
let tz = $state(data.user.timezone === "<none>" ? null : data.user.timezone);
// Timezone code
const validTimezones = Intl.supportedValuesOf("timeZone");
const detectTimezone = () => {
tz = DateTime.local().zoneName;
};
// Timezone code
let currentTime = $state("");
let displayTimezone = $state("");
$effect(() => {
if (!tz || tz === "") {
currentTime = "";
displayTimezone = "";
return;
}
const offset = DateTime.now().setZone(tz).offset;
const zone = FixedOffsetZone.instance(offset);
currentTime = DateTime.now().setZone(zone).toLocaleString(DateTime.TIME_SIMPLE);
displayTimezone = zone.formatOffset(DateTime.now().toUnixInteger(), "narrow");
});
// SID reroll code
// We compare the current time with the user's last SID reroll time. If it's more than an hour ago, it can be rerolled.
let canRerollSid = $derived(
DateTime.now().toLocal().diff(DateTime.fromISO(lastSidReroll).toLocal(), "hours").hours >= 1,
);
const rerollSid = async () => {
try {
const resp = await apiRequest<MeUser>("POST", "/users/@me/reroll-sid", { token: data.token });
sid = resp.sid;
lastSidReroll = resp.last_sid_reroll;
error = null;
} catch (e) {
log.error("Could not reroll sid:", e);
if (e instanceof ApiError) error = e;
}
};
// Passed to AvatarEditor
let updated = $state(false);
const updateAvatar = async (avatar: string) => {
try {
await fastRequest("PATCH", "/users/@me", {
body: { avatar },
token: data.token,
});
updated = true;
error = null;
} catch (e) {
log.error("Could not update avatar:", e);
if (e instanceof ApiError) error = e;
}
};
</script>
{#if error}
<ErrorAlert error={error.obj} />
{/if}
<div class="row">
<div class="col-md">
<h4>{$t("settings.avatar")}</h4>
<AvatarEditor
current={data.user.avatar_url}
alt={$t("avatar-tooltip", { name: "@" + data.user.username })}
onclick={updateAvatar}
{updated}
/>
</div>
<div class="col-md">
<h4>{$t("edit-profile.sid")}</h4>
{$t("edit-profile.sid-current")} <code>{sid}</code>
<ButtonGroup class="mb-1">
<Button color="secondary" onclick={() => rerollSid()} disabled={!canRerollSid}>
{$t("edit-profile.sid-reroll")}
</Button>
<Button color="secondary" onclick={() => copySid()}>
<Icon name="link-45deg" aria-hidden />
<span class="visually-hidden">{$t("edit-profile.sid-copy")}</span>
</Button>
</ButtonGroup>
<p class="text-muted">
<Icon name="info-circle-fill" aria-hidden />
{$t("edit-profile.sid-hint")}
</p>
</div>
</div>
<div class="mt-3">
<h4>{$t("edit-profile.profile-options-header")}</h4>
<FormStatusMarker {form} />
<form method="POST" action="?/options">
<div class="mb-3">
<label class="form-label" for="member-title">{$t("edit-profile.member-header-label")}</label>
<input
type="text"
id="member-title"
name="member-title"
class="form-control"
value={data.user.member_title}
placeholder={$t("profile.default-members-header")}
/>
<p class="text-muted mt-1">
<Icon name="info-circle-fill" aria-hidden />
{$t("edit-profile.member-header-info")}
</p>
</div>
<div class="mb-3">
<label class="form-label" for="timezone">{$t("edit-profile.timezone-label")}</label>
<InputGroup>
<input
type="text"
id="timezone"
name="timezone"
class="form-control"
list="timezones"
bind:value={tz}
/>
<datalist id="timezones">
{#each validTimezones as timezone}<option value={timezone}></option>{/each}
</datalist>
<button type="button" class="btn btn-secondary" onclick={() => detectTimezone()}>
Detect timezone
</button>
</InputGroup>
{#if tz && tz !== "" && validTimezones.includes(tz)}
<div class="mt-1">
{$t("edit-profile.timezone-preview")}
<Icon name="clock" aria-hidden />
{currentTime} <span class="text-body-secondary">(UTC{displayTimezone})</span>
</div>
{/if}
<p class="text-muted mt-1">
<Icon name="info-circle-fill" aria-hidden />
{$t("edit-profile.timezone-info")}
</p>
</div>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
checked={data.user.member_list_hidden}
value="true"
name="hide-member-list"
id="hide-member-list"
/>
<label class="form-check-label" for="hide-member-list">
{$t("edit-profile.hide-member-list-label")}
</label>
</div>
<p class="text-muted mt-1">
<Icon name="info-circle-fill" aria-hidden />
{$t("edit-profile.hide-member-list-info")}
</p>
<div class="mt-2">
<button type="submit" class="btn btn-primary">{$t("save-changes")}</button>
</div>
</form>
</div>

View file

@ -0,0 +1,19 @@
import { fastRequest } from "$api";
import ApiError from "$api/error";
import log from "$lib/log.js";
export const actions = {
default: async ({ request, fetch, cookies }) => {
const body = await request.formData();
const bio = body.get("bio") as string | null;
try {
await fastRequest("PATCH", "/users/@me", { body: { bio }, fetch, cookies });
return { error: null, ok: true };
} catch (e) {
if (e instanceof ApiError) return { error: e.obj, ok: false };
log.error("Error updating bio:", e);
throw e;
}
},
};

View file

@ -0,0 +1,40 @@
<script lang="ts">
import FormStatusMarker from "$components/editor/FormStatusMarker.svelte";
import { renderMarkdown } from "$lib/markdown";
import { t } from "$lib/i18n";
import type { ActionData, PageData } from "./$types";
type Props = { data: PageData; form: ActionData };
let { data, form }: Props = $props();
let bio = $state(data.user.bio || "");
</script>
<h4>Bio</h4>
<FormStatusMarker {form} />
<form method="POST">
<textarea name="bio" class="form-control" style="height: 200px;" bind:value={bio}></textarea>
<button
disabled={bio.length > data.meta.limits.bio_length}
type="submit"
class="btn btn-primary mt-2 my-1"
>
{$t("save-changes")}
</button>
</form>
<p class="text-muted mt-1">
{$t("edit-profile.bio-length-hint", {
length: bio.length,
maxLength: data.meta.limits.bio_length,
})}
</p>
{#if bio !== ""}
<div class="card">
<div class="card-header">Preview</div>
<div class="card-body">{@html renderMarkdown(bio)}</div>
</div>
{/if}