diff --git a/Foxnouns.Backend/Controllers/UsersController.cs b/Foxnouns.Backend/Controllers/UsersController.cs index 1d85c77..33c38d6 100644 --- a/Foxnouns.Backend/Controllers/UsersController.cs +++ b/Foxnouns.Backend/Controllers/UsersController.cs @@ -1,4 +1,5 @@ using System.Diagnostics.CodeAnalysis; +using Coravel.Mailer.Mail.Helpers; using Coravel.Queuing.Interfaces; using EntityFramework.Exceptions.Common; using Foxnouns.Backend.Database; @@ -116,6 +117,42 @@ public class UsersController( if (req.HasProperty(nameof(req.Avatar))) errors.Add(("avatar", ValidationUtils.ValidateAvatar(req.Avatar))); + if (req.HasProperty(nameof(req.MemberTitle))) + { + if (string.IsNullOrEmpty(req.MemberTitle)) + { + user.MemberTitle = null; + } + else + { + errors.Add(("member_title", ValidationUtils.ValidateDisplayName(req.MemberTitle))); + user.MemberTitle = req.MemberTitle; + } + } + + if (req.HasProperty(nameof(req.MemberListHidden))) + user.ListHidden = req.MemberListHidden == true; + + if (req.HasProperty(nameof(req.Timezone))) + { + if (string.IsNullOrEmpty(req.Timezone)) + { + user.Timezone = null; + } + else + { + if (TimeZoneInfo.TryFindSystemTimeZoneById(req.Timezone, out _)) + user.Timezone = req.Timezone; + else + errors.Add( + ( + "timezone", + ValidationError.GenericValidationError("Invalid timezone", req.Timezone) + ) + ); + } + } + ValidationUtils.Validate(errors); // This is fired off regardless of whether the transaction is committed // (atomic operations are hard when combined with background jobs) @@ -253,6 +290,9 @@ public class UsersController( public Pronoun[]? Pronouns { get; init; } public Field[]? Fields { get; init; } public Snowflake[]? Flags { get; init; } + public string? MemberTitle { get; init; } + public bool? MemberListHidden { get; init; } + public string? Timezone { get; init; } } [HttpGet("@me/settings")] diff --git a/Foxnouns.Backend/Database/Migrations/20241124201309_AddUserTimezone.cs b/Foxnouns.Backend/Database/Migrations/20241124201309_AddUserTimezone.cs new file mode 100644 index 0000000..e317f65 --- /dev/null +++ b/Foxnouns.Backend/Database/Migrations/20241124201309_AddUserTimezone.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Foxnouns.Backend.Database.Migrations +{ + /// + [DbContext(typeof(DatabaseContext))] + [Migration("20241124201309_AddUserTimezone")] + public partial class AddUserTimezone : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "timezone", + table: "users", + type: "text", + nullable: true + ); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn(name: "timezone", table: "users"); + } + } +} diff --git a/Foxnouns.Backend/Database/Migrations/DatabaseContextModelSnapshot.cs b/Foxnouns.Backend/Database/Migrations/DatabaseContextModelSnapshot.cs index e1e05c2..d012fe0 100644 --- a/Foxnouns.Backend/Database/Migrations/DatabaseContextModelSnapshot.cs +++ b/Foxnouns.Backend/Database/Migrations/DatabaseContextModelSnapshot.cs @@ -434,6 +434,10 @@ namespace Foxnouns.Backend.Database.Migrations .HasColumnName("sid") .HasDefaultValueSql("find_free_user_sid()"); + b.Property("Timezone") + .HasColumnType("text") + .HasColumnName("timezone"); + b.Property("Username") .IsRequired() .HasColumnType("text") diff --git a/Foxnouns.Backend/Database/Models/User.cs b/Foxnouns.Backend/Database/Models/User.cs index c8c12c5..367e293 100644 --- a/Foxnouns.Backend/Database/Models/User.cs +++ b/Foxnouns.Backend/Database/Models/User.cs @@ -15,6 +15,7 @@ public class User : BaseModel public string? Avatar { get; set; } public string[] Links { get; set; } = []; public bool ListHidden { get; set; } + public string? Timezone { get; set; } public List Names { get; set; } = []; public List Pronouns { get; set; } = []; diff --git a/Foxnouns.Backend/Properties/launchSettings.json b/Foxnouns.Backend/Properties/launchSettings.json index b680651..b9e2ace 100644 --- a/Foxnouns.Backend/Properties/launchSettings.json +++ b/Foxnouns.Backend/Properties/launchSettings.json @@ -4,6 +4,7 @@ "Development": { "commandName": "Project", "dotnetRunMessages": true, + "hotReloadEnabled": false, "launchBrowser": false, "externalUrlConfiguration": true, "environmentVariables": { @@ -13,6 +14,7 @@ "Production": { "commandName": "Project", "dotnetRunMessages": true, + "hotReloadEnabled": false, "launchBrowser": false, "externalUrlConfiguration": true, "environmentVariables": { diff --git a/Foxnouns.Backend/Services/UserRendererService.cs b/Foxnouns.Backend/Services/UserRendererService.cs index c6f9e5b..ceeba94 100644 --- a/Foxnouns.Backend/Services/UserRendererService.cs +++ b/Foxnouns.Backend/Services/UserRendererService.cs @@ -4,6 +4,7 @@ using Foxnouns.Backend.Utils; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using NodaTime; +using Org.BouncyCastle.Ocsp; namespace Foxnouns.Backend.Services; @@ -49,6 +50,13 @@ public class UserRendererService( .ToListAsync(ct) : []; + int? utcOffset = null; + if ( + user.Timezone != null + && TimeZoneInfo.TryFindSystemTimeZoneById(user.Timezone, out var tz) + ) + utcOffset = (int)tz.GetUtcOffset(DateTimeOffset.UtcNow).TotalSeconds; + return new UserResponse( user.Id, user.Sid, @@ -63,6 +71,7 @@ public class UserRendererService( user.Fields, user.CustomPreferences, flags.Select(f => RenderPrideFlag(f.PrideFlag)), + utcOffset, user.Role, renderMembers ? members.Select(m => memberRenderer.RenderPartialMember(m, tokenHidden)) @@ -70,7 +79,8 @@ public class UserRendererService( renderAuthMethods ? authMethods.Select(RenderAuthMethod) : null, tokenHidden ? user.ListHidden : null, tokenHidden ? user.LastActive : null, - tokenHidden ? user.LastSidReroll : null + tokenHidden ? user.LastSidReroll : null, + tokenHidden ? user.Timezone ?? "" : null ); } @@ -115,6 +125,7 @@ public class UserRendererService( IEnumerable Fields, Dictionary CustomPreferences, IEnumerable Flags, + int? UtcOffset, [property: JsonConverter(typeof(ScreamingSnakeCaseEnumConverter))] UserRole Role, [property: JsonProperty(NullValueHandling = NullValueHandling.Ignore)] IEnumerable? Members, @@ -124,7 +135,8 @@ public class UserRendererService( bool? MemberListHidden, [property: JsonProperty(NullValueHandling = NullValueHandling.Ignore)] Instant? LastActive, [property: JsonProperty(NullValueHandling = NullValueHandling.Ignore)] - Instant? LastSidReroll + Instant? LastSidReroll, + [property: JsonProperty(NullValueHandling = NullValueHandling.Ignore)] string? Timezone ); public record AuthMethodResponse( diff --git a/Foxnouns.Frontend/.env.example b/Foxnouns.Frontend/.env.example index d3d5832..d79c672 100644 --- a/Foxnouns.Frontend/.env.example +++ b/Foxnouns.Frontend/.env.example @@ -1,5 +1,7 @@ # Example .env file--DO NOT EDIT PUBLIC_LANGUAGE=en +PUBLIC_BASE_URL=https://pronouns.cc +PUBLIC_SHORT_URL=https://prns.cc PUBLIC_API_BASE=https://pronouns.cc/api PRIVATE_API_HOST=http://localhost:5003/api PRIVATE_INTERNAL_API_HOST=http://localhost:5000/api diff --git a/Foxnouns.Frontend/package.json b/Foxnouns.Frontend/package.json index 69d4a1f..142b442 100644 --- a/Foxnouns.Frontend/package.json +++ b/Foxnouns.Frontend/package.json @@ -38,9 +38,11 @@ "packageManager": "pnpm@9.12.3+sha512.cce0f9de9c5a7c95bef944169cc5dfe8741abfb145078c0d508b868056848a87c81e626246cb60967cbd7fd29a6c062ef73ff840d96b3c86c40ac92cf4a813ee", "dependencies": { "@fontsource/firago": "^5.1.0", + "base64-arraybuffer": "^1.0.2", "bootstrap-icons": "^1.11.3", "luxon": "^3.5.0", "markdown-it": "^14.1.0", + "pretty-bytes": "^6.1.1", "sanitize-html": "^2.13.1", "tslog": "^4.9.3" } diff --git a/Foxnouns.Frontend/pnpm-lock.yaml b/Foxnouns.Frontend/pnpm-lock.yaml index d9bd974..d35d2ed 100644 --- a/Foxnouns.Frontend/pnpm-lock.yaml +++ b/Foxnouns.Frontend/pnpm-lock.yaml @@ -11,6 +11,9 @@ importers: '@fontsource/firago': specifier: ^5.1.0 version: 5.1.0 + base64-arraybuffer: + specifier: ^1.0.2 + version: 1.0.2 bootstrap-icons: specifier: ^1.11.3 version: 1.11.3 @@ -20,6 +23,9 @@ importers: markdown-it: specifier: ^14.1.0 version: 14.1.0 + pretty-bytes: + specifier: ^6.1.1 + version: 6.1.1 sanitize-html: specifier: ^2.13.1 version: 2.13.1 @@ -704,6 +710,10 @@ packages: balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + base64-arraybuffer@1.0.2: + resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==} + engines: {node: '>= 0.6.0'} + bootstrap-icons@1.11.3: resolution: {integrity: sha512-+3lpHrCw/it2/7lBL15VR0HEumaBss0+f/Lb6ZvHISn1mlK83jjFpooTLsMWbIjJMDjDjOExMsTxnXSIT4k4ww==} @@ -1211,6 +1221,10 @@ packages: engines: {node: '>=14'} hasBin: true + pretty-bytes@6.1.1: + resolution: {integrity: sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ==} + engines: {node: ^14.13.1 || >=16.0.0} + punycode.js@2.3.1: resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} engines: {node: '>=6'} @@ -1938,6 +1952,8 @@ snapshots: balanced-match@1.0.2: {} + base64-arraybuffer@1.0.2: {} + bootstrap-icons@1.11.3: {} bootstrap@5.3.3(@popperjs/core@2.11.8): @@ -2432,6 +2448,8 @@ snapshots: prettier@3.3.3: {} + pretty-bytes@6.1.1: {} + punycode.js@2.3.1: {} punycode@2.3.1: {} diff --git a/Foxnouns.Frontend/src/lib/api/models/user.ts b/Foxnouns.Frontend/src/lib/api/models/user.ts index 715cf46..e32873e 100644 --- a/Foxnouns.Frontend/src/lib/api/models/user.ts +++ b/Foxnouns.Frontend/src/lib/api/models/user.ts @@ -1,5 +1,6 @@ export type PartialUser = { id: string; + sid: string; username: string; display_name: string | null; avatar_url: string | null; @@ -14,17 +15,20 @@ export type User = PartialUser & { pronouns: Pronoun[]; fields: Field[]; flags: PrideFlag[]; + utc_offset: number | null; role: "USER" | "MODERATOR" | "ADMIN"; }; export type MeUser = UserWithMembers & { + members: PartialMember[]; auth_methods: AuthMethod[]; member_list_hidden: boolean; last_active: string; last_sid_reroll: string; + timezone: string; }; -export type UserWithMembers = User & { members: PartialMember[] }; +export type UserWithMembers = User & { members: PartialMember[] | null }; export type UserWithHiddenFields = User & { auth_methods?: unknown[]; @@ -38,6 +42,7 @@ export type UserSettings = { export type PartialMember = { id: string; + sid: string; name: string; display_name: string; bio: string | null; diff --git a/Foxnouns.Frontend/src/lib/components/Avatar.svelte b/Foxnouns.Frontend/src/lib/components/Avatar.svelte index 99a5608..31f8355 100644 --- a/Foxnouns.Frontend/src/lib/components/Avatar.svelte +++ b/Foxnouns.Frontend/src/lib/components/Avatar.svelte @@ -1,14 +1,22 @@ + + diff --git a/Foxnouns.Frontend/src/lib/components/editor/AvatarEditor.svelte b/Foxnouns.Frontend/src/lib/components/editor/AvatarEditor.svelte new file mode 100644 index 0000000..5998c9d --- /dev/null +++ b/Foxnouns.Frontend/src/lib/components/editor/AvatarEditor.svelte @@ -0,0 +1,77 @@ + + +

+ +

+ + + + + + +{#if updated} +

+ + {$t("edit-profile.avatar-updated")} +

+{/if} + +{#if avatarTooLarge} +

+ + {$t("edit-profile.file-too-large", { + max: prettyBytes(MAX_AVATAR_BYTES), + current: prettyBytes(avatar.length), + })} +

+{/if} diff --git a/Foxnouns.Frontend/src/lib/components/editor/FormStatusMarker.svelte b/Foxnouns.Frontend/src/lib/components/editor/FormStatusMarker.svelte new file mode 100644 index 0000000..43ca9b9 --- /dev/null +++ b/Foxnouns.Frontend/src/lib/components/editor/FormStatusMarker.svelte @@ -0,0 +1,18 @@ + + +{#if form?.error} + +{:else if form?.ok} +

+ + {$t("edit-profile.saved-changes")} +

+{/if} diff --git a/Foxnouns.Frontend/src/lib/i18n/locales/en.json b/Foxnouns.Frontend/src/lib/i18n/locales/en.json index abc4d85..5c026f9 100644 --- a/Foxnouns.Frontend/src/lib/i18n/locales/en.json +++ b/Foxnouns.Frontend/src/lib/i18n/locales/en.json @@ -1,91 +1,118 @@ { - "hello": "Hello, {{name}}!", - "nav": { - "log-in": "Log in or sign up", - "settings": "Settings" - }, - "avatar-tooltip": "Avatar for {{name}}", - "profile": { - "edit-member-profile-notice": "You are currently viewing the public profile of {memberName}.", - "edit-user-profile-notice": "You are currently viewing your public profile.", - "edit-profile-link": "Edit profile", - "names-header": "Names", - "pronouns-header": "Pronouns", - "default-members-header": "Members", - "create-member-button": "Create member" - }, - "title": { - "log-in": "Log in", - "welcome": "Welcome", - "settings": "Settings" - }, - "auth": { - "log-in-form-title": "Log in with email", - "log-in-form-email-label": "Email address", - "log-in-form-password-label": "Password", - "register-with-email-button": "Register with email", - "log-in-button": "Log in", - "log-in-3rd-party-header": "Log in with another service", - "log-in-3rd-party-desc": "If you prefer, you can also log in with one of these services:", - "log-in-with-discord": "Log in with Discord", - "log-in-with-google": "Log in with Google", - "log-in-with-tumblr": "Log in with Tumblr", - "log-in-with-the-fediverse": "Log in with the Fediverse", - "remote-fediverse-account-label": "Your Fediverse account", - "register-username-label": "Username", - "register-button": "Register account", - "register-with-mastodon": "Register with a Fediverse account", - "log-in-with-fediverse-error-blurb": "Is your instance returning an error?", - "log-in-with-fediverse-force-refresh-button": "Force a refresh on our end" - }, - "error": { - "bad-request-header": "Something was wrong with your input", - "generic-header": "Something went wrong", - "raw-header": "Raw error", - "authentication-error": "Something went wrong when logging you in.", - "bad-request": "Your input was rejected by the server, please check for any mistakes and try again.", - "forbidden": "You are not allowed to perform that action.", - "internal-server-error": "Server experienced an internal error, please try again later.", - "authentication-required": "You need to log in first.", - "missing-scopes": "The current token is missing a required scope. Did you manually edit your cookies?", - "generic-error": "An unknown error occurred.", - "user-not-found": "User not found, please check your spelling and try again. Remember that usernames are case sensitive.", - "member-not-found": "Member not found, please check your spelling and try again.", - "account-already-linked": "This account is already linked with a pronouns.cc account.", - "last-auth-method": "You cannot remove your last authentication method.", - "validation-max-length-error": "Value is too long, maximum length is {{max}}, current length is {{actual}}.", - "validation-min-length-error": "Value is too long, minimum length is {{min}}, current length is {{actual}}.", - "validation-disallowed-value-1": "The following value is not allowed here", - "validation-disallowed-value-2": "Allowed values are", - "validation-reason": "Reason", - "validation-generic": "The value you entered is not allowed here. Reason", - "extra-info-header": "Extra error information" - }, - "settings": { - "general-information-tab": "General information", - "your-profile-tab": "Your profile", - "members-tab": "Members", - "authentication-tab": "Authentication", - "export-tab": "Export your data", - "change-username-button": "Change username", - "username-change-hint": "Changing your username will make any existing links to your or your members' profiles invalid.\nYour username must be unique, be at most 40 characters long, and only contain letters from the basic English alphabet, dashes, underscores, and periods. Your username is used as part of your profile link, you can set a separate display name.", - "username-update-error": "Could not update your username as the new username is invalid:\n{{message}}", - "change-avatar-link": "Change your avatar here", - "new-username": "New username", - "table-role": "Role", - "table-custom-preferences": "Custom preferences", - "table-member-list-hidden": "Member list hidden?", - "table-member-count": "Member count", - "table-created-at": "Account created at", - "table-id": "Your ID", - "table-title": "Account information", - "force-log-out-title": "Log out everywhere", - "force-log-out-button": "Force log out", - "force-log-out-hint": "If you think one of your tokens might have been compromised, you can log out on all devices by clicking this button.", - "log-out-title": "Log out", - "log-out-hint": "Use this button to log out on this device only.", - "log-out-button": "Log out" - }, - "yes": "Yes", - "no": "No" + "hello": "Hello, {{name}}!", + "nav": { + "log-in": "Log in or sign up", + "settings": "Settings" + }, + "avatar-tooltip": "Avatar for {{name}}", + "profile": { + "edit-member-profile-notice": "You are currently viewing the public profile of {memberName}.", + "edit-user-profile-notice": "You are currently viewing your public profile.", + "edit-profile-link": "Edit profile", + "names-header": "Names", + "pronouns-header": "Pronouns", + "default-members-header": "Members", + "create-member-button": "Create member" + }, + "title": { + "log-in": "Log in", + "welcome": "Welcome", + "settings": "Settings" + }, + "auth": { + "log-in-form-title": "Log in with email", + "log-in-form-email-label": "Email address", + "log-in-form-password-label": "Password", + "register-with-email-button": "Register with email", + "log-in-button": "Log in", + "log-in-3rd-party-header": "Log in with another service", + "log-in-3rd-party-desc": "If you prefer, you can also log in with one of these services:", + "log-in-with-discord": "Log in with Discord", + "log-in-with-google": "Log in with Google", + "log-in-with-tumblr": "Log in with Tumblr", + "log-in-with-the-fediverse": "Log in with the Fediverse", + "remote-fediverse-account-label": "Your Fediverse account", + "register-username-label": "Username", + "register-button": "Register account", + "register-with-mastodon": "Register with a Fediverse account", + "log-in-with-fediverse-error-blurb": "Is your instance returning an error?", + "log-in-with-fediverse-force-refresh-button": "Force a refresh on our end" + }, + "error": { + "bad-request-header": "Something was wrong with your input", + "generic-header": "Something went wrong", + "raw-header": "Raw error", + "authentication-error": "Something went wrong when logging you in.", + "bad-request": "Your input was rejected by the server, please check for any mistakes and try again.", + "forbidden": "You are not allowed to perform that action.", + "internal-server-error": "Server experienced an internal error, please try again later.", + "authentication-required": "You need to log in first.", + "missing-scopes": "The current token is missing a required scope. Did you manually edit your cookies?", + "generic-error": "An unknown error occurred.", + "user-not-found": "User not found, please check your spelling and try again. Remember that usernames are case sensitive.", + "member-not-found": "Member not found, please check your spelling and try again.", + "account-already-linked": "This account is already linked with a pronouns.cc account.", + "last-auth-method": "You cannot remove your last authentication method.", + "validation-max-length-error": "Value is too long, maximum length is {{max}}, current length is {{actual}}.", + "validation-min-length-error": "Value is too long, minimum length is {{min}}, current length is {{actual}}.", + "validation-disallowed-value-1": "The following value is not allowed here", + "validation-disallowed-value-2": "Allowed values are", + "validation-reason": "Reason", + "validation-generic": "The value you entered is not allowed here. Reason", + "extra-info-header": "Extra error information" + }, + "settings": { + "general-information-tab": "General information", + "your-profile-tab": "Your profile", + "members-tab": "Members", + "authentication-tab": "Authentication", + "export-tab": "Export your data", + "change-username-button": "Change username", + "username-change-hint": "Changing your username will make any existing links to your or your members' profiles invalid.\nYour username must be unique, be at most 40 characters long, and only contain letters from the basic English alphabet, dashes, underscores, and periods. Your username is used as part of your profile link, you can set a separate display name.", + "username-update-error": "Could not update your username as the new username is invalid:\n{{message}}", + "change-avatar-link": "Change your avatar here", + "new-username": "New username", + "table-role": "Role", + "table-custom-preferences": "Custom preferences", + "table-member-list-hidden": "Member list hidden?", + "table-member-count": "Member count", + "table-created-at": "Account created at", + "table-id": "Your ID", + "table-title": "Account information", + "force-log-out-title": "Log out everywhere", + "force-log-out-button": "Force log out", + "force-log-out-hint": "If you think one of your tokens might have been compromised, you can log out on all devices by clicking this button.", + "log-out-title": "Log out", + "log-out-hint": "Use this button to log out on this device only.", + "log-out-button": "Log out", + "avatar": "Avatar", + "username-update-success": "Successfully changed your username!" + }, + "yes": "Yes", + "no": "No", + "edit-profile": { + "user-header": "Editing your profile", + "general-tab": "General", + "names-pronouns-tab": "Names & pronouns", + "file-too-large": "This file is too large, please resize it (maximum is {{max}}, the file you're trying to upload is {{current}})", + "sid-current": "Current short ID:", + "sid": "Short ID", + "sid-reroll": "Reroll short ID", + "sid-hint": "This ID is used in prns.cc links. You can reroll one short ID every hour (shared between your main profile and all members) by pressing the button above.", + "sid-copy": "Copy short link", + "update-avatar": "Update avatar", + "avatar-updated": "Avatar updated! It might take a moment to be reflected on your profile.", + "member-header-label": "\"Members\" header text", + "member-header-info": "This is the text used for the \"Members\" heading. If you leave it blank, the default text will be used.", + "hide-member-list-label": "Hide member list", + "timezone-label": "Timezone", + "timezone-preview": "This will show up on your profile like this:", + "timezone-info": "This is optional. Your timezone is never shared directly, only the difference between UTC and your current timezone is.", + "hide-member-list-info": "This only hides your member list. Individual members will still be visible to anyone with a direct link to their pages.", + "profile-options-header": "Profile options", + "bio-tab": "Bio", + "saved-changes": "Successfully saved changes!", + "bio-length-hint": "Using {{length}}/{{maxLength}} characters" + }, + "save-changes": "Save changes" } diff --git a/Foxnouns.Frontend/src/routes/+layout.server.ts b/Foxnouns.Frontend/src/routes/+layout.server.ts index 00c3ef3..82f3cb2 100644 --- a/Foxnouns.Frontend/src/routes/+layout.server.ts +++ b/Foxnouns.Frontend/src/routes/+layout.server.ts @@ -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("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("GET", "/meta", { fetch, cookies }); - return { meta, meUser }; + return { meta, meUser, token }; }) satisfies LayoutServerLoad; diff --git a/Foxnouns.Frontend/src/routes/@[username]/+page.server.ts b/Foxnouns.Frontend/src/routes/@[username]/+page.server.ts index 330bd21..6c582bc 100644 --- a/Foxnouns.Frontend/src/routes/@[username]/+page.server.ts +++ b/Foxnouns.Frontend/src/routes/@[username]/+page.server.ts @@ -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("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 }; diff --git a/Foxnouns.Frontend/src/routes/settings/+layout.server.ts b/Foxnouns.Frontend/src/routes/settings/+layout.server.ts index a1ac93c..fe2eaa3 100644 --- a/Foxnouns.Frontend/src/routes/settings/+layout.server.ts +++ b/Foxnouns.Frontend/src/routes/settings/+layout.server.ts @@ -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! }; }; diff --git a/Foxnouns.Frontend/src/routes/settings/+page.svelte b/Foxnouns.Frontend/src/routes/settings/+page.svelte index 062d9e6..cfd0b88 100644 --- a/Foxnouns.Frontend/src/routes/settings/+page.svelte +++ b/Foxnouns.Frontend/src/routes/settings/+page.svelte @@ -29,7 +29,8 @@ {#if form?.ok}

- Successfully changed your username! + + {$t("settings.username-update-success")}

{:else if usernameError}

@@ -46,7 +47,7 @@

-
Avatar
+
{$t("settings.avatar")}
+ 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; + + +

{$t("edit-profile.user-header")}

+ diff --git a/Foxnouns.Frontend/src/routes/settings/profile/+page.server.ts b/Foxnouns.Frontend/src/routes/settings/profile/+page.server.ts new file mode 100644 index 0000000..2233626 --- /dev/null +++ b/Foxnouns.Frontend/src/routes/settings/profile/+page.server.ts @@ -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; + } + }, +}; diff --git a/Foxnouns.Frontend/src/routes/settings/profile/+page.svelte b/Foxnouns.Frontend/src/routes/settings/profile/+page.svelte new file mode 100644 index 0000000..5b00f0c --- /dev/null +++ b/Foxnouns.Frontend/src/routes/settings/profile/+page.svelte @@ -0,0 +1,190 @@ + + +{#if error} + +{/if} + +
+
+

{$t("settings.avatar")}

+ +
+
+

{$t("edit-profile.sid")}

+ {$t("edit-profile.sid-current")} {sid} + + + + +

+ + {$t("edit-profile.sid-hint")} +

+
+
+ +
+

{$t("edit-profile.profile-options-header")}

+ +
+
+ + +

+ + {$t("edit-profile.member-header-info")} +

+
+
+ + + + + {#each validTimezones as timezone}{/each} + + + + {#if tz && tz !== "" && validTimezones.includes(tz)} +
+ {$t("edit-profile.timezone-preview")} + + {currentTime} (UTC{displayTimezone}) +
+ {/if} +

+ + {$t("edit-profile.timezone-info")} +

+
+
+ + +
+

+ + {$t("edit-profile.hide-member-list-info")} +

+
+ +
+
+
diff --git a/Foxnouns.Frontend/src/routes/settings/profile/bio/+page.server.ts b/Foxnouns.Frontend/src/routes/settings/profile/bio/+page.server.ts new file mode 100644 index 0000000..bb86f7e --- /dev/null +++ b/Foxnouns.Frontend/src/routes/settings/profile/bio/+page.server.ts @@ -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; + } + }, +}; diff --git a/Foxnouns.Frontend/src/routes/settings/profile/bio/+page.svelte b/Foxnouns.Frontend/src/routes/settings/profile/bio/+page.svelte new file mode 100644 index 0000000..c3ac2fe --- /dev/null +++ b/Foxnouns.Frontend/src/routes/settings/profile/bio/+page.svelte @@ -0,0 +1,40 @@ + + +

Bio

+ + + +
+ + +
+ +

+ {$t("edit-profile.bio-length-hint", { + length: bio.length, + maxLength: data.meta.limits.bio_length, + })} +

+ +{#if bio !== ""} +
+
Preview
+
{@html renderMarkdown(bio)}
+
+{/if} diff --git a/package.json b/package.json index 50681f6..db48a60 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,8 @@ "concurrently": "^9.0.1" }, "scripts": { - "dev": "concurrently -n .net,node,rate -c magenta,yellow,blue -i 'cd Foxnouns.Backend && dotnet watch --no-hot-reload' 'cd Foxnouns.Frontend && pnpm dev' 'cd rate && go run -v .'", + "dev": "concurrently -n .net,node,rate -c magenta,yellow,blue -i 'pnpm watch:be' 'cd Foxnouns.Frontend && pnpm dev' 'cd rate && go run -v .'", + "watch:be": "dotnet watch --no-hot-reload --project Foxnouns.Backend -- --migrate-and-start", "format": "dotnet csharpier . && cd Foxnouns.Frontend && pnpm format" }, "packageManager": "pnpm@9.12.3+sha512.cce0f9de9c5a7c95bef944169cc5dfe8741abfb145078c0d508b868056848a87c81e626246cb60967cbd7fd29a6c062ef73ff840d96b3c86c40ac92cf4a813ee"