feat: enhance user experience with tooltips; implement return URL handling on login and registration; add user roles; improve paste visibility checks

This commit is contained in:
2025-12-28 15:31:13 -05:00
parent 4151c62b8c
commit 5fca207ad6
11 changed files with 253 additions and 27 deletions
@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { page } from '$app/stores';
function logout() { function logout() {
localStorage.removeItem('token'); localStorage.removeItem('token');
@@ -8,6 +9,9 @@
user.set(null); user.set(null);
window.location.href = '/'; window.location.href = '/';
} }
$: currentPath = $page.url.pathname;
$: returnParam = currentPath !== '/' ? `?return=${encodeURIComponent($page.url.pathname + $page.url.search)}` : '';
</script> </script>
<div class="fixed top-0 left-0 h-15 w-full bg-neutral-900"> <div class="fixed top-0 left-0 h-15 w-full bg-neutral-900">
@@ -18,15 +22,15 @@
<span class="text-neutral-400">{$user.username}</span> <span class="text-neutral-400">{$user.username}</span>
<button <button
on:click={logout} on:click={logout}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Logout</button class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800 cursor-pointer">Logout</button
> >
</div> </div>
{:else} {:else}
<div class="ml-auto flex items-center space-x-4"> <div class="ml-auto flex items-center space-x-4">
<a href={resolve('/login')} class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800" <a href={resolve('/login') + returnParam} class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
>Login</a >Login</a
> >
<a href={resolve('/register')} class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800" <a href={resolve('/register') + returnParam} class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
>Register</a >Register</a
> >
</div> </div>
+7
View File
@@ -72,3 +72,10 @@ export const displayNames: Record<string, string> = {
}; };
// only include langs that need special display names // only include langs that need special display names
// e.g. cpp -> C++ or toml -> TOML, langs like java are automatically capitalized // e.g. cpp -> C++ or toml -> TOML, langs like java are automatically capitalized
export const roles = {
0: 'User',
1: 'Moderator',
255: 'Administrator',
403: 'Banned'
}
+4
View File
@@ -45,7 +45,11 @@ export async function refreshTokenIfNeeded() {
const data = await res.json(); const data = await res.json();
if (data.token && data.refreshToken) { if (data.token && data.refreshToken) {
setTokens(data.token, data.refreshToken); setTokens(data.token, data.refreshToken);
} else {
clearTokens();
} }
} else {
clearTokens();
} }
} }
} }
+113
View File
@@ -35,3 +35,116 @@ export function dateToRelativeString(date: Date, useSuffix = true): string {
if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''} ${suffix}`; if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''} ${suffix}`;
return `${seconds} second${seconds !== 1 ? 's' : ''} ${suffix}`; return `${seconds} second${seconds !== 1 ? 's' : ''} ${suffix}`;
} }
export function tooltip(node: HTMLElement, text: string) {
let tooltipEl: HTMLDivElement | null;
let caretEl: HTMLDivElement | null;
let showTimeout: ReturnType<typeof setTimeout>;
let hideTimeout: ReturnType<typeof setTimeout>;
function createTooltip() {
const el = document.createElement('div');
el.textContent = text;
el.className =
'fixed z-50 rounded bg-neutral-800 px-2 py-1 text-sm text-white shadow-lg opacity-0 pointer-events-none transition-opacity duration-150';
el.style.maxWidth = '90%';
el.style.wordBreak = 'break-word';
const lines = text.split('\n');
if (lines.length > 1) {
el.innerHTML = '';
lines.forEach((line, index) => {
const lineEl = document.createElement('div');
lineEl.textContent = line;
el.appendChild(lineEl);
if (index < lines.length - 1) {
const br = document.createElement('br');
el.appendChild(br);
}
});
}
const caret = document.createElement('div');
caret.style.position = 'absolute';
caret.style.width = '0';
caret.style.height = '0';
caret.style.left = '50%';
caret.style.transform = 'translateX(-50%)';
caret.style.pointerEvents = 'none';
caretEl = caret;
el.appendChild(caret);
document.body.appendChild(el);
tooltipEl = el;
}
function positionTooltip() {
if (!tooltipEl || !caretEl) return;
const rect = node.getBoundingClientRect();
const tooltipRect = tooltipEl.getBoundingClientRect();
let top = rect.top - tooltipRect.height - 8 + window.scrollY;
let left = rect.left + rect.width / 2 - tooltipRect.width / 2 + window.scrollX;
let caretOnTop = false;
if (top < window.scrollY) {
top = rect.bottom + 8 + window.scrollY;
caretOnTop = true;
}
if (left < 0) left = 8;
if (left + tooltipRect.width > window.innerWidth)
left = window.innerWidth - tooltipRect.width - 8;
tooltipEl.style.top = `${top}px`;
tooltipEl.style.left = `${left}px`;
tooltipEl.style.position = 'absolute';
caretEl.style.top = caretOnTop ? '-7px' : '';
caretEl.style.bottom = caretOnTop ? '' : '-7px';
caretEl.style.borderLeft = '7px solid transparent';
caretEl.style.borderRight = '7px solid transparent';
if (caretOnTop) {
caretEl.style.borderBottom = '7px solid #27272a';
caretEl.style.borderTop = '';
} else {
caretEl.style.borderTop = '7px solid #27272a';
caretEl.style.borderBottom = '';
}
}
function mouseOver() {
clearTimeout(hideTimeout);
showTimeout = setTimeout(() => {
createTooltip();
positionTooltip();
requestAnimationFrame(() => {
if (tooltipEl) tooltipEl.style.opacity = '1';
});
}, 200);
}
function mouseOut() {
clearTimeout(showTimeout);
if (tooltipEl) {
tooltipEl.style.opacity = '0';
hideTimeout = setTimeout(() => {
if (tooltipEl) {
tooltipEl.remove();
tooltipEl = null;
caretEl = null;
}
}, 150);
}
}
node.addEventListener('mouseover', mouseOver);
node.addEventListener('mouseout', mouseOut);
window.addEventListener('scroll', mouseOut, true);
window.addEventListener('resize', mouseOut, true);
return {
destroy() {
node.removeEventListener('mouseover', mouseOver);
node.removeEventListener('mouseout', mouseOut);
window.removeEventListener('scroll', mouseOut, true);
window.removeEventListener('resize', mouseOut, true);
if (tooltipEl) tooltipEl.remove();
}
};
}
@@ -141,6 +141,7 @@
spellcheck="false" spellcheck="false"
autocomplete="off" autocomplete="off"
bind:value={title} bind:value={title}
maxlength={data.options.maxTitleLength ?? 500}
/> />
<textarea <textarea
placeholder="Your paste content here..." placeholder="Your paste content here..."
@@ -148,6 +149,7 @@
spellcheck="false" spellcheck="false"
autocomplete="off" autocomplete="off"
bind:value={content} bind:value={content}
maxlength={data.options.maxContentSize ? Math.floor(data.options.maxContentSize / 4) : undefined}
></textarea> ></textarea>
<Dropdown <Dropdown
options={syntaxOptions} options={syntaxOptions}
+13 -16
View File
@@ -1,12 +1,16 @@
<script lang="ts"> <script lang="ts">
import type { PageData } from './$types'; import type { PageData } from './$types';
import { FileBox, Eye, User, CalendarDays, CalendarOff, Code } from '@lucide/svelte/icons/index'; import { FileBox, Eye, User, CalendarDays, CalendarOff, Code } from '@lucide/svelte/icons/index';
import { formatBytes, extractDateFromUUIDv7, dateToRelativeString } from '$lib/utils/misc'; import {
formatBytes,
extractDateFromUUIDv7,
dateToRelativeString,
tooltip
} from '$lib/utils/misc';
import { displayNames } from '$lib/consts'; import { displayNames } from '$lib/consts';
import { fade } from 'svelte/transition'; import { fade } from 'svelte/transition';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
export let data: PageData; export let data: PageData;
let fileSizeHovered = false;
function addLineNumbers(html: string): string { function addLineNumbers(html: string): string {
const match = html.match(/<pre.*?>[\s\S]*?<code.*?>([\s\S]*?)<\/code><\/pre>/); const match = html.match(/<pre.*?>[\s\S]*?<code.*?>([\s\S]*?)<\/code><\/pre>/);
@@ -31,26 +35,19 @@
class="max-h-[80vh] w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-4" class="max-h-[80vh] w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
> >
{#if data.paste} {#if data.paste}
<h1 class="mb-4 text-center text-4xl font-bold">{data.paste.title || 'Untitled Paste'}</h1> <h1
use:tooltip={data.paste.title || 'Untitled Paste'}
class="mb-4 truncate text-center text-4xl font-bold"
>
{data.paste.title || 'Untitled Paste'}
</h1>
<div class="mb-2 flex flex-wrap items-center justify-center gap-4"> <div class="mb-2 flex flex-wrap items-center justify-center gap-4">
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="relative flex shrink-0 items-center"> <div class="relative flex shrink-0 items-center">
<div <div class="flex" use:tooltip={`True Size: ${formatBytes(data.paste.trueSize)}`}>
class="flex"
on:mouseenter={() => (fileSizeHovered = true)}
on:mouseleave={() => (fileSizeHovered = false)}
>
<FileBox class="mr-2 h-6 w-6 text-neutral-400" /> <FileBox class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{formatBytes(data.paste.size)}</span> <span class="text-neutral-400">{formatBytes(data.paste.size)}</span>
</div> </div>
{#if fileSizeHovered}
<div
class="absolute -top-8 left-1/2 z-10 w-fit -translate-x-1/2 rounded bg-neutral-800 px-2 py-1 text-sm whitespace-nowrap text-white shadow-lg"
transition:fade={{ duration: 150 }}
>
True Size: {formatBytes(data.paste.trueSize)}
</div>
{/if}
</div> </div>
<div class="flex shrink-0 items-center"> <div class="flex shrink-0 items-center">
@@ -17,6 +17,12 @@
setTokens(data.result.token, data.result.refreshToken); setTokens(data.result.token, data.result.refreshToken);
startTokenRefreshInterval(); startTokenRefreshInterval();
} }
const urlParams = new URLSearchParams(window.location.search);
const returnUrl = urlParams.get('return');
if (returnUrl) {
window.location.href = returnUrl;
return;
}
window.location.href = '/'; window.location.href = '/';
} else { } else {
error = 'Invalid username or password'; error = 'Invalid username or password';
@@ -48,9 +48,15 @@
setTokens(data.token, data.refreshToken); setTokens(data.token, data.refreshToken);
startTokenRefreshInterval(); startTokenRefreshInterval();
goto(resolve('/')); goto(resolve('/'));
} else {
const urlParams = new URLSearchParams(window.location.search);
const returnUrl = urlParams.get('return');
if (returnUrl) {
goto(resolve('/login') + `?return=${encodeURIComponent(returnUrl)}`);
} else { } else {
goto(resolve('/login')); goto(resolve('/login'));
} }
}
} else { } else {
error = 'Registration failed'; error = 'Registration failed';
} }
@@ -1,5 +1,6 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { getServerToken } from '$lib/utils/auth'; import { getServerToken } from '$lib/utils/auth';
import type { User } from '$lib/types/user';
export const load: PageServerLoad = async ({ params, fetch, cookies }) => { export const load: PageServerLoad = async ({ params, fetch, cookies }) => {
const { username } = params; const { username } = params;
@@ -9,6 +10,7 @@ export const load: PageServerLoad = async ({ params, fetch, cookies }) => {
Authorization: token ? `Bearer ${token}` : '' Authorization: token ? `Bearer ${token}` : ''
} }
}); });
const user = await res.json();
const user = await res.json() as User;
return { user }; return { user };
} }
@@ -1,7 +1,85 @@
<script lang="ts"> <script lang="ts">
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import type { PageData } from './$types'; import type { PageData } from './$types';
import { User, CalendarDays, ShieldUser, Ban, File, AtSign } from '@lucide/svelte';
import { extractDateFromUUIDv7, tooltip } from '$lib/utils/misc';
import { roles } from '$lib/consts';
export let data: PageData; export let data: PageData;
console.log(data);
</script> </script>
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
<div class="w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="flex items-center justify-center gap-4 text-center text-4xl font-bold">
{#if data.user.roles.includes(1) || data.user.roles.includes(255)}
{#if Math.max(...data.user.roles.filter((r) => r !== 403)) !== -Infinity}
<span
use:tooltip={roles[
Math.max(...data.user.roles.filter((r) => r !== 403)) as keyof typeof roles
]}
>
<ShieldUser class="h-8 w-8 text-neutral-400" />
</span>
{:else}
<span use:tooltip={'User'}>
<User class="h-8 w-8 text-neutral-400" />
</span>
{/if}
{:else if data.user.roles.includes(403)}
<span class="relative flex items-center justify-center" use:tooltip={roles[403]}>
<User class="h-8 w-8 text-neutral-500 opacity-90" />
<Ban class="absolute h-7 w-7 text-red-500" />
</span>
{:else}
<span use:tooltip={'User'}>
<User class="h-8 w-8 text-neutral-400" />
</span>
{/if}
{data.user.displayName || data.user.username}
</h1>
{#if data.user.displayName && data.user.displayName !== data.user.username}
<div class="mb-2 flex items-center justify-center">
<AtSign class="mr-2 inline h-5 w-5 text-neutral-400" />
<span class="text-neutral-400">{data.user.username}</span>
</div>
{/if}
<div class="mb-2 flex flex-wrap items-center justify-center gap-4">
<div class="flex shrink-0 items-center">
<CalendarDays class="mr-2 h-6 w-6 text-neutral-400" />
<span
class="text-neutral-400"
use:tooltip={extractDateFromUUIDv7(data.user.uuid)?.toLocaleString() ?? 'Unknown'}
>
Joined {extractDateFromUUIDv7(data.user.uuid)?.toLocaleDateString() ?? 'Unknown'}
</span>
</div>
<div class="flex shrink-0 items-center">
<File class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{data.user.pastes?.length} paste{data.user.pastes?.length !== 1 ? 's' : ''}</span
>
</div>
</div>
<div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto">
{#if data.user.pastes && data.user.pastes.length > 0}
{#each data.user.pastes as paste}
<a
href={resolve(`/${paste.id}`)}
class="flex flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
>
<span class="truncate text-lg font-semibold text-neutral-100 hover:text-white">
{paste.title || 'Untitled Paste'}
</span>
<p class="text-sm text-neutral-400">
Created on {extractDateFromUUIDv7(paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'}
</p>
</a>
{/each}
{:else}
<p class="text-center text-neutral-400">This user has not created any pastes yet.</p>
{/if}
</div>
</div>
</main>
+7
View File
@@ -45,9 +45,15 @@ namespace SharpbinV3.Server.Controllers
var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString(); var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString();
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID); var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser) if (!isAuthenticatedUser)
{
if (user.Visibility == 1 || user.Visibility == 2)
return NotFound();
else
pasteQuery = pasteQuery.Where(p => p.Visibility == 0); pasteQuery = pasteQuery.Where(p => p.Visibility == 0);
}
var pastes = await pasteQuery.Select(p => new { var pastes = await pasteQuery.Select(p => new {
p.ID,
p.UUID, p.UUID,
p.Title, p.Title,
p.Syntax, p.Syntax,
@@ -79,6 +85,7 @@ namespace SharpbinV3.Server.Controllers
user.Username, user.Username,
user.UUID, user.UUID,
user.DisplayName, user.DisplayName,
user.Roles,
Pastes = pastes Pastes = pastes
}; };
} }